Ctrl K

Level the Grid in Steps

Medium
You get a rectangular integer grid grid and a step step. One move adds step to any single cell or subtracts it from that cell. Return the fewest moves after which all cells hold the same value, or -1 if that is impossible.
Example 1
grid=[[3, 9], [6, 12]], step=3 → 4

Level everything to 6: raise 3 by one step, lower 9 by one step and 12 by two. That is 4 moves.

Example 2
grid=[[5, 7, 8]], step=2 → -1

5 and 7 are odd while 8 is even, so steps of 2 can never make them equal.

Example 3
grid=[[4], [4]], step=7 → 0

The cells are already equal.

Constraints
  • 1 ≤ rows, columns
  • number of cells ≤ 10⁵
  • 1 ≤ step ≤ 10⁴
  • 1 ≤ grid[i][j] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThree Heaviest Diamonds MediumWhere the Friends Should Meet HardHow a Rumor Spreads EasyTurn a Square Clockwise MediumSorted Parabola Values Medium
loading Python…
Input
grid=[[3, 9], [6, 12]], step=3
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 98 tests on the server, hidden ones included.