Data Structures & AlgorithmsVery hard
In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?
- A. Every element needs exactly one swap regardless of cycles.
- B. The answer is the number of inversions in the permutation.
- C. The answer equals the length of the longest increasing subsequence.
- D. Each cycle of length L can be sorted with L−1 swaps, and the total over all cycles is n minus the cycle count.
Correct answer: D. Each cycle of length L can be sorted with L−1 swaps, and the total over all cycles is n minus the cycle count.
Within a cycle of length L, L−1 swaps place every element, and the cycles are independent, so the swap counts add. Counting inversions measures a different quantity.
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 statement about a monotonic deque for sliding-window minimum is correct?
- Why is prefix-sum counting of zero-sum subarrays unaffected by the choice of starting index for the prefix array?
- For the sum-at-most-K problem on a prefix-sum array with negative values, why does a balanced search structure appear in the solution?
- The shunting-yard algorithm converts the infix expression "a+bc^d^e-f^(gh)" to postfix, with ^ highest precedence and right-associative…
- What is the largest rectangular area in a histogram with bar heights 6, 2, 5, 4, 5, 1, 6 (each bar has width 1)?
- In the undirected graph with edges (1,2), (1,3), (2,4), (3,4), (4,5), (3,6), how many vertices are at shortest-path distance exactly 2…