Left and Right Sum Differences (LeetCode 2574): Solution and Explanation
For every index, return the absolute difference between the sum of the elements before it and the sum of the elements after it. The element at the index itself belongs to neither side.
Intuition
Picture a divider sliding across the array from left to right. Everything behind the divider is the left side, everything ahead of it is the right side, and the element under the divider is set aside.
Each time the divider moves one step, exactly one element changes sides. It leaves the right side and, one step later, joins the left side. So there is no need to re-add anything: two running sums are enough.
Start with left = 0 and right = the whole total. At index i, take nums[i] off the right first, record the gap |left - right|, then put nums[i] on the left before moving on.
Approach: Two running sums
- Set
left = 0andright = sum(nums). - For each element
xin order, subtract it fromright. Nowrightholds the sum strictly after the current index. - Append
abs(left - right)to the answer. - Add
xtoleft, soleftholds the sum strictly before the next index. - Return the answer array.
Step-by-step example
nums = [10,4,8,3]
- The total is 25, so
left = 0andright = 25. - i = 0: right becomes 25 - 10 = 15. The gap is |0 - 15| = 15. left becomes 10.
- i = 1: right becomes 15 - 4 = 11. The gap is |10 - 11| = 1. left becomes 14.
- i = 2: right becomes 11 - 8 = 3. The gap is |14 - 3| = 11. left becomes 22.
- i = 3: right becomes 3 - 3 = 0. The gap is |22 - 0| = 22. The answer is [15,1,11,22].
Code: Python, Java, C++
1class Solution:
2 def leftRightDifference(self, nums: List[int]) -> List[int]:
3 left, right = 0, sum(nums)
4 answer = []
5 for x in nums:
6 right -= x
7 answer.append(abs(left - right))
8 left += x
9 return answer1class Solution {
2 public int[] leftRightDifference(int[] nums) {
3 int left = 0, right = 0;
4 for (int x : nums) right += x;
5 int[] answer = new int[nums.length];
6 for (int i = 0; i < nums.length; i++) {
7 right -= nums[i];
8 answer[i] = Math.abs(left - right);
9 left += nums[i];
10 }
11 return answer;
12 }
13}1class Solution {
2public:
3 vector<int> leftRightDifference(vector<int>& nums) {
4 int left = 0, right = accumulate(nums.begin(), nums.end(), 0);
5 vector<int> answer(nums.size());
6 for (int i = 0; i < (int)nums.size(); i++) {
7 right -= nums[i];
8 answer[i] = abs(left - right);
9 left += nums[i];
10 }
11 return answer;
12 }
13};Time and space complexity
O(n)
One pass for the total and one pass that does constant work per index.
O(1)
Only left and right are kept besides the output array.
Other approaches
Prefix and suffix arrays (time O(n), space O(n))
Build leftSum from the front and rightSum from the back, then subtract them index by index. Easy to read, but it stores two extra arrays.
Brute force (time O(n^2), space O(1))
For each index, add up the elements before it and after it from scratch. Correct, but quadratic.
Common mistakes
- Subtracting from
rightafter recording the gap, which leaves the current element counted on the right side. - Adding to
leftbefore recording the gap, which counts the current element on the left side. - Forgetting the absolute value. When the left side is heavier,
left - rightis positive, otherwise it is negative.
Frequently asked questions
Does the element at index i count toward either sum?
No. Both sums are strictly to the left or strictly to the right of i, which is why the code removes nums[i] from right before the comparison and adds it to left only afterwards.
Can the sums overflow a 32-bit integer?
No. At most 1000 elements of at most 10^5 each gives a total of 10^8, well under the 32-bit limit.
How is this related to Find Pivot Index?
It uses the same left and right sums. Find Pivot Index looks for the first index where the gap is 0, while this problem reports the gap at every index.