Bits and string matching · senior
String matching: built-ins, KMP and safe patterns
Finding a pattern in text is O(n·m) done naively and O(n + m) with KMP's prefix function. In real code, use the built-in find, and never build a regular expression from user input without escaping it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Built-ins: Java String.indexOf and contains, Python str.find and the 'in' operator, C++ std::string::find; in an interview say the naive worst case (O(n·m), for example 'aaaa...ab' in 'aaaa...a') and offer KMP if asked for a guaranteed O(n + m).
- KMP prefix function pi[i] = the length of the longest proper prefix of s[0..i] that is also a suffix. On a mismatch, jump k = pi[k - 1] instead of restarting from 0.
- Search = prefix function of pattern + a separator + text (the separator must not appear in either), or a separate matching loop that reuses pi.
- Repeated substring pattern: s is a repetition if n % (n - pi[n - 1]) == 0 and pi[n - 1] > 0; or if s appears inside (s + s) with the first and last character removed.
- Rabin-Karp: a rolling hash, compare hashes, then verify the characters; good for many patterns. Keep the hash in a 64-bit type and take a modulus, or it overflows.
- Searching user text: do not build a pattern from it unless you escape it (Java Pattern.quote, Python re.escape); or use plain find on lower-cased strings.
The red pen
Common traps: mistake → fix
Mistake: Building a regular expression from user input is safe
Fix: '(' is an error and '.*' matches everything; escape first.
Mistake: KMP is needed in everyday code
Fix: the built-in find is fine; KMP is an interview tool.
Mistake: Lower-casing makes all matching correct
Fix: some languages change the length when case-folded; mention the locale and Unicode normalisation.
Easy to hard
Questions interviewers ask, easy to hard
- Find the first index of needle in haystack.
- What is the worst case of the naive approach? Give an example.
- Explain the KMP prefix function.
- Highlight a search query inside a text safely.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.