Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i' / 'not swapped at i').

Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i' / 'not swapped at i').
def minswap(a, b):
    keep, swap = 0, 1
    for i in range(1, len(a)):
        k2 = s2 = float('inf')
        if a[i-1] < a[i] and b[i-1] < b[i]: k2, s2 = keep, swap + 1
        if a[i-1] < b[i] and b[i-1] < a[i]: k2, s2 = min(k2, swap), min(s2, keep + 1)
        keep, swap = k2, s2
    return min(keep, swap)
print(minswap([1, 3, 5, 4, 9], [1, 2, 3, 7, 8]))
What is printed?
  1. A. 2
  2. B. 0
  3. C. 3
  4. D. 1

Correct answer: D. 1

Only index 3 breaks a (5 > 4 in a, while b has 7): swapping position 3 alone gives a = [1, 3, 5, 7, 9] and b = [1, 2, 3, 4, 8], both increasing. One swap suffices, as the brute force over all 2⁵ choices confirms.

More Coding Interview Problems questions

Exams that ask this topic