Bird
Raised Fist0

Identify the bug in the following code snippet for the Minimum Domino Rotations problem:

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Minimum Domino Rotations
Identify the bug in the following code snippet for the Minimum Domino Rotations problem:
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 0  # Bug here
            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])
AIncorrect initialization of rotations_a and rotations_b
BNot incrementing rotations when both sides equal x
CReturning rotations without checking both candidates
DThe return value 0 instead of -1 when no domino can be rotated to x
Step-by-Step Solution
  1. Step 1: Analyze early return condition

    If neither side matches candidate x, the function should return -1 to indicate failure, not 0.
  2. Step 2: Impact of returning 0

    Returning 0 falsely indicates zero rotations needed, causing incorrect positive results.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Returning -1 signals no solution; 0 misleads caller [OK]
Quick Trick: Return -1 on failure, not 0 [OK]
Common Mistakes:
MISTAKES
  • Returning 0 instead of -1 on failure
  • Overcounting rotations when both sides equal candidate
Trap Explanation:
PITFALL
  • Returning 0 looks plausible but breaks correctness by hiding failure.
Interviewer Note:
CONTEXT
  • Tests attention to subtle return value correctness in edge cases.
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