1+ // 1007. Minimum Domino Rotations For Equal Row
2+
3+ /* Time Complexity O(n)
4+ Space Complexity O(1)*/
5+
6+ class Solution
7+ {
8+ public:
9+ int dominoRotations (vector<int > &tops, vector<int > &bottoms)
10+ {
11+ int minRotation = INT_MAX;
12+ for (int i = 1 ; i <= 6 ; ++i)
13+ {
14+ int swap = 0 , j;
15+ for (j = 0 ; j < tops.size (); ++j)
16+ {
17+ if (tops[j] == i)
18+ continue ;
19+ else if (bottoms[j] == i)
20+ ++swap;
21+ else
22+ break ;
23+ }
24+
25+ // if we reach at the end of vector && minRotation > swap
26+ if (j == tops.size () && minRotation > swap)
27+ minRotation = swap;
28+ }
29+ return minRotation == INT_MAX ? -1 : minRotation;
30+ }
31+
32+ int minDominoRotations (vector<int > &tops, vector<int > &bottoms)
33+ {
34+
35+ // try to make all a faces same
36+ int ab = dominoRotations (tops, bottoms);
37+
38+ // try to make all b faces same
39+ int ba = dominoRotations (bottoms, tops);
40+
41+ return ab == -1 ? ba : ba == -1 ? ab
42+ : min (ab, ba);
43+ }
44+ };
45+
46+ // another approach
47+
48+ /* Time Complexity O(n)
49+ Space Complexity O(1)*/
50+ class Solution
51+ {
52+ public:
53+ int minDominoRotations (vector<int > &tops, vector<int > &bottoms)
54+ {
55+ int n = tops.size ();
56+
57+ // vector for faceA , faceB & same for accumulating when,
58+ // both faceA & faceB have same values
59+ vector<int > faceA (7 ), faceB (7 ), same (7 );
60+
61+ for (int i = 0 ; i < n; ++i)
62+ {
63+ ++faceA[tops[i]];
64+ ++faceB[bottoms[i]];
65+
66+ if (tops[i] == bottoms[i])
67+ ++same[tops[i]];
68+ }
69+
70+ int minRotation = INT_MAX;
71+
72+ for (int i = 1 ; i <= 6 ; ++i)
73+ {
74+ if (faceA[i] + faceB[i] - same[i] == n)
75+ minRotation = min (minRotation, min (faceA[i], faceB[i]) - same[i]);
76+ }
77+
78+ return minRotation == INT_MAX ? -1 : minRotation;
79+ }
80+ };
0 commit comments