20. Subarray with 0 sum

20. Subarray with 0 sum


Problem link :- click here


package programs;

import java.util.*;

public class Array__20
{
	
	static Boolean subArrayWithSunZero(int arr[], int n)
	{
		HashSet<Integer> sum_in_each_step = new HashSet<>();
		
		int sum = 0;
		for(int i=0; i<n; i++)
		{
			sum = sum + arr[i];
			if(sum==0  ||  arr[i]==0  ||  sum_in_each_step.contains(sum))
				return true;
			
			//since we cannot subtract elements added before 
			//if we store sum of each step in some data structure 
			//and if it repeats 
			//                       which means we added nothing but zero
			//                       which in-turn means we just passed a 
			//                                     sub-array with sum zero
			sum_in_each_step.add(sum);
		}
		return false;
	}

	public static void main(String[] args)
	{
		int n, i;
		Boolean ans;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the size of the array : ");
		n = s.nextInt();
		int array[] = new int[n];
		System.out.println("Enter the elements of the array :");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		
		System.out.println("Given array : ");
		print_array(array, n);
		
		ans = subarraySum0(array, n);
		if(ans == true )
			System.out.println("\n\nFound a Subarray sum 0");
		else
			System.out.println("\n\nNo such subarray exists");
	}

	static void print_array(int arr[], int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(n)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree