Coding Solution 01
Write a Java program to check if a given array contains a subarray with 0 sum and to print all sub-arrays with 0 sum present in the given array of integers.
Code:
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.*;
import java.lang.*;
class solution
{
public static Boolean find_subarray_sum_zero(int[] nums)
{
Set<Integer> set = new HashSet<>();
set.add(0);
int suba_sum = 0;
for (int i = 0; i < nums.length; i++)
{
suba_sum += nums[i];
if (set.contains(suba_sum)) {
return true;
}
set.add(suba_sum);
}
return false;
}
public static void print_all_Subarrays(int[] A)
{
List<Integer> llist = new ArrayList<Integer>();
for (int i = 0; i < A.length; i++)
{
int sum = 0;
llist.removeAll(llist);
for (int j = i; j < A.length; j++)
{
sum += A[j];
llist.add(A[j]);
if (sum == 0) {
System.out.println("Sub-arrays with 0 sum : " + llist.toString());
}
}
}
}
public static void main (String[] args)
{
int[] nums1 = { 1, 3, -7, 3, 2, 3, 1, -3, -2, -2 };
System.out.println("\nOriginal array: "+Arrays.toString(nums1));
System.out.println("Does the said array contain a subarray with 0 sum: "+find_subarray_sum_zero(nums1));
if(find_subarray_sum_zero(nums1))
print_all_Subarrays(nums1);
int[] nums2 = { 1, 2, -3, 4, 5, 6 };
System.out.println("\nOriginal array: "+Arrays.toString(nums2));
System.out.println("Does the said array contain a subarray with 0 sum: "+find_subarray_sum_zero(nums2));
if(find_subarray_sum_zero(nums2))
print_all_Subarrays(nums2);
int[] nums3= { 1, 2, -2, 3, 4, 5, -1, -10, 6 };
System.out.println("\nOriginal array: "+Arrays.toString(nums3));
System.out.println("Does the said array contain a subarray with 0 sum: "+find_subarray_sum_zero(nums3));
if(find_subarray_sum_zero(nums3))
print_all_Subarrays(nums3);
int[] nums4= { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("\nOriginal array: "+Arrays.toString(nums4));
System.out.println("Does the said array contain a subarray with 0 sum: "+find_subarray_sum_zero(nums4));
if(find_subarray_sum_zero(nums4))
print_all_Subarrays(nums4);
}
}
Output:
| Output 1.1 |
| Output 1.2 |
Link: https://ide.geeksforgeeks.org/eGhlYJBATk
I hereby confirm that the coding solution is written by me and complied & run at GreeksForGreeks Online Complier.
#MAR #MARACTIVITY #MARPOINTS #MAKAUT #SKFGI #CODINGSOLUTION
#mar #maractivity #marpoints #makaut #skfgi #codingsolution
Comments
Post a Comment