[LeetCode] Minimum Domino Rotations For Equal Row

1007. Minimum Domino Rotations For Equal Row

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.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {
int n = tops.size();
int res = INT_MAX;
int tp[6]{0,}, bo[6]{0,}, switchtp[6]{0,}, switchbo[6]{0,};
for(int i = 0; i < n; i++) {
tp[tops[i] - 1]++;
bo[bottoms[i] - 1]++;
if(tops[i] != bottoms[i]) {
switchbo[tops[i]-1]++;
switchtp[bottoms[i]-1]++;
}
}
for(int i = 0; i < 6; i++) {
if(switchbo[i] + bo[i] == n) {
res = min(res, switchbo[i]);
}
if(switchtp[i] + tp[i] == n) {
res = min(res, switchtp[i]);
}
}
return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/minimum-domino-rotations-for-equal-row/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.