← Learning Hub
Beginner

String Problems

Strings are like arrays of characters. In Python they can't be changed in place, so build a list and join it, or make a new string.

Strings are arrays of characters, so array techniques apply, plus a few special tricks: counting characters, comparing reversed text, and building results efficiently. Palindromes, anagrams and substring problems are interview favourites.

Palindrome

Example
You can edit this code.

Count characters

Example
You can edit this code.

Reverse the words

Example
You can edit this code.
Adding to a string in a loop (s = s + ch) can be O(n²) because each step copies the string. Collect pieces in a list and "".join() once.
Key points
  • Strings can be treated like arrays of characters.
  • Counting characters solves anagram problems.
  • Build results with a list and join, not repeated +.

📝 Test yourself

1. Why build a list and join it instead of s = s + ch in a loop?
2. What does Counter('aab') give for 'a'?
3. Fill in the method that splits a sentence into words:
words = sentence.()