#1007

Minimum Domino Rotations For Equal Row

Medium
ArrayGreedyHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we only need to check the values on the first domino. If we can make all dominoes match that value, we can calculate the minimum rotations efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Identify the first domino's top and bottom values as potential candidates.
  2. 2Step 2: For each candidate, count how many rotations are needed to make all tops or bottoms equal to that candidate.
  3. 3Step 3: Return the minimum rotations found for either candidate, or -1 if neither is possible.
solution.py14 lines
1def minDominoRotations(tops, bottoms):
2    def countRotations(value):
3        top_rotations = bottom_rotations = 0
4        for i in range(len(tops)):
5            if tops[i] != value and bottoms[i] != value:
6                return float('inf')
7            elif tops[i] != value:
8                top_rotations += 1
9            elif bottoms[i] != value:
10                bottom_rotations += 1
11        return min(top_rotations, bottom_rotations)
12
13    min_rotations = min(countRotations(tops[0]), countRotations(bottoms[0]))
14    return min_rotations if min_rotations != float('inf') else -1

Complexity note: The time complexity is O(n) because we only iterate through the arrays a constant number of times (twice at most), making it efficient.

  • 1The first domino's values are crucial as they determine potential candidates for uniformity.
  • 2If a value cannot be made uniform across either row, it is impossible to achieve the goal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.