Data Structures & AlgorithmsVery hardGATE CS · TCS NQT
Which algorithm counts occurrences of a pattern p inside a text t in O(|t| + |p|) time?
- A. Naive nested loop search
- B. KMP (prefix-function) search
- C. Binary search on the text
- D. Sorting both strings
Correct answer: B. KMP (prefix-function) search
KMP never re-reads text characters, so it runs in linear time. The naive search is O(|t| * |p|) in the worst case.
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
- Which algorithm finds the longest palindromic substring of a string in linear time?
- Which technique detects whether an array contains a non-empty subarray with sum zero in O(n) expected time?
- An array of 200000 integers may contain negative values, and you must count its contiguous subarrays whose sum equals K in near-linear…
- For a string of length 10^6 and a pattern of 20 letters, you need the shortest substring containing every pattern letter with…
- Given an array of 10^6 values and window size k, you need the maximum over all windows of the window minimum. What is the most suitable…
- How many contiguous subarrays of [1, 2, 1, 3, 2, 2, 1] contain at most two distinct values?