Difficulty: Medium
We can brute force through all possible values for the dominoes (there are only 6 possible values).
As we iterate through all the dominoes, if we have a domino that does not have the current value on it, we know that the current value is not a valid number to match.
Then we keep track of the swaps we would need if we align the numbers at the bottom and the top. We take the lowest of these for each of the 6 numbers and return the lowest out of those.
class Solution(object):
def minDominoRotations(self, tops, bottoms):
"""
:type tops: List[int]
:type bottoms: List[int]
:rtype: int
"""
# 2 is now the top
# 2 2 2 4 2 2
# 5 1 6 2 3 2
n = len(tops)
res = float('inf')
for val in range(1, 7):
top_swap = 0
bottom_swap = 0
valid = True
for i in range(n):
top = tops[i]
bottom = bottoms[i]
if top != val and bottom != val:
valid = False
break
if top != val:
top_swap += 1
if bottom != val:
bottom_swap += 1
if valid:
res = min(res, top_swap, bottom_swap)
if res == float('inf'):
return -1
return res
Time Complexity:
O(n)
Space Complexity:
O(1)
Time Taken:
51m 44s