Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Minimum number of swaps (any two positions) needed to sort an array of distinct values, by counting cycles of the permutation.
Problem: Minimum number of swaps (any two positions) needed to sort an array of distinct values, by counting cycles of the permutation.
def min_swaps(a):
pos = sorted(range(len(a)), key=lambda i: a[i])
seen = [False] * len(a); swaps = 0
for i in range(len(a)):
L = 0; j = i
while not seen[j]: seen[j] = True; j = pos[j]; L += 1
if L: swaps += L - 1
return swaps
print(min_swaps([4, 3, 1, 2, 5, 7, 6]))What is printed?- A. 5
- B. 3
- C. 6
- D. 4
Correct answer: D. 4
Each cycle of length L needs L − 1 swaps. Here 4 → position of 4 … forms one 4-cycle among the first four values (3 swaps), 5 is fixed, and 7, 6 form a 2-cycle (1 swap): 4. Bubble-sort-style adjacent swaps would need as many as the inversions (6).
More Coding Interview Problems questions
- Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect). python from bisect import bisectleft…
- Problem: Starting at index s, you may jump from i to i + a[i] or i − a[i]. Can you reach any index holding 0? python def canreach(a, s)…
- Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2). python def count(a, t)…
- Problem: Rotate an array right by k in O(1) extra space with three reversals. python def rotate(a, k): n = len(a); k %= n def rev(i, j)…
- Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment). python import math…
- Edge case: itertools.groupby on unsorted data. python from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g…