Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the minimum number of swaps to sort an array of distinct values.
Problem: Find the minimum number of swaps to sort an array of distinct values.
def min_swaps(a):
order = sorted(range(len(a)), key=lambda i: a[i])
seen = [False] * len(a); swaps = 0
for i in range(len(a)):
if seen[i] or order[i] == i: continue
j, cyc = i, 0
while not seen[j]:
seen[j] = True; j = order[j]; cyc += 1
swaps += cyc - 1
return swaps
print(min_swaps([4, 3, 2, 1]), min_swaps([1, 5, 4, 3, 2]), min_swaps([2, 3, 4, 1, 5]))What is printed?- A. 2 2 3
- B. 3 2 3
- C. 2 3 3
- D. 2 2 4
Correct answer: A. 2 2 3
Map each position to where its value belongs; the permutation splits into cycles, and a cycle of length c needs c − 1 swaps. [4, 3, 2, 1] has two 2-cycles → 2. [2, 3, 4, 1, 5] has one 4-cycle → 3. Counting inversions (6 for the first) gives adjacent-swap counts, not arbitrary swaps. O(n log n).
More Coding Interview Problems questions
- Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays. python def distinctor(a): res, cur = set(), set()…
- Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit. python def maxxor(a): ans = mask = 0…
- Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range. python…
- Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7. java static long ways3(int n) { long MOD =…
- Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost. python def…
- Problem: Count palindromic substrings (each occurrence counts separately). python def countpal(s): n, c = len(s), 0 for center in range(2…