Data Structures & AlgorithmsVery hardGATE CS · ICPC regional
What is the minimum number of swaps of two (not necessarily adjacent) elements needed to sort the permutation [4, 2, 5, 1, 3] (0-based indices shifted so the values are 0 to 4)?
- A. 2
- B. 3
- C. 4
- D. 6
Correct answer: A. 2
The minimum number of swaps equals n minus the number of cycles of the permutation. Counting inversions gives a different number, which is not the right measure for arbitrary 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
- Which quantity gives the minimum number of arbitrary swaps needed to sort a permutation, and why is it correct?
- 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…