š¤ String Manipulation
You're validating user input - checking if a phrase is a palindrome, ignoring spaces and punctuation. String problems are everywhere in interviews. Let's master the essential patterns.
String Fundamentals
Strings are immutable in most languages - you can't change them in place. This affects how you solve problems.
Immutability
s = "hello"
s[0] = 'H' # Error! Can't modify
# Create new string instead
s = 'H' + s[1:] # "Hello"
Impact: String concatenation in loops is O(n²) because each concatenation creates a new string!
Solution: Use a list/array and join at the end.
Click Run to execute your code
Quick Quiz
-
Why is string concatenation in a loop slow?
Show answer
Because strings are immutable, each concatenation creates a new string and copies all characters. For n concatenations, that's 1+2+3+...+n = O(n²) operations! -
How do you efficiently build a string?
Show answer
Use a list to collect parts, then join once at the end:''.join(parts)- this is O(n) instead of O(n²).
Five Essential Patterns
Click Run to execute your code
| Pattern | Technique | Complexity | Example |
|---|---|---|---|
| Two Pointers | Work from both ends | O(n) | Palindrome, reverse |
| Hash Map | Count frequencies | O(n) | Anagrams, unique chars |
| Sliding Window | Variable substring | O(n) | Longest substring |
| String Building | List + join | O(n) | Compression, reversal |
| Pattern Matching | Substring search | O(nĆm) | Find substring |
Pattern Selection Guide
Choose Your Pattern
- Palindrome/Reverse: Two pointers
- Anagram/Frequency: Hash map
- Longest/Shortest substring: Sliding window
- Build/Modify string: List + join
- Find pattern: Built-in search or KMP (advanced)
Common Mistakes
ā String Concatenation in Loop
# Slow: O(n²)
result = ""
for char in s:
result += char # Creates new string each time!
# Fast: O(n)
result = ''.join(s)
ā Forgetting to Handle Empty Strings
def first_char(s):
return s[0] # Error if s is empty!
# Better
def first_char(s):
return s[0] if s else None
ā Case Sensitivity Issues
# "Hello" != "hello"
# Always normalize case first
s1.lower() == s2.lower()
Summary
The 3-Point String Guide
- Immutability: Strings can't be modified - use list + join for building
- Patterns: Two pointers, hash map, sliding window - same as arrays!
- Efficiency: Avoid concatenation in loops - it's O(n²)
Interview tip: Most string problems use the same patterns as array problems. Think: "How would I solve this with an array?"
What's Next?
š Congratulations! You've completed Module 2: Arrays & Strings!
You Now Know:
- ā Array fundamentals and O(1) access
- ā Two pointers technique
- ā Sliding window pattern
- ā String manipulation
These patterns solve 50%+ of interview array/string problems!
Next up: Module 3: Linked Lists - learn pointer-based data structures and solve problems like reversing lists, detecting cycles, and more!
Enjoying these tutorials?