Find the minimum number of domino rotations needed so that all values in either the top row or bottom row become equal.
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 .
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
topsandbottomsof the same length. - Each position
idescribes one domino with valuestops[i]andbottoms[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.
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.