#2574
Easy Algorithms Left and right sum differences
Array Prefix Sum
87.9% acceptance
Feb 25, 2026
1244
115
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 index i in the array nums. If there is no such element, leftSum[i] = 0.
rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0.
Return an integer array answer of size n where answer[i] = |leftSum[i] - rightSum[i]|.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn left_right_difference(nums: Vec<i32>) -> Vec<i32> {
let total: i32 = nums.iter().sum();
let mut left = 0i32;
let mut result = Vec::with_capacity(nums.len());
for &x in &nums {
let right = total - left - x;
result.push((left - right).abs());
left += x;
}
result
}
}