Data Structures & AlgorithmsHardGATE CS · DSA
Rabin–Karp with a good rolling hash is used to find a pattern of length m in a text of length n. Which statement is correct?
- A. O(n log m) because the rolling hash needs a logarithm
- B. Expected O(n + m), but O(nm) in the worst case when many windows produce hash collisions
- C. Always O(nm)
- D. Always O(n + m) because hashes are compared in O(1)
Correct answer: B. Expected O(n + m), but O(nm) in the worst case when many windows produce hash collisions
Rolling the hash costs O(1) per shift, but each hash hit must be verified character by character; adversarial or unlucky collisions can force Θ(m) checks at most positions.
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
- Reverse the order of words, collapsing multiple spaces. What is printed? python s = " the is new code " w = s.split() print("|" + "…
- Rabin–Karp with base 10 and a deliberately small modulus counts true matches and spurious hits (hash equal, text different). What is…
- 11 people stand in a circle numbered 1 to 11. Counting starts at person 1, and every 4th person is removed (counting continues from the…
- Kadane's algorithm runs on [−4, −7, 9, 3, −5, 4, 1, 4, 8]. What is the maximum sum of a non-empty contiguous subarray?
- How many contiguous subarrays of [3, 2, −3, 5, 2, −1, 0, 1, 2] have sum exactly 3? (Prefix sums with a hash map of prefix-sum frequencies.)
- How many pairs (i < j) of [6, 27, 29, 25, 10, 6, 25, 3, 7, 22] have a[i] + a[j] divisible by 6? (Count remainders mod 6 and pair r with 6…