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?- A. 2
- B. 0
- C. 3
- 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
- Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that…
- Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'. python def mindel(s): bseen = dels…
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…
- Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, ……
- Problem: Compute a^b mod 1337 where the exponent b is given as a digit array (too large for an integer), using a^(10x + d) = (a^x)^10 ·…