🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

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 needle in haystack, 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 s and t, return true if t is an anagram of s.

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 s and a window size k, return a list of hashes for each window of size k in 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

In valid anagram checking, why does a 26-element frequency array work even if the alphabet has millions of Unicode characters?
In the string compression problem, why is the two-pointer approach (read pointer i, write pointer write) necessary?

Next: the ten practice problems — every algorithm in the chapter represented, in order of difficulty.