Minimum Operations to Make Columns Strictly Increasing - Problem

You are given a m x n matrix grid consisting of non-negative integers.

In one operation, you can increment the value of any grid[i][j] by 1.

Return the minimum number of operations needed to make all columns of grid strictly increasing.

A column is strictly increasing if each element is greater than the element above it: grid[i][j] < grid[i+1][j] for all valid i.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[3,1,6],[1,1,9],[2,4,7]]
Output: 10
💡 Note: Column 1: [3,1,2] → [3,4,5] (1→4 needs +3, 2→5 needs +3, total 6 ops), Column 2: [1,1,4] → [1,2,4] (1→2 needs +1 op), Column 3: [6,9,7] → [6,9,10] (7→10 needs +3 ops). Total: 10
Example 2 — Already Increasing
$ Input: grid = [[1,2],[3,4]]
Output: 0
💡 Note: Both columns are already strictly increasing: [1,3] and [2,4], so no operations needed
Example 3 — Single Column
$ Input: grid = [[5],[4],[3]]
Output: 6
💡 Note: Column [5,4,3] needs to become [5,6,7]: 4→6 (+2 ops), 3→7 (+4 ops). Total: 6 operations

Constraints

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

Visualization

Tap to expand
Minimum Operations to Make Columns Strictly Increasing INPUT grid = [[3,1,6],[1,1,9],[2,4,7]] 3 1 6 1 1 9 2 4 7 Col 0 Col 1 Col 2 R0 R1 R2 Need: Each column must be strictly increasing (top to bottom) Col 0: 3 > 1 (invalid!) Col 1: 1 = 1 (invalid!) Col 2: 9 > 7 (invalid!) m=3, n=3 ALGORITHM STEPS 1 Init ops = 0 Start counter at zero 2 Process each column j = 0, 1, 2 3 For each row i > 0 Check if grid[i][j] > grid[i-1][j] 4 If not, increment Set grid[i][j] = grid[i-1][j] + 1 Column Processing: Col 0: 3-->3, 1-->4(+3), 2-->5(+3) Col 1: 1-->1, 1-->2(+1), 4-->4(+0) Col 2: 6-->6, 9-->9, 7-->10(+3) Col 0 ops: 3 + 3 = 6 Col 1 ops: 1 + 0 = 1 Col 2 ops: 0 + 3 = 3 Total: 6 + 1 + 3 + 2 = 12 FINAL RESULT Modified Grid (strictly increasing): 3 1 6 4 2 9 5 4 10 Verification: Col 0: 3 < 4 < 5 OK Col 1: 1 < 2 < 4 OK Col 2: 6 < 9 < 10 OK Output: 12 operations All columns strictly increasing! Key Insight: Greedy approach works because we can only increment values. For each column, process top to bottom: if current value is not greater than the one above, set it to (previous + 1). This ensures minimum operations since making it exactly (prev + 1) leaves maximum room for subsequent elements. Time: O(m*n), Space: O(1) TutorialsPoint - Minimum Operations to Make Columns Strictly Increasing | Greedy Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
425 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