1007. Minimum Domino Rotations For Equal Row
MediumView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Target value must be A[0] or B[0].
Intuition
Target value must be A[0] or B[0]. For each candidate, greedily count swaps needed.
Algorithm
- 1For each candidate (A[0], B[0]): simulate, count swaps. Return min swaps.
- 2If a position has neither value for a candidate: skip that candidate.
Common Pitfalls
- •Only two candidates to try. Return -1 if neither works.
1007.cs
C#
// Approach: Count frequency of each value in tops, bottoms, and common positions; the answer for a candidate value = min(tops - common, bottoms - common).
// Time: O(n) Space: O(1)
public class Solution
{
public int MinDominoRotations(int[] tops, int[] bottoms)
{
int n = tops.Length;
// Count occurrences for each number in tops and bottoms
int[] countTop = new int[7];
int[] countBottom = new int[7];
int[] countCommon = new int[7]; // When top[i] == bottom[i]
for (int i = 0; i < n; i++)
{
int t = tops[i];
int b = bottoms[i];
countTop[t]++;
countBottom[b]++;
if (t == b)
countCommon[t]++;
}
int minRotations = int.MaxValue;
// Try each possible target value from 1 to 6
for (int candidate = 1; candidate <= 6; candidate++)
{
// Check if it's possible to make all values equal to candidate
if (countTop[candidate] + countBottom[candidate] - countCommon[candidate] == n)
{
// Calculate rotations needed
int rotateTop = countTop[candidate] - countCommon[candidate]; // Make all top = candidate
int rotateBottom = countBottom[candidate] - countCommon[candidate]; // Make all bottom = candidate
minRotations = Math.Min(minRotations, Math.Min(rotateTop, rotateBottom));
}
}
return minRotations == int.MaxValue ? -1 : minRotations;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)