Show problems as
Classic problem #2574EasyArrayPrefix Sum

Left and Right Sum Differences

Real-world version: Silo Row Imbalance
Tracked in this browser only
Read Left and Right Sum Differences on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A grain terminal lines up its silos in one row. Silo i currently holds nums[i] tonnes.

For each silo the operator wants its imbalance: the absolute difference between the tonnage stored in the silos strictly before it in the row and the tonnage stored in the silos strictly after it. The silo itself counts on neither side, and an empty side contributes zero.

Return an array of the imbalances, one entry per silo, in row order.

Examples

Example 1

Input
nums = [6,2,9,4]
Output
[15,7,4,17]

For silo 0 nothing lies before it and 2 + 9 + 4 = 15 lies after it. For silo 1 the sides hold 6 and 13. For silo 2 they hold 8 and 4. For silo 3 they hold 17 and nothing.

Example 2

Input
nums = [12,5]
Output
[5,12]

Silo 0 has nothing before it and 5 tonnes after it. Silo 1 has 12 tonnes before it and nothing after it.

Example 3

Input
nums = [3,3,3]
Output
[6,0,6]

The middle silo has 3 tonnes on each side, so its imbalance is 0, while each end silo faces 6 tonnes on its inner side and nothing on its outer side.

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^5

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def left_right_difference(nums: list[int]) -> list[int]:
Java
public int[] leftRightDifference(int[] nums)