Solving Leetcode Interviews in Seconds with AI: Minimum Domino Rotations For Equal Row
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1007" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. Constraints: 2 <= tops.length <= 2 * 104 bottoms.length == tops.length 1 <= tops[i], bottoms[i] <= 6
Explanation
Here's a breakdown of the solution:
- Check Feasibility: Iterate through possible target values (1 to 6). For each value, check if it's possible to make either the
topsrow or thebottomsrow contain only that value. - Count Rotations: If a target value is feasible, calculate the minimum number of rotations needed to achieve it for both
topsandbottoms. Return Minimum: Return the minimum number of rotations among all feasible target values, or -1 if no target value is feasible.
Runtime & Space Complexity: O(n) runtime, O(1) space
Code
def minDominoRotations(tops, bottoms):
"""
Finds the minimum number of rotations to make all values in tops or bottoms the same.
Args:
tops: A list of integers representing the top halves of dominoes.
bottoms: A list of integers representing the bottom halves of dominoes.
Returns:
The minimum number of rotations, or -1 if it cannot be done.
"""
n = len(tops)
min_rotations = float('inf')
for target in range(1, 7):
rotations_top = 0
rotations_bottom = 0
possible_top = True
possible_bottom = True
for i in range(n):
if tops[i] != target and bottoms[i] != target:
possible_top = False
possible_bottom = False
break
if tops[i] != target:
rotations_top += 1
if bottoms[i] != target:
rotations_bottom += 1
if possible_top:
min_rotations = min(min_rotations, rotations_top)
if possible_bottom:
min_rotations = min(min_rotations, rotations_bottom)
if min_rotations == float('inf'):
return -1
else:
return min_rotations