Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps? Compute it from the cycle decomposition by running the code.
The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps? Compute it from the cycle decomposition by running the code.
p=[4,3,1,7,6,2,5]
seen=[0]*8; c=0
for i in range(1,8):
if not seen[i]:
c+=1; j=i
while not seen[j]: seen[j]=1; j=p[j-1]
print(7-c)What is printed?- A. 7
- B. 1
- C. 6
- D. 10
Correct answer: C. 6
The minimum swaps equal n minus the number of cycles, so with this single 7-cycle the answer is 6 and not the cycle count. Counting misplaced elements counts positions rather than cycles, and counting inversions measures disorder rather than cycle structure.
More Coding Interview Problems questions
- Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and…
- How many ways are there to tile a 3 × 8 board completely with 1 × 2 dominoes (placed horizontally or vertically)? Count by DFS over the…
- Meetings are given as half-open intervals [(0,30),(5,10),(15,20),(12,25),(28,35)]. What is the minimum number of meeting rooms needed so…
- Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code. python a=list(range(1,15))…
- Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code…
- Problem: A connected undirected graph has 7 vertices. Its BFS tree from vertex 0 has depths: vertex 0 at depth 0, vertices 1 and 2 at…