Skip to main content
Back to problems
#1007
Medium Algorithms

Minimum domino rotations for equal row

Array Greedy
56.5% acceptance
Feb 25, 2026
3284
271
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_domino_rotations(tops: Vec<i32>, bottoms: Vec<i32>) -> i32 {
    let n = tops.len();
    let try_val = |v: i32| -> i32 {
      let (mut rt, mut rb) = (0i32, 0i32);
      for i in 0..n {
        if tops[i] != v && bottoms[i] != v { return i32::MAX; }
        else if tops[i] != v { rt += 1; }
        else if bottoms[i] != v { rb += 1; }
      }
      rt.min(rb)
    };
    let ans = [try_val(tops[0]), try_val(bottoms[0])].into_iter().min().unwrap();
    if ans == i32::MAX { -1 } else { ans }
  }
}