Implement string matching with follow-up
DoorDashSoftware Engineer · Technical ScreenLast updated
A DoorDash software-engineer coding screen on string matching: implement firstIndex(T, P) in O(|T| + |P|) time and O(|P|) space using KMP, then handle follow-ups on naive vs KMP vs Rabin–Karp, Unicode and very long inputs, edge cases, wildcard ('?'/'*') matching, and simultaneous multi-pattern search via Aho–Corasick. Includes corrected, complete solutions and complexity trade-offs.
Question
Given a text T and a pattern P, implement a function firstIndex(T, P) that returns the starting index of the first occurrence of P in T, or -1 if P does not occur. Aim for O(|T| + |P|) time and O(|P|) extra space.
Be ready to extend the solution through the following follow-ups:
- Algorithm comparison. Compare the naive (brute-force) approach to KMP and Rabin–Karp. Explain the time and space complexity of each and when you would choose one over another.
- Robustness. How would you handle Unicode text (multi-byte / combining characters) and very long inputs? Discuss correctness and memory considerations.
- Edge cases. Walk through the important edge cases: empty pattern, empty text, pattern longer than text, and highly repetitive patterns (e.g.
P = "aaaa"inT = "aaaaaa"). - Wildcards. Extend the matcher to support two wildcard characters in the pattern:
?matches any single character, and*matches any (possibly empty) sequence of characters. Describe the matching semantics and complexity. - Multi-pattern search. Extend the solution to search for
kpatternsP1..PkinTsimultaneously and return all starting indices for each pattern. Outline the data structure you would use and the runtime / space trade-offs versus running a single-pattern matcherktimes.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.