Bird
Raised Fist0

Given the following code and input arrays, what is the final output printed?

easy🧾 Code Trace Q12 of Q15
Greedy Algorithms - Minimum Domino Rotations
Given the following code and input arrays, what is the final output printed?
def minDominoRotations(A, B):
    def check(x):
        rotations_a = rotations_b = 0
        for i in range(len(A)):
            if A[i] != x and B[i] != x:
                return -1
            elif A[i] != x:
                rotations_a += 1
            elif B[i] != x:
                rotations_b += 1
        return min(rotations_a, rotations_b)

    rotations = check(A[0])
    if rotations != -1:
        return rotations
    else:
        return check(B[0])

A = [3,5,1,2]
B = [3,6,3,3]
print(minDominoRotations(A, B))
A-1
B2
C1
D3
Step-by-Step Solution
  1. Step 1: Check candidate x = A[0] = 3

    i=0: A[0]=3 matches x=3, no rotation.
    i=1: A[1]=5 != 3, B[1]=6 != 3 -> return -1 immediately.
  2. Step 2: Check candidate x = B[0] = 3

    i=0: A[0]=3 matches x=3, no rotation.
    i=1: A[1]=5 != 3, B[1]=6 != 3 -> return -1 immediately.
    Both candidates fail, so output is -1.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Both candidates fail at i=1, so no solution [OK]
Quick Trick: Check both candidates carefully for early failure [OK]
Common Mistakes:
MISTAKES
  • Assuming first candidate always works
  • Miscounting rotations when both sides match
Trap Explanation:
PITFALL
  • Candidates often miss early return -1 when neither side matches candidate.
Interviewer Note:
CONTEXT
  • Tests ability to trace code and handle early termination correctly.
Master "Minimum Domino Rotations" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes