Data Structures & AlgorithmsVery hardProduct company OA
Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if impossible).
Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if impossible).
def min_swaps(s1, s2):
xy = yx = 0
for a, b in zip(s1, s2):
if a == "x" and b == "y": xy += 1
elif a == "y" and b == "x": yx += 1
if (xy + yx) % 2: return -1
return xy // 2 + yx // 2 + 2 * (xy % 2)
print(min_swaps("xxyy", "yyxx"), min_swaps("xxyx", "yyxy"), min_swaps("xyx", "yxy"))What is printed?- A. 2 3 -1
- B. 2 3 1
- C. 4 3 -1
- D. 2 2 -1
Correct answer: A. 2 3 -1
Only mismatched positions matter. Two 'xy' mismatches are fixed with ONE swap (swap s1's x at one with s2's y at the other); likewise two 'yx'. A leftover xy + yx pair needs 2 swaps. Odd total mismatches → −1. "xxyy"/"yyxx": 2 xy + 2 yx → 1 + 1 = 2 (not 4). "xxyx"/"yyxy": 3 xy + 1 yx → 1 + 0 + 2 = 3. "xyx"/"yxy": 3 mismatches → −1. O(n).
More Coding Interview Problems questions
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…