Data Structures & AlgorithmsHardAmazon · Microsoft coding round
Problem: Rabin-Karp pattern matching uses a rolling hash to compare a pattern against every window of the text. What is its typical time complexity, and when does it degrade?
- A. O(n+m) on average; degrades to O(nm) worst case under many hash collisions
- B. O(n log m) always, using binary search on hash values
- C. O(nm) always, regardless of hashing
- D. O(log n) because hashing is constant time
Correct answer: A. O(n+m) on average; degrades to O(nm) worst case under many hash collisions
Hashing lets most mismatching windows be rejected in O(1), giving O(n+m) on average, but an adversarial input causing many hash collisions forces full O(m) character checks at each position, degrading to O(nm).
More Coding Interview Problems questions
- Problem: Which traversal order is guaranteed to visit nodes level by level in a tree or graph?
- Problem: For a weighted graph with all non-negative edge weights, which algorithm finds shortest paths from a single source, and in what…
- Problem: A graph may contain negative edge weights but no negative cycle. Which single-source shortest path algorithm handles this…
- Problem: What is the time complexity of the Floyd-Warshall algorithm for finding shortest paths between every pair of nodes in a graph…
- Problem: Which of these best describes why Kruskal's MST algorithm needs a Union-Find (disjoint set) structure?
- Problem: Between Kruskal's and Prim's MST algorithms, which is typically preferred for a dense graph represented with an adjacency matrix?