LeetCode Problem 2574
Link of the Problem to try -: Link
You are given a 0-indexed integer array nums of size n.
Define two arrays leftSum and rightSum where:
leftSum[i]is the sum of elements to the left of the indexiin the arraynums. If there is no such element,leftSum[i] = 0.rightSum[i]is the sum of elements to the right of the indexiin the arraynums. If there is no such element,rightSum[i] = 0.
Return an integer array answer of size n where answer[i] = |leftSum[i] - rightSum[i]|.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 105
Left and Right Sum Difference in an Array (Java) – Easy & Optimal Approaches
This problem can be solved using multiple approaches. In this blog, I will explain two simple and effective ways to solve the Left and Right Sum Difference problem.
- Approach 1: A straightforward and beginner-friendly solution
- Approach 2: A more optimal solution with better space efficiency
Both approaches are easy to understand and suitable for submitting on LeetCode.
Approach 1: Simplest and Easy to Understand
Explanation
In this approach, we use three arrays of size n:
prefix[]to store the sum of elements on the left of each indexsuffix[]to store the sum of elements on the right of each indexans[]to store the final result
Steps
- Build the
prefixarray using a forward loop. - Build the
suffixarray using a backward loop. - Iterate through the array and calculate the absolute difference between prefix and suffix sums.
Time & Space Complexity
- Time Complexity:
O(n) - Space Complexity:
O(n)(extra arrays used)
Java Code
Why Use This Approach?
- Very easy to understand
- Best for beginners
- Clear separation of prefix and suffix logic
Approach 2: Optimal Solution (Best for Interviews)
Explanation
This is the most optimal approach, where we only use one result array.
Instead of creating a suffix array, we:
- Calculate the total sum of the array
- Maintain a running left sum
- Compute the right sum using the formula:
This removes the need for extra arrays and reduces space usage.
Time & Space Complexity
- Time Complexity:
O(n) - Space Complexity:
O(1)(excluding output array)
Java Code
Why This Is Optimal?
- Uses constant extra space
- Clean and efficient logic
- Ideal for coding interviews and competitive programming




