Data Structures & AlgorithmsHardCodeforces Div2 C · permutations
Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle decomposition code below.
Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle decomposition code below.
p = [3, 2, 1, 0]
seen = [False] * len(p)
swaps = 0
for i in range(len(p)):
if not seen[i]:
j = i
size = 0
while not seen[j]:
seen[j] = True
j = p[j]
size += 1
swaps += size - 1
print(swaps)What is printed?- A. 3
- B. 4
- C. 1
- D. 2
Correct answer: D. 2
The permutation has two 2-cycles (0 with 3 and 1 with 2), and each cycle of size s needs s - 1 swaps, giving 2. Counting the inversions (6) answers a different question.
More Coding Interview Problems questions
- Problem: What is floor(sqrt(2000)) found by binary search? Run the code. python lo, hi = 0, 2000 while lo < hi: mid = (lo + hi + 1) // 2…
- Problem: Tasks with (duration, deadline) are (3,5), (2,4), (4,9), (1,3). Scheduling by earliest deadline first, how many tasks finish on…
- Problem: Which statement about the greedy algorithm for 'minimum number of lecture rooms' (interval partitioning) is correct?
- Problem: Which statement about bitmask DP for a Hamiltonian path problem on n = 20 vertices is correct in the standard sense?
- Problem: Which claim about a binary search over a rotated sorted array (no duplicates) finding the minimum element is correct?
- Problem: How many pairs (i < j) of a = [1, 2, 4, 5, 7, 8] have a[i] - a[j] divisible by 3? Run the code. python a = [1, 2, 4, 5, 7, 8]…