Data Structures & AlgorithmsVery hard
When merging two sorted lists with the standard two-pointer method, how many comparisons are made in the worst case?
- A. At most n + m − 1 comparisons, since each comparison outputs one element and the last element needs no comparison.
- B. Exactly n·m comparisons.
- C. Exactly log(n + m) comparisons.
- D. Exactly n comparisons regardless of m.
Correct answer: A. At most n + m − 1 comparisons, since each comparison outputs one element and the last element needs no comparison.
Each comparison emits one element, and once one list is exhausted the rest is copied without comparisons. The worst case therefore uses at most n + m − 1 comparisons.
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
- When computing the k-th smallest element of two sorted arrays, why can a binary search on the answer's position replace a full merge?
- Why do the positions of a stable partition by parity keep their relative order, and why is that important?
- The sorted array [2, 3, 4, 7, 11] contains some positive integers. What is the 5th positive integer that does NOT appear in this array?
- In how many ways can you choose 3 indices from the 9 positions 1 to 9 so that no two chosen positions are adjacent (consecutive integers)?
- What is the length of the longest contiguous subarray of [4, 7, 5, 6, 8, 9, 7, 6, 3, 4] in which the largest value minus the smallest…
- How many contiguous subarrays of [3, 1, 3, 2, 3, 1] have their maximum value occurring EXACTLY twice inside the subarray?