Last active
November 23, 2019 07:04
-
-
Save arafatkamaal/460c8e5e578f1bae9ad9b5caf40999f3 to your computer and use it in GitHub Desktop.
Zero Sum Subarrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/ | |
import java.util.ArrayList; | |
public class PrefixSum { | |
public static int[] recoverOriginalArray(int[] array) { | |
int l = array.length; | |
int[] result = new int[l]; | |
result[0] = array[0]; | |
for(int i = 1; i < l; i++) { | |
result[i] = array[i] - array[i - 1]; | |
} | |
return result; | |
} | |
public static int[] prefixSum(int[] array) { | |
int l = array.length; | |
int[] result = new int[l]; | |
result[0] = array[0]; | |
for(int i = 1; i < l; i++) { | |
result[i] = result[i - 1] + array[i]; | |
} | |
return result; | |
} | |
//Subarray's with 0 sum | |
public static ArrayList<int[]> countZeroSumSubArrays(int[] array) { | |
int l = array.length; | |
int sum = 0; | |
ArrayList<int[]> result = new ArrayList<>(); | |
for(int i = 0; i < l; i++) { | |
for(int j = i; j < l; j++) { | |
sum += array[j]; | |
if(sum == 0) { | |
result.add(new int[] {i, j}); | |
} | |
} | |
sum = 0; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
System.out.println("Beginning of the program"); | |
int[] a = prefixSum(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}); | |
for(int i = 0; i < a.length; i++) { | |
System.out.print(a[i] + " "); | |
} | |
System.out.println(); | |
int[] recovered = recoverOriginalArray(a); | |
for(int i = 0; i < recovered.length; i++) { | |
System.out.print(recovered[i] + " "); | |
} | |
System.out.println(); | |
ArrayList<int[]> result = countZeroSumSubArrays(new int[] {3, 2, -1, 1, 1, -1, 2, 3, -3, 6, 2, -8, 10}); | |
System.out.println("The following " + result.size() + " results were found"); | |
for(int[] r: result) { | |
System.out.println(r[0] + ", " + r[1]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ java PrefixSum
Beginning of the program
1 3 6 10 15 21 28 36 45 45
1 2 3 4 5 6 7 8 9 0
The following 6 results were found
2, 3
2, 5
4, 5
7, 8
7, 11
9, 11