Microsoft Interview Question for SDE1s


Country: India




Comment hidden because of low score. Click to expand.
2
of 4 vote

You can solve this one in linear time using dynamic programing, hear me out.

Basically 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.

- thinksmart April 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- thinksmart April 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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) .

- Anonymous July 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you elaborate more on this?

- ami November 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you please explain this with an example?

- ami November 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you please explain this with an example?

- ami November 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- IntwPrep.MS December 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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!!!

- poorvisha April 08, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

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.

- Lite April 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;		
	}

- m@}{ April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Sharp April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

obviously you can't populate o(n^2) space under o(n) time.

- chk June 09, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- aka April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
	}

- Dhass April 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O

- hbrkanwei April 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

It is NPC - a variation of subset sum

- pras June 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a

- a August 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

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,[])
}}

- Sandy April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you please explain this with an example?

- CodeNameEagle April 17, 2013 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More