Data Structures & AlgorithmsModerateGATE CS · TCS NQT
Consider the pattern-matching algorithms: naive, KMP, Rabin–Karp (polynomial rolling hash), Z-function. Which statement is correct?
- A. KMP finds all occurrences of a pattern in O(n + m) time, without backtracking the text
- B. Rabin–Karp always runs in O(n + m) because it never compares characters
- C. The naive algorithm is O(n + m) on every input because it stops at the first mismatch
- D. The Z-function needs a separate pass over the text for every pattern letter
Correct answer: A. KMP finds all occurrences of a pattern in O(n + m) time, without backtracking the text
KMP uses the prefix function to skip ahead, so the text pointer never moves backwards and the total work is O(n + m). Rabin–Karp needs character checks on hash matches to rule out collisions, and the naive method can take O(nm) time.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A polynomial rolling hash with a fixed modulus M and random base B is used to compare two different strings of length L. Which statement…
- What is the length of the longest palindromic substring of "bananaracecarbnn"?
- Apply the reversal of the first 4 elements to the queue 1, 2, 3, 4, 5, 6, 7, 8 (front first). What is the element at position 6 of the…
- For the array [1, 3, 2, 4], take the next strictly greater element of each position (-1 if none) and sum these values, ignoring the -1…
- What is the sum of the minimum of every contiguous window of length 2 in the array [3, 1, 4, 1, 5, 9, 2, 6]?
- A singly linked list contains the people 1 to 12 in a circle. Starting from person 1, every 4th person is removed (the count starts at 1)…