Data Structures & AlgorithmsHardGATE CS · ICPC regional
Which quantity gives the minimum number of arbitrary swaps needed to sort a permutation, and why is it correct?
- A. Number of inversions, because each swap removes exactly one inversion
- B. n minus the number of cycles, because each swap changes the cycle count by at most one
- C. Number of fixed points, because each swap fixes one element
- D. Sum of displacements divided by two, because swaps move two elements
Correct answer: B. n minus the number of cycles, because each swap changes the cycle count by at most one
A swap can split a cycle or merge two cycles, changing the cycle count by one; a sorted permutation has n cycles of length one. Inversions are only the answer for adjacent swaps.
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
- Counting ways to pay each amount 0..9 with coins [1, 4, 6]: version A loops over amounts (outer) and coins (inner), counting ordered…
- For the array [4, 2, 5, 3, 1, 6, 0], a 'next greater element' routine returns for each index the value of the next strictly larger element…
- A routine builds a list t: for each x in a, it appends x to t only if x is larger than the last element of t (otherwise it skips x), and…
- Items as (weight, value) are [(2, 3), (3, 4), (1, 1)]. The 0/1 knapsack table dp[c] for capacities c = 0..6 is built correctly by scanning…
- Intervals [(1, 6), (2, 4), (3, 9), (5, 7), (8, 10), (4, 5)] are given as closed ranges. You must remove the fewest intervals so that no…
- How many non-empty contiguous subarrays of [1, -1, 2, 0, 1, 3, -2, 1] have a sum equal to their length (number of elements)? Transform…