Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees the best worst-case time?
- A. Naive sliding comparison – O(n + m) in the worst case
- B. Rabin–Karp – O(n + m) guaranteed in the worst case
- C. KMP (prefix function) – O(n + m)
- D. Sorting all suffixes – O(n) worst case
Correct answer: C. KMP (prefix function) – O(n + m)
KMP never re-reads text characters, giving O(n + m) worst case. The naive method is O(nm) worst case (text 'aaaa…', pattern 'aa…ab'). Rabin–Karp is O(n + m) expected but O(nm) worst case if many hash collisions must be verified. Building a suffix array is O(n log n) or more.
More Coding Interview Problems questions
- Problem: Return the longest palindromic substring of s (first one if there is a tie). python def lps(s): best = "" for c in range(len(s))…
- Problem: Check whether a string of brackets ()[]{} is balanced. python def balanced(s): pair = {')': '(', ']': '[', '}': '{'} st = [] for…
- Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never). python def wait(t): res, st = [0]…
- Problem: Find the largest rectangle that fits under a histogram of bar heights. python def largest(h): st, best = [], 0 for i, x in…
- Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero. python def rpn(tokens): st = [] for t in…
- Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode…