Minimum Number of Operations to Satisfy Conditions - Problem

You are given a 2D matrix grid of size m x n. In one operation, you can change the value of any cell to any non-negative number.

You need to perform some operations such that each cell grid[i][j] is:

  • Equal to the cell below it, i.e. grid[i][j] == grid[i + 1][j] (if it exists)
  • Different from the cell to its right, i.e. grid[i][j] != grid[i][j + 1] (if it exists)

Return the minimum number of operations needed.

Input & Output

Example 1 — Basic 3x3 Grid
$ Input: grid = [[1,1,1],[0,0,0],[1,0,1]]
Output: 3
💡 Note: Make column 0 all 1s (cost 0), column 1 all 0s (cost 1), column 2 all 1s (cost 2). Total: 3 operations.
Example 2 — Already Valid
$ Input: grid = [[1,0,2],[1,0,2]]
Output: 0
💡 Note: Each column has uniform values and adjacent columns differ. No operations needed.
Example 3 — Single Row
$ Input: grid = [[1,2,3,4]]
Output: 4
💡 Note: Change to [0,1,0,1] - each column uniform, adjacent differ. Cost: 1+1+1+1 = 4.

Constraints

  • 1 ≤ m, n ≤ 1000
  • 0 ≤ grid[i][j] ≤ 9

Visualization

Tap to expand
Minimum Operations to Satisfy Conditions INPUT 2D Matrix Grid (3x3) 1 1 1 0 0 0 1 0 1 Constraints: - Same value in each column - Adjacent columns differ - m=3, n=3 - Values: 0-9 ALGORITHM (DP) 1 Count Frequency Count each digit per column 2 Define DP State dp[col][digit] = min ops 3 Transition Pick different digit for next col 4 Result Min of dp[last_col][*] DP Table (simplified): Col d=0 d=1 0 2 1 1 2 3 2 4 3 FINAL RESULT Optimal Grid After Changes 1 0 1 1 0 1 1 0 1 Unchanged Changed Changes made: - [0][1]: 1 --> 0 - [1][0]: 0 --> 1 - [2][2]: 1 --> 1 (alt: other opt) Output: 3 Key Insight: Each column must have uniform values, and adjacent columns must differ. Use DP where dp[col][digit] represents minimum operations to make column col have all cells equal to digit. Transition considers only different digits for the next column. Cost = rows - frequency of chosen digit in that column. TutorialsPoint - Minimum Number of Operations to Satisfy Conditions | DP Approach
Asked in
Google 42 Meta 35 Amazon 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen