Ctrl K

Levelling the Shelf Row

Hard
A row of shelves runs along a wall, and shelves[i] is the number of boxes on shelf i. You want every shelf to hold the same number of boxes. Boxes move in rounds. In one round you pick any number of shelves (at least one), and each picked shelf simultaneously passes exactly one box to a neighbouring shelf, left or right. Return the fewest rounds needed to level all the shelves. If it cannot be done, return −1.
Example 1
shelves=[4, 0, 2] → 2

Each shelf needs 2 boxes. Round 1: the first shelf hands a box to the second → [3, 1, 2]. Round 2: again → [2, 2, 2]. The answer is 2.

Example 2
shelves=[0, 0, 8, 0] → 6

Each shelf needs 2 boxes. The third shelf has to give away 6 of them but can pass only one per round, so at least 6 rounds are needed, and 6 are enough.

Example 3
shelves=[1, 2] → -1

3 boxes cannot be split evenly between 2 shelves, so the answer is −1.

Constraints
  • 1 ≤ len(shelves) ≤ 10⁴
  • 0 ≤ shelves[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStickers for Test Scores HardLargest Number From Two Rows HardHow Many Coins to Add HardThe Heaviest Reading Day HardGrowing Capital Project by Project Hard
loading Python…
Input
shelves=[4, 0, 2]
Expected
2

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