Similar Problems

Similar Problems not available

Zero sum subarray - Leetcode Solution

Companies:

LeetCode:  Zero sum subarray Leetcode Solution

Difficulty: Unknown

Topics: hash-table  

Given an array, find any subarray with sum as zero.

Example Test Cases

Sample Test Case 1

Input Array: 1, 2, -5, 3, -4,
Expected Output: 1, 3
Explanation: Since the sum of subarray b/w indices 1 and 3 is 0

Sample Test Case 2

Input Linked List: 1, 2, 3, 4, 5, 0, 6, 3
Expected Output: 5, 5

Solution

We can solve this problem by taking constructing a cumulative sum array and by using a hash table. Let the main array be called arr and cumulative sum array be called cu . cu will store the cumulative sum of all elements starting from position 0 till n - 1
Therefore, we can write: cu[k] = arr[0] + arr[1] + arr[2] + .... arr[k]
If the sum of subarray from index i + 1 till index j is 0, it means that cu[j] = cu[i] Therefore, we can create a hashmap with key as the sum and value as the index till which the sum was calculated, and check for duplicates.
See the below code for implementation.

Zero sum subarray Solution Code

1