Ctrl K

Left Versus Right Weight Gap

Easy
Boxes stand in a row on a shelf, and their weights are given in the array weights. For every box, add up the weights of all boxes to its left and of all boxes to its right (a side with no boxes sums to 0). Return an array of the same length whose element i is the absolute difference between those two sums for box i.
Example 1
weights=[3, 7, 2, 6] → [15, 5, 4, 12]

At index 1 the left side sums to 3 and the right side to 2 + 6 = 8, a gap of 5. At index 3 the left side is 12 and the right side is empty, a gap of 12.

Example 2
weights=[4, 4] → [4, 4]

Each element has 4 on one side and 0 on the other.

Example 3
weights=[9] → [0]

A single element: both sides are empty, so the gap is 0.

Constraints
  • 1 ≤ len(weights) ≤ 10⁵
  • 1 ≤ weights[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBalance Point Index EasyThe Battery Must Not Run Dry EasyBalance After Each Day EasyTotals of Odd-Length Slices EasyThe Hiker's Highest Point Easy
loading Python…
Input
weights=[3, 7, 2, 6]
Expected
[15, 5, 4, 12]

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