Bits and string matching · senior
String matching: indexOf, KMP and safe regex
Finding a pattern in text is O(n·m) done naively, O(n + m) with KMP's prefix function, and in UI code it usually means indexOf or a RegExp built from user input, which must be escaped first.
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: includes/indexOf/startsWith are fine in real code; in an interview say their worst case and offer KMP if asked for guaranteed O(n + m).
- KMP prefix function pi[i] = 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.
- Search = prefix function of pattern + '\u0000' + text (separator must not appear), or a separate matching loop.
- Repeated substring pattern: s is a repetition iff (s + s).slice(1, −1) includes s, or n % (n − pi[n − 1]) === 0 with pi[n − 1] > 0.
- Rabin–Karp: rolling hash, compare hashes then verify characters; good for many patterns.
- Highlighting a user's query: escape regex special characters (. * + ? ^ $ { } ( ) | [ ] ) before new RegExp(query, 'gi'), or avoid regex and use indexOf on lower-cased strings.
The red pen
Common traps: mistake → fix
Mistake: new RegExp(userInput) is safe
Fix: '(' throws and '.*' matches everything; escape first.
Mistake: KMP is needed in UI code
Fix: indexOf is fine; KMP is an interview tool.
Mistake: Lower-casing makes all matching correct
Fix: some languages change length when case-folded; mention locale and normalize().
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 the search query inside suggestion 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.