#2574
Left and Right Sum Differences
EasyArrayPrefix SumPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass to calculate the total sum of the array and then derives left and right sums dynamically, which significantly reduces the number of operations.
⚙️
Algorithm
6 steps- 1Step 1: Calculate the total sum of the array 'nums'.
- 2Step 2: Initialize leftSum to 0 and create an empty array 'answer'.
- 3Step 3: Iterate through each index 'i' in 'nums'. For each index, update rightSum as totalSum - leftSum - nums[i].
- 4Step 4: Calculate the absolute difference |leftSum - rightSum| and store it in 'answer[i]'.
- 5Step 5: Update leftSum by adding nums[i] for the next iteration.
- 6Step 6: Return the 'answer' array.
solution.py14 lines
1# Full working Python code
2
3def left_right_sum_difference(nums):
4 totalSum = sum(nums)
5 leftSum = 0
6 answer = []
7 for num in nums:
8 rightSum = totalSum - leftSum - num
9 answer.append(abs(leftSum - rightSum))
10 leftSum += num
11 return answer
12
13# Example usage
14print(left_right_sum_difference([10, 4, 8, 3]))ℹ
Complexity note: The time complexity is O(n) because we traverse the array a constant number of times, and the space complexity is O(n) due to the output array.
- 1Understanding the relationship between left and right sums is crucial for optimizing the solution.
- 2Using a single pass to maintain running totals can greatly improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.