Skip to content

Instantly share code, notes, and snippets.

@arafatkamaal
Last active November 23, 2019 07:04
Show Gist options
  • Save arafatkamaal/460c8e5e578f1bae9ad9b5caf40999f3 to your computer and use it in GitHub Desktop.
Save arafatkamaal/460c8e5e578f1bae9ad9b5caf40999f3 to your computer and use it in GitHub Desktop.
Zero Sum Subarrays
//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]);
}
}
}
@arafatkamaal
Copy link
Author

$ 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment