Microsoft Interview Question
SDE1sCountry: India
Actually I am partially off on this since the answer to print is not linear. My solution is basically linear to output.
eg: For an array 0000, the answer itself is n^2.
Does this solution prints subarray ( 2, 3 ) in input arr[] = { 1, -1, 4, -4 } ?
I guess we need to apply your algorithm for every start point ( i = 0 to n-1 ) which boils down to o(n^2) .
This should work. But the actual process of getting subarray intervals can render this algorithm O(C(K,2)) where K is the maximum number of indices for a given sum.
i got your point. the below soln will work for sure..try it!!!
algorithm that solves problem in linear time:
1.store the sum in an array from start till the point.
2.maintain the counts of sum in hash table
3.if there exists sum == 0 in the hash table, count of 0 = count of 0 + 1
4.for sum whose count == 2
no_of_sub-arrays = no_of_sub-arrays + 1;
else
for sum whose count > 2 ,let n = count
no_of_sub-arrays = no_of_sub-arrays + nC2 ,C denotes combination
5.repeat step 4 for all sums in hash table
6.print no_of_sub-arrays.
that's it!!!
Given array arr, create array run so that run[i] = sum(arr[0..i]), you can do this in linear time. Now look for duplicate entries in run. You can do this by scanning over it, checking if an element is in the hashmap, if yes we have a duplicate and so a sum to zero, if not add it to the map.
Bruteforce solution. time: O(N^2), space: O(1)
public static List<int[]> zeroSubarrays( int[] arr ){
List<int[]> subarrays = new ArrayList<>();
for( int i = 0; i < arr.length; i++ ){
int sum = 0;
for( int j = i; j < arr.length; j++ ){
sum += arr[j];
if( sum == 0 ){
subarrays.add( Arrays.copyOfRange(arr, i, j+1) );
}
}
}
return subarrays;
}
This solution uses O(n square) space, O(n) time -
calc all subarray sums & store in a 2D matrix (actually uses only half the matrix)
print subarrays as you find 0 subarray sums
void SubSums(vector<int> &arr, vector<vector<int>> &sums) {
int i=0, j=0, k=0;
for (i=0; i<arr.size(); i++) {
for (j=0; j<=i; j++) {
if (i==j) sums[i][j] = arr[i];
else sums[i][j] = sums[i-1][j]+arr[i];
// print subarray from i till j
if (!sums[i][j]) {
k=j;
while (k<=i) {
cout << arr[k];
k++;
}
cout << endl;
}
}
}
}
void FindAndPrint(vector<int> &arr) {
vector<vector<int>> sums;
int i=0;
sums.resize(arr.size());
for(i=0; i<arr.size(); i++) {
sums[i].resize(i);
}
SubSums(arr, sums);
}
void main() {
vector<int> arr;
int s, i=0, val;
cout << "input size";
cin >> s;
while (i<s) {
cin >> val;
arr.push_back(val);
i++;
}
FindAndPrint(arr);
cin >> val;
}
solve using subset sum problem with one additional constraint, which is to find only two elements which add up to k.
Using binary tree example as explained in this paper.Very nice approach.
www dot wou.edu/~broegb/Cs345/SubsetSum.pdf
#define SIZE(a) sizeof(a)/sizeof(a[0])
int visited[100];
int a[] = {-5, -4, -1, 1, 4, 5};
int r[100];
int sum = 0;
void r_ss(int s, int k)
{
r[k] = 1;
if(s+a[k] == sum) {
int i, count=0;
// make ifdef 0 to print all the solutions
#if 1
for(i=0;i<SIZE(a);i++) {
if(r[i])
count++;
if(count > 2) {
r[k] = 0;
return;
}
}
#endif
for(i=0;i<SIZE(a);i++) {
if(r[i])
printf("found %d\n", a[i]);
}
r[k] = 0;
printf("got it\n");
return;
}
if((k+1<=SIZE(a)) &&((s+a[k]) <= sum))
r_ss(s+a[k], k+1);
if((k+1<=SIZE(a)) &&((s+a[k+1]) <= sum)) {
r[k] = 0;
r_ss(s, k+1);
}
}
int main()
{
memset(r, 0, sizeof(int)*100);
r_ss(0, 0);
return 0;
}
Code:
public void printSubArraysSumZero(int a[]) {
int s[] = new int[a.length];
int l = a.length;
for (int i = 0; i < l; i++) {
if (i == 0)
s[i] = a[i];
else
s[i] = s[i - 1] + a[i];
}
HashMap<Integer, ArrayList<Integer>> h = new HashMap<Integer, ArrayList<Integer>>();
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(-1);
h.put(0, t);
for (int i = 0; i < l; i++) {
if (h.containsKey(s[i])) {
for (Integer v : h.get(s[i]))
printArray(a, v + 1, i);
h.get(s[i]).add(i);
} else {
ArrayList<Integer> in = new ArrayList<Integer>();
in.add(i);
h.put(s[i], in);
}
}
}
public void printArray(int a[], int i, int j) {
for (int n = i; n <= j; n++)
System.out.print(a[n] + " ");
System.out.println();
}
edit
it will require O(n^2)
using recursion here
{{
def findSum(array,index,sum,path):
if index >= len(array):
return
sum = sum + array[index]
path.append(array[index])
if sum == 0 :
print path
findSum(array,index+1,sum,path)
findSum(array,index+1,0,[])
}}
You can solve this one in linear time using dynamic programing, hear me out.
- thinksmart April 17, 2013Basically you store the sum in an array from start till the point. That can be done in 1 pass. After that basically you look for twins in the array and all numbers in b/w are subsets of 0.
Its basically because numbers that add to 0 do not change the total sum of all numbers.