Skip to main content
Back to problems
Leetcode
Medium
Arrays
Greedy
Math
Minimum Domino Rotations For Equal Row

Find the minimum number of domino rotations needed so that all values in either the top row or bottom row become equal.

Acceptance 100%
Problem Statement

You are given two equal-length arrays representing the top and bottom halves of a row of dominoes. Each domino contains one value on the top and one value on the bottom.

In one move, you may rotate a domino so that its top and bottom values swap places.

Your task is to determine the minimum number of rotations needed so that all values in one entire row are the same number. The row can be either the top row or the bottom row. If it is impossible, return 1-1.

A valid final arrangement means:

  • every element in the chosen row is identical, and
  • the other row may contain any values.

Only rotations of individual dominoes are allowed; dominoes cannot be reordered.

Input Format

  • Two integer arrays tops and bottoms of the same length.
  • Each position i describes one domino with values tops[i] and bottoms[i].

Output Format

Return the minimum number of rotations needed to make all values in either the top row or the bottom row equal. If no such value exists, return -1.

Constraints

  • 1 <= tops.length == bottoms.length
  • Domino values are positive integers.
  • You may swap the two values within any domino any number of times, but each swap counts as one rotation.
  • The solution should be efficient for large arrays.
Examples
Sample cases returned by the problem API.

Example 1

Input

tops = [2,1,2,4,2,2]
bottoms = [5,2,6,2,3,2]

Output

2

Explanation

Make all values in the top row equal to 2 by rotating the second and fourth dominoes.

Example 2

Input

tops = [3,5,1,2,3]
bottoms = [3,6,3,3,4]

Output

-1

Explanation

No single value can be made to fill an entire row.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.