Data Structures & AlgorithmsHard
Why does the cycle-based 'place each value at its index' method find missing numbers in linear time?
- A. The method sorts the array in quadratic time.
- B. Missing values are removed from the array first.
- C. Each element is compared with every other element.
- D. Each swap puts one value in its final position and never moves it again, so the total number of swaps is bounded by n.
Correct answer: D. Each swap puts one value in its final position and never moves it again, so the total number of swaps is bounded by n.
A correctly placed value is never disturbed again, so each swap fixes at least one position and the total work is linear. Positions left wrong then reveal the missing values.
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
- Why does Floyd's method for finding a duplicate in an array of n+1 values in 1..n view the array as a linked structure?
- Stable sorting by two keys works by sorting twice. Which order of passes gives the lexicographic order with the first key as primary?
- Why does the median of two sorted arrays of sizes m and n not require merging both arrays fully?
- Which property makes the number of inversions of a rotated sorted array equal to a simple product?
- When merging two sorted lists with the standard two-pointer method, how many comparisons are made in the worst case?
- 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?