Google&Facebook Interview - Find subarray with given sum

Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.

Examples:

Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Ouptut: Sum found between indexes 1 and 4

Input: arr[] = {1, 4}, sum = 0
Output: No subarray found

There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray.

 

public boolean subArraySumK(int[] A, int k) {
	int n = A.length;
	if(n == 0) return false;
	int start = 0, sum = 0;
	for(int i=0; i<n; i++) {
		sum += A[i];
		while(sum > k && start < i) {
			sum -= A[start++];
		}
		if(sum == k) {
			System.out.println("find subarray from "+start +" to " + i);
			return true;
		}
	}
	System.out.println("no subarray found");
	return false;
}

Time complexity of this method looks more than O(n), but if we take a closer look at the program, then we can figure out the time complexity is O(n). We can prove it by counting the number of operations performed on every element of arr[] in worst case. There are at most 2 operations performed on every element: (a) the element is added to the curr_sum (b) the element is subtracted from curr_sum. So the upper bound on number of operations is 2n which is O(n).

 

Reference:

http://www.geeksforgeeks.org/find-subarray-with-given-sum/

你可能感兴趣的:(interview)