Problem 1007

Abstract / Summary

Given a row of dominoes, find the minimum number of rotations needed to make all values in the row the same by only rotating entire dominoes.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1007.py

class Solution:
    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
        result = +inf

        # brute force: expect each number to be in the top or bottom row
        for need in ( 1,2,3,4,5,6 ):
            for g in [ zip(tops, bottoms), zip(bottoms, tops) ]:
                okay  = True
                swaps = 0
                for one, two in g:
                    # try to rotate
                    if one != need:
                        if two == need and swaps < result:
                            swaps += 1
                        else:
                            okay = False
                            break

                # valid sequence
                if okay:
                    result = swaps

        return result if result != +inf else -1
23 lines | 823 bytes | submitted May 30, 2024 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method minDominoRotations. The method receives two integer lists, tops and bottoms, representing the values on the two faces of a sequence of dominoes. Its purpose is to determine the smallest number of rotations required so that every domino shows the same value on either its top row or its bottom row. If no such uniform configuration exists, the method returns -1.

The algorithm follows a straightforward exhaustive strategy: it tests each possible target value (the six faces of a standard domino) and evaluates both orientations-trying to make the top row uniform and trying to make the bottom row uniform. Throughout the process it keeps track of the best (smallest) number of rotations found.

Key Steps

Initialization

result = +inf

A variable result is set to positive infinity. This sentinel value represents the current best solution; any feasible rotation count that is smaller will replace it. Using an infinite initial value allows the algorithm to compare candidate counts without needing a separate flag to indicate whether a solution has been found.

Enumerating Candidate Values

for need in (1, 2, 3, 4, 5, 6):

The outer loop iterates over every face value that could become the uniform number. Because a domino only contains numbers from 1 to 6, the loop covers the complete search space. This guarantees that if a uniform configuration exists, it will be examined.

Trying Both Orientations

for g in [zip(tops, bottoms), zip(bottoms, tops)]:

For each candidate need, the inner loop creates two iterators:

  • zip(tops, bottoms) - pairs each top value with its corresponding bottom value, representing the scenario where we aim to make the top row uniform.
  • zip(bottoms, tops) - pairs each bottom value with its corresponding top value, representing the scenario where we aim to make the bottom row uniform.

By swapping the order of the zipped lists, the same logic can be reused for both orientations, eliminating duplicate code.

Scanning Dominoes and Counting Rotations

okay = True
swaps = 0
for one, two in g:
    if one != need:
        if two == need and swaps < result:
            swaps += 1
        else:
            okay = False
            break

Inside the scan:

  • okay tracks whether the current orientation can achieve uniformity for the chosen need. It starts as True and is set to False the moment an impossible domino is encountered.
  • swaps counts the rotations needed for the current candidate.
  • For each domino pair (one, two), the algorithm first checks whether the face that should already be need (one) already matches. If it does, no action is required.
  • If one does not match, the algorithm looks at the opposite face (two). If two equals need and the current swaps count is still less than the best result found so far, a rotation is counted (swaps += 1). The additional condition swaps < result prevents unnecessary counting once the candidate already exceeds the best known solution, providing a small early-pruning optimization.
  • If neither face matches, the current orientation cannot satisfy the requirement, so okay is set to False and the loop exits immediately (break). This early exit avoids processing the remaining dominoes once failure is certain.

Updating the Best Result

if okay:
    result = swaps

When the scan finishes without breaking, okay remains True, indicating that the current orientation can achieve uniformity with swaps rotations. The algorithm then records this count as the new best result. Because result was initialized to infinity, the first feasible solution will always replace it, and subsequent solutions will only replace it if they require fewer rotations.

Final Return

return result if result != +inf else -1

If at least one feasible configuration was discovered, result will hold a finite integer and is returned. Otherwise, the sentinel value +inf remains unchanged, and the method returns -1 to signal impossibility.

Edge Cases Handled

The code gracefully deals with several boundary conditions:

  • Already Uniform - When all entries in tops (or bottoms) already equal a candidate need, the inner loop never increments swaps. The algorithm detects this quickly because the condition one != need never triggers, leaving swaps at zero and okay true. The final result becomes 0, reflecting that no rotations are required.

  • Single Domino - With a single element in each list, the zip iterator yields one pair. The algorithm correctly evaluates whether a rotation is needed or whether the domino already satisfies the target value, returning either 0 or 1 accordingly, or -1 if the value cannot be made uniform.

  • Impossible Configuration - If for a particular need there exists at least one domino where neither face matches, the inner loop breaks early, setting okay to False. The outer loops continue testing other candidates, and if none succeed, the sentinel +inf persists, leading to a return value of -1.

  • Multiple Viable Targets - When more than one number could serve as the uniform value, the algorithm evaluates each and retains the smallest rotation count. The early-pruning condition swaps < result ensures that once a better solution is found, subsequent candidates that would require more swaps are abandoned as soon as they exceed the current best.

Performance Optimizations Observed

  • Early Termination on Failure - The break statement inside the inner scan stops processing a candidate as soon as a domino is found that cannot be rotated to match need. This prevents unnecessary iteration over the remainder of the lists for hopeless candidates.

  • Pruning Based on Current Best - The check swaps < result before incrementing swaps acts as a guard against counting rotations that would already exceed the best solution discovered so far. When the current candidate’s swap count reaches or surpasses result, the algorithm stops counting further rotations for that candidate, effectively pruning the search space.

  • Reusing Logic for Both Orientations - By constructing the two zip iterators (zip(tops, bottoms) and zip(bottoms, tops)) and processing them with the same loop body, the code avoids duplicated logic. This not only reduces code size but also ensures that any micro-optimizations in the loop apply uniformly to both orientations.

  • Constant-Space Tracking - The algorithm maintains only a few scalar variables (result, okay, swaps, need, one, two). No auxiliary data structures proportional to the input size are allocated, keeping memory usage minimal throughout execution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two long rows of dominoes lying on the floor, and both rows have lots of different numbers showing on the top faces. The goal is to see if it is possible to make one whole row show the same number all the way across. Because there are only six different numbers on a domino, the code checks each of those numbers one by one to see if it can be the star of the show.

For every number, the code looks at both the top row and the bottom row to see if it can build a perfect line. It goes along each domino in the rows and asks if the number is already there. If the number is missing from the top spot, the code peeks at the bottom spot to see if a swap can be made. If the bottom domino has the right number, it turns over and counts as a move. If the number is not in either spot, then that specific number cannot be used to make a matching row, so it stops trying that path and moves on to the next possibility.

After checking all the ways to make a row of ones, twos, threes, fours, fives, or sixes, the code picks the choice that required the fewest flips. If no number can reach all the way across, it reports that it is impossible.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 4.93 | σ = 1.68

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fsq C++
Garvit244 Python
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fsq C++
Garvit244 Python
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
31 links | 17 authors | 9 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

7 solutions   May 30, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality