Data Structures & AlgorithmsModerateCodeforces Div2 C · permutations
Problem: Which algorithm is the standard way to find the minimum number of swaps to sort a permutation?
- A. Count inversions only
- B. Dijkstra on positions
- C. Binary search on the answer
- D. Count cycles: swaps = n - (number of cycles)
Correct answer: D. Count cycles: swaps = n - (number of cycles)
Each cycle of length c needs c - 1 swaps, so the total is n minus the number of cycles.
More Coding Interview Problems questions
- Problem: What is the complexity of binary exponentiation for computing a^b mod m?
- Problem: What property of an array makes the two-pointer technique for pair sums valid?
- Problem: What is the purpose of a 'segment tree beats' structure?
- Problem: What is the number of comparisons needed in the worst case to check whether a sorted array of n elements contains a given value…
- Problem: What is the greedy choice used in the 'minimum number of arrows to burst balloons' problem?
- Problem: Which problem is solved by the Gale-Shapley algorithm in O(n^2) time with preference lists?