VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sub-array-sum-closest-0/

⇱ Find the Sub-array with sum closest to 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Sub-array with sum closest to 0

Last Updated : 15 Sep, 2023

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:


Output
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:-

  • Maintain a Prefix sum array . Also maintain indexes in the prefix sum array.
  • Sort the prefix sum array on the basis of sum.
  • Find the two elements in a prefix sum array with minimum difference. 
i.e. Find min(pre_sum[i] - pre_sum[i-1]) 
  • Return indexes of pre_sum with minimum difference.
  • Subarray with (lower_index+1, upper_index) will have the sum closest to 0.
  • Taking lower_index+1 because on subtracting value at lower_index we get the sum closest to 0. That's why lower_index need not to be included.

Implementation:


Output
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.

Comment
Article Tags:
Article Tags: