Basic String Questions
Six warm-ups. The first two are direct applications of algorithms from this chapter; the rest are building-block patterns you need to have in muscle memory before attempting the practice problems.
1. Implement strStr (naive, then KMP)
Return the index of the first occurrence of
needleinhaystack, or -1 if not found.
Start with the naive implementation for clarity, then upgrade to KMP.
Naive O(nm):
KMP O(n + m):
Time: O(n + m) KMP. Space: O(m).
2. Valid Anagram
Given two strings
sandt, return true iftis an anagram ofs.
Anagram = same characters with the same frequencies. Classic frequency-array trick.
Time: O(n). Space: O(1) — the 26-element array is constant-size.
3. String compression (run-length encoding)
Compress
['a','a','b','b','c','c','c']to['a','2','b','2','c','3']in-place. If compressed length is not shorter, return the original.
Classic two-pointer compression.
Time: O(n). Space: O(1) extra.
The two-pointer structure (read at i, write at write) is the template for all in-place string mutation problems.
4. Reverse words in a string
Given
" the sky is blue ", return"blue is sky the"— reverse word order, strip extra spaces.
Classic three-step approach: reverse all chars, then reverse each word.
Time: O(n). Space: O(n) for the word list.
5. Longest common prefix
Given
["flower","flow","flight"], return"fl".
Vertical scan: compare the k-th character across all strings.
Time: O(S) where S is total characters across all strings. Space: O(1) extra.
6. Rolling hash from scratch
Implement a rolling hash: given
sand a window sizek, return a list of hashes for each window of sizekin O(n) total.
This locks in the Rabin-Karp computation before the practice problems.
Time: O(n). Space: O(n) for output, O(1) rolling work.
Mini-quiz
Next: the ten practice problems — every algorithm in the chapter represented, in order of difficulty.