5/03/2025

[LeetCode] 1007. Minimum Domino Rotations For Equal Row

Problem : https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/description/

To reach the goal of this problem, we can:

  • Lock the first column and rotate the other columns to match the top value the first column.
  • Lock the first column and rotate the other columns to match the bottom value the first column.
  • Rotate and lock the first column, then rotate the other columns to match the top value of the first column.
  • Rotate and lock the first column, then rotate the other columns to match the bottom value of the first column.
  • The answer is minimum rotation count of the above 4 usecases.

    
    class Solution {
        public int minDominoRotations(int[] tops, int[] bottoms) {
            int rotationCountForMatchingTop = helper(tops[0], tops, bottoms);
            int rotationCountForMatchingBottom = helper(bottoms[0], tops, bottoms);
            
            if (rotationCountForMatchingTop == -1 && rotationCountForMatchingBottom == -1)
              return -1;
    
            if (rotationCountForMatchingTop == -1)
              return rotationCountForMatchingBottom;
    
            if (rotationCountForMatchingBottom == -1)
              return rotationCountForMatchingTop;
    
            return Math.min(rotationCountForMatchingTop, rotationCountForMatchingBottom);
        }
    
        int helper(int target, int[] A, int[] B) {
          int rotateToTop = 0, rotateToBottom = 0;
          for (int i = 0; i < A.length; i++) {
            if (target != A[i] && target != B[i]) {
              // There is no way to rotate the current domino to match the target value.
              return -1;
            }
    
            if (target != A[i]) {
              rotateToTop += 1;
            }
    
            if (target != B[i]) {
              rotateToBottom += 1;
            }
          }
    
          return Math.min(rotateToTop, rotateToBottom);
        }
    }
    

    No comments:

    Post a Comment