Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft
A string of length n is searched for a pattern of length m. What are the worst-case times of the naive algorithm and of KMP?
- A. O(nm) and O(nm)
- B. O(n log n) and O(n + m)
- C. O(n + m) and O(n log m)
- D. O(nm) and O(n + m)
Correct answer: D. O(nm) and O(n + m)
The naive method can re-compare up to m characters at each of n − m + 1 shifts. KMP never moves the text pointer backwards and builds its failure table in O(m).
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
- How many inversions (pairs i < j with a[i] > a[j]) does [35, 33, 31, 3, 20, 18, 13, 4] have? (This is also the number of swaps bubble sort…
- The Dutch national flag algorithm (pointers low, mid, high; 0 → swap with low and advance both; 1 → advance mid; 2 → swap with high and…
- A mountain is a contiguous subarray of length ≥ 3 that strictly increases to a single peak and then strictly decreases. What is the length…
- For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed? python…
- Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?…
- An array holds n distinct elements. What is the minimum number of comparisons that ANY comparison-based algorithm needs, in the worst…