Skip to main content
LeetCode 1769, Medium. Topics: Array, String, Prefix Sum. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:

Problem

<p>You have <code>n</code> boxes. You are given a binary string <code>boxes</code> of length <code>n</code>, where <code>boxes[i]</code> is <code>‘0’</code> if the <code>i<sup>th</sup></code> box is <strong>empty</strong>, and <code>‘1’</code> if it contains <strong>one</strong> ball.</p> <p>In one operation, you can move <strong>one</strong> ball from a box to an adjacent box. Box <code>i</code> is adjacent to box <code>j</code> if <code>abs(i - j) == 1</code>. Note that after doing so, there may be more than one ball in some boxes.</p> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong>minimum</strong> number of operations needed to move all the balls to the <code>i<sup>th</sup></code> box.</p> <p>Each <code>answer[i]</code> is calculated considering the <strong>initial</strong> state of the boxes.</p>

Examples

Constraints

  • n == boxes.length
  • 1 <= n <= 2000
  • boxes[i] is either ‘0’ or ‘1’.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026