Skip to content

Conversation

@shafaq16
Copy link
Contributor

@shafaq16 shafaq16 commented Oct 5, 2025

Approach:

We need to make all dominos show the same number on either the top or bottom row with the minimum rotations.
Since only two values are possible candidates — tops[0] or bottoms[0] — we check both.
Steps:
Let X = tops[0] and Y = bottoms[0].
Try to make all dominos equal to X (top or bottom) and also to Y.
For each domino:
If neither top nor bottom has X, then X is impossible.
Otherwise, count how many flips are needed to make all tops or all bottoms equal to X.
Do the same for Y.
The answer is the minimum flips among all valid cases, or -1 if neither works.

Intuition:

This is a brute-force check on only two candidates — the first domino’s numbers — because if a uniform value exists, it must be one of these.
We just simulate how many rotations would be needed to align all dominos to each candidate and pick the smallest valid one.

Solution in Code (C++)
class Solution {
public:
int minDominoRotations(vector& tops, vector& bottoms) {
const int n = tops.size();

    // Try to make all values equal to tops[0] or bottoms[0]
    int X=tops[0], Y=bottoms[0];
    int swapXT=0, swapXB=0;
    int swapYT=0, swapYB=0;

    bool hasX=1, hasY=1;

    for (int i=0; i<n; i++) {
        // Check for candidate X
        if (hasX) {
            if (tops[i]!=X && bottoms[i]!=X) 
                hasX=0;
            else {
                if (tops[i]!=X) swapXT++;
                if (bottoms[i]!=X) swapXB++;
            }
        }

        // Check for candidate Y
        if (hasY) {
            if (tops[i]!=Y && bottoms[i]!=Y) 
                hasY=0;
            else {
                if (tops[i]!=Y) swapYT++;
                if (bottoms[i]!=Y) swapYB++;
            }
        }

        // Early exit if both invalid
        if (!hasX && !hasY) return -1;
    }

    int ans=INT_MAX;
    if (hasX) ans=min(ans, min(swapXT, swapXB));
    if (hasY) ans=min(ans, min(swapYT, swapYB));

    return ans;
}

};

@SjxSubham
Copy link
Owner

Closed #119 #120

@SjxSubham SjxSubham closed this Oct 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants