Data Structures & AlgorithmsVery hardTCS NQT Digital · Product Company SDE
Problem: A string s (length n) must be searched for a pattern p (length m) in text. Which algorithm guarantees O(n+m) worst-case time regardless of the text/pattern content?
- A. Rabin-Karp with a weak hash and no collision check
- B. Naive sliding comparison of the pattern at every position
- C. Sorting both strings and comparing
- D. Knuth-Morris-Pratt (KMP), using the pattern's failure function to avoid re-scanning
Correct answer: D. Knuth-Morris-Pratt (KMP), using the pattern's failure function to avoid re-scanning
KMP precomputes the longest-prefix-suffix (failure) function in O(m), then scans the text once in O(n), never re-examining a text character on a mismatch, giving O(n+m) worst case.
More Coding Interview Problems questions
- Problem: Rabin-Karp pattern matching uses a rolling hash to compare a pattern against every window of the text. What is its typical time…
- 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?