Challenge 6: A Subarray with a Sum of 0

In this exercise, you will find a subarray whose sum turns out to be zero. Let's try it out!

Problem statement

You must implement the bool findSubZero(int[] arr, int size) function, which will take in an array of positive and negative integers. It will tell you if there exists a subarray in which the sum of all elements is zero. The term “subarray” implies that the elements whose sum is 0 must occur consecutively.

An array with these contents would return true:

{6, 4, -7, 3, 12, 9}

Whereas, this would return false as the elements which sum up to be 0 do not appear together:

{-7, 4, 6, 3, 12, 9}

Input

This is an array containing positive and negative integers and its size.

Output

It returns true if there exists a subarray with its sum equal to 0. Otherwise, the function returns false.

Sample input

arr = {6, 4, -7, 3, 12, 9} 
size = 6

Sample output

true

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.