Approaches
💡
Intuition
Time O(n²)Space O(1)
The brute-force approach checks every possible target value in the grid and calculates the number of operations needed to convert all elements to that target. This is straightforward but inefficient for larger grids.
⚙️
Algorithm
3 steps- 1Step 1: Identify all unique values in the grid.
- 2Step 2: For each unique value, calculate the number of operations needed to convert all elements to this value.
- 3Step 3: Return the minimum operations found or -1 if conversion is not possible.
solution.py14 lines
1# Full working Python code
2
3def minOperations(grid, x):
4 unique_values = set(val for row in grid for val in row)
5 min_operations = float('inf')
6 for target in unique_values:
7 operations = 0
8 for row in grid:
9 for val in row:
10 if (val - target) % x != 0:
11 return -1
12 operations += abs(val - target) // x
13 min_operations = min(min_operations, operations)
14 return min_operations if min_operations != float('inf') else -1ℹ
Complexity note: This complexity arises because we check each element in the grid for every unique value, leading to a quadratic time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.