![]() |
VOOZH | about |
Given an array of both positive and negative numbers, the task is to find out the subarray whose sum is closest to 0.
There can be multiple such subarrays, we need to output just 1 of them.
Examples:
Input : arr[] = {-1, 3, 2, -5, 4}
Output : 1, 3
Subarray from index 1 to 3 has sum closest to 0 i.e.
3 + 2 + -5 = 0
Input : {2, -5, 4, -6, 3}
Output : 0, 2
2 + -5 + 4 = 1 closest to 0
Asked in : Microsoft
A Naive approach is to consider all subarrays one by one and update indexes of subarray with sum closest to 0.
Implementation:
Subarray starting from 0 to 2
Time Complexity: O(n2)
Space Complexity: O(1) as no extra space has been used.
An Efficient method is to perform following steps:-
i.e. Find min(pre_sum[i] - pre_sum[i-1])
Implementation:
Subarray starting from 0 to 3
Time Complexity: O(n log n)
Space Complexity: O(n) as pre_sum array has been created. Here, n is size of input array.