Leetcode 2574. Left and Right Sum Differences
Given a 1-indexed integer array nums
, you are asked to return an array answer
of length n
where answer[i]
is the absolute difference between the sum of elements to the left of index i
and the sum of elements to the right of index i
.
More formally, answer[i] = |leftSum[i] - rightSum[i]|
.
Where:
leftSum[i]
is the sum of the elements to the left of index i
.rightSum[i]
is the sum of the elements to the right of index i
.Given leftSum[i] and rightSum[i] , compute the absolute difference ( |
leftSum[i] - rightSum[i] | ). |
#include <vector>
#include <cmath>
#include <iostream>
std::vector<int> leftRightDifference(const std::vector<int>& nums) {
int n = nums.size();
std::vector<int> answer(n);
std::vector<int> prefixSum(n, 0);
// Compute prefix sum
prefixSum[0] = nums[0];
for (int i = 1; i < n; ++i) {
prefixSum[i] = prefixSum[i - 1] + nums[i];
}
// Compute the total sum of the array
int totalSum = prefixSum[n - 1];
// Compute the result
for (int i = 0; i < n; ++i) {
int leftSum = (i == 0) ? 0 : prefixSum[i - 1];
int rightSum = totalSum - prefixSum[i];
answer[i] = std::abs(leftSum - rightSum);
}
return answer;
}
// Helper function to print the vector
void printVector(const std::vector<int>& vec) {
std::cout << "[ ";
for (const int& value : vec) {
std::cout << value << " ";
}
std::cout << "]" << std::endl;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
std::vector<int> result = leftRightDifference(nums);
printVector(result);
return 0;
}
Thus, the overall time complexity is O(n), where (n) is the number of elements in the input array.
This solution is efficient and handles the constraints effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?