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?
  1. A. 2 3 -1
  2. B. 2 3 1
  3. C. 4 3 -1
  4. 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

Exams that ask this topic