Left and Right Sum Differences
Left and Right Sum Differences

Left and Right Sum Differences

LeetCode 2574 Easy

19 views
0
0

LeetCode 2574: Left and Right Sum Differences (Java)

The Left and Right Sum Difference problem is a classic array manipulation challenge. It tests your ability to efficiently calculate prefix and suffix valuesโ€”a skill essential for more advanced algorithms like "Product of Array Except Self."


๐Ÿ”— Resources

  1. Problem Link: LeetCode 2574 - Left and Right Sum Differences

๐Ÿ“ Problem Statement

You are given a 0-indexed integer array nums. You need to return an array answer of the same length where:

  1. answer[i] = |leftSum[i] - rightSum[i]|
  2. leftSum[i] is the sum of elements to the left of index i.
  3. rightSum[i] is the sum of elements to the right of index i.


๐Ÿ’ก Approach 1: The Three-Array Method (Beginner Friendly)

This approach is highly intuitive. We pre-calculate all left sums and all right sums in separate arrays before computing the final difference.

The Logic

  1. Prefix Array: Fill pref[] by adding the previous element to the cumulative sum.
  2. Suffix Array: Fill suff[] by iterating backward from the end of the array.
  3. Result: Loop one last time to calculate Math.abs(pref[i] - suff[i]).


Java Implementation

public int[] leftRightDifference(int[] nums) {
int n = nums.length;
int[] pref = new int[n];
int[] suff = new int[n];
int[] ans = new int[n];

// Calculate Left Sums (Prefix)
for (int i = 1; i < n; i++) {
pref[i] = pref[i - 1] + nums[i - 1];
}

// Calculate Right Sums (Suffix)
for (int i = n - 2; i >= 0; i--) {
suff[i] = suff[i + 1] + nums[i + 1];
}

// Combine results
for (int i = 0; i < n; i++) {
ans[i] = Math.abs(pref[i] - suff[i]);
}

return ans;
}
  1. Time Complexity: O(n)
  2. Space Complexity: O(n) (Uses extra space for pref and suff arrays).


๐Ÿš€ Approach 2: The Running Sum Method (Space Optimized)

In technical interviews, you should aim for O(1) extra space. Instead of storing every suffix sum, we calculate the Total Sum first and derive the right sum using logic.

The Logic

We use the mathematical property:

Right Sum = Total Sum - Left Sum - Current Element

By maintaining a single variable leftSum that updates as we iterate, we can calculate the result using only the output array.


Java Implementation

public int[] leftRightDifference(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
int totalSum = 0;
int leftSum = 0;

// 1. Get the total sum of all elements
for (int num : nums) {
totalSum += num;
}

// 2. Calculate rightSum and difference on the fly
for (int i = 0; i < n; i++) {
int rightSum = totalSum - leftSum - nums[i];
ans[i] = Math.abs(leftSum - rightSum);

// Update leftSum for the next index
leftSum += nums[i];
}

return ans;
}
  1. Time Complexity: O(n)
  2. Space Complexity: O(1) (Excluding the output array).


๐Ÿ“Š Summary Comparison

FeatureApproach 1Approach 2
Space ComplexityO(n) (Higher)O(1) (Optimal)
Logic TypeStorage-basedMathematical
Use CaseBeginnersInterviews


Key Takeaway

While Approach 1 is easier to visualize, Approach 2 is more professional. It shows you can handle data efficiently without unnecessary memory allocation, which is critical when dealing with large-scale systems.

Ai Assistant Kas