Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create subarray_withzerosum.java #614

Merged
merged 2 commits into from
Oct 11, 2021

Conversation

HarshS1611
Copy link
Contributor

Problem

  • Given an array of positive and negative numbers, find if there is a subarray (of size at-least one) with 0 sum.

Solution

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class subarray_withzerosum {
static Boolean subArrayExists(int arr[]) {
Set hs = new HashSet();
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (arr[i] == 0 || sum == 0 || hs.contains(sum))
return true;
hs.add(sum);
}

        return false;
    }
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int n=sc.nextInt();
        int arr[] = new int[n];
        for (int i=0;i<n;i++){
            arr[i]=sc.nextInt();
        }
        if (subArrayExists(arr))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

Changes proposed in this Pull Request :

  • 1.
  • 2.
  • ..

Other changes

@fineanmol fineanmol merged commit be612a7 into fineanmol:master Oct 11, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants