Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 26, 2025 11:40
Show Gist options
  • Save Ifihan/db76348c1c14a698b08de7477e2ecb31 to your computer and use it in GitHub Desktop.
Save Ifihan/db76348c1c14a698b08de7477e2ecb31 to your computer and use it in GitHub Desktop.
Minimum Operations to Make a Uni-Value Grid

Question

Approach

To solve this problem, I first flattened the grid into a single list and sorted it. Then I checked whether all differences between elements and the first element are divisible by x—if not, it's impossible to make the grid uni-value and I return -1. If not, I used the median of the list as the target value (since it minimizes the total number of absolute differences), and computed the total number of operations needed by summing up abs(value - median) // x for each value.

Implementation

class Solution:
    def minOperations(self, grid: List[List[int]], x: int) -> int:
        flat = [num for row in grid for num in row]
        base = flat[0]
        
        for val in flat:
            if (val - base) % x != 0:
                return -1
        
        flat.sort()
        median = flat[len(flat) // 2]
        
        return sum(abs(val - median) // x for val in flat)

Complexities

  • Time: O(n log n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment