Facebook Interview Question for Interns


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
7
of 9 vote

public static boolean solution(int[] nums, int target) {
        if(nums.length == 0) {
            return target == 0;
        }
        int start = 0;
        int end = 0;
        int sum = nums[0];
        if (sum == target) {
            return true;
        }
        while(end < nums.length) {
            if(sum > target) {
                sum -= nums[start];
                start++;
            } else {
                end++;
                if(end < nums.length) {
                    sum += nums[end];
                }
            }
            if (sum == target) {
                return true;
            }
        }
        return false;
    }

- Irit October 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

That's a java linear-time constant space solution. Starts from an interval that contains only the first elements, then grows it to the right when its sum is too small and shrinks it on the left when its sum is too large.

- Irit October 28, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 votes

This only works if the input array is sorted, and in particular in ascending ordee

- Anonymous October 29, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 votes

This only works if the input array is sorted

- Anon October 29, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What? No it doesn't, it works for any array sorted or unsorted.

- Anonymous October 29, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This works for any array with non-negative elements, good job.

- Anonymous October 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous, no, this solution is correct.
Since all numbers are positive, array of partial sums is strictly increasing.
Now you are given an array of strictly increasing elements and have to answer in linear time if there are two elements that aj - ai = delta, j > i
So the dumb approach would be to binary search for j for every index i.
Then we see that if we increase i, the second index j will only increase, it can't decrease. So we just move j until aj - ai < delta (if aj - ai = delta, we've found the solution) and then do i = i + 1 after that.

- emb October 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What is the logic ? Can anyone please explaine

- sandhyalalkumar October 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

I think the code works for only sorted arrays.

- ducalpha November 08, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This solution doesn't take into account targets of values that are already included in the array. They will return false each time, which isn't a correct solution.

- steve November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This works. It must be consecutive integers not random integers within the array.

- Anonymous November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

O(n) solution

class Solution {
  
  public static boolean containsSubarray(int[] numbers, int target){
    //input numbers is all positive
    if(target < 0) return false;
    if(target == 0) return true;
    
    int startIndex = 0;
    int runningSum = 0;
    
    for(int i = 0; i < numbers.length; i++){
      runningSum += numbers[i];
      while(runningSum > target && startIndex < i){
        runningSum -= numbers[startIndex];
        startIndex ++;
      }
      if(runningSum == target){
        return true;
      }
    }
    
    return false;
  }
  
  public static void main(String[] args) {
    int[] numbers = new int[]{1, 1, 3, 5, 7, 9};
    int target = 8;
    
    System.out.println( containsSubarray(numbers, target) );
  }
}

- Meow October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you please explain why it is O(n)? I think it should be O(n^2). Thank you.

- Hello October 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Each element is visited at most twice, once for adding to sum, once for removing from sum. Thus runtime complexity is O(n).

- George.Zhi.Xu February 14, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java code

private static boolean addEls(int n, int[] els) {
    
    
    // key will be sum 
    // array list will be the integers that have been added together 
    HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>(); 
     
      
      for (int i = 0; i < els.length; i ++) {
        for (int j = 1; j < els.length-1; j++) {
          Integer sum = new Integer(i+j);
          
          ArrayList<Integer> sumFactors = hm.get(sum); 
          
          if (sumFactors == null)
            sumFactors = new ArrayList<Integer>();
          
          sumFactors.add(new Integer(i));
          sumFactors.add(new Integer(j));
          
          hm.put(sum, sumFactors); 
          
        }    
      }
    
    return (hm.containsKey(n));
    
    
  }

- SMAY October 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static boolean addEls(int n, int[] els) {
    
    
    // key will be sum 
    // array list will be the integers that have been added together 
    HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>(); 
     
      
      for (int i = 0; i < els.length; i ++) {
        for (int j = 1; j < els.length-1; j++) {
          Integer sum = new Integer(i+j);
          
          ArrayList<Integer> sumFactors = hm.get(sum); 
          
          if (sumFactors == null)
            sumFactors = new ArrayList<Integer>();
          
          sumFactors.add(new Integer(i));
          sumFactors.add(new Integer(j));
          
          hm.put(sum, sumFactors); 
          
        }    
      }
    
    return (hm.containsKey(n));
    
    
  }

- Smay October 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static boolean doesSumToTarget(int arr[], int target) {
		if (arr[0] == target) return true;
		if (arr.length < 2) return false;
		int left = 0,  right = 1, sum = arr[0];
		while (right < arr.length + 1) {
			
			if (sum < target)  {
				if (right < arr.length)
					sum += arr[right++];
			}
			else if (sum > target) {
				sum -= arr[left++];
				if (left == right && right < arr.length) 
					sum += arr[right++];
			}
			else {
				System.out.print("{ ");
				for (int i = left; i < right; i++)
					System.out.print(String.valueOf(arr[i]) + " ");
				System.out.println("}");
				return true;
			}

		}
		return false;
	}

input:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(doesSumToTarget(arr, 7));

output:

{ 3 4 }
true

- effy October 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

for (i = 0;i< SIZE;i++)
	S[i] = s[i] + a[i]

for (i=0;i<size-1;i++)
  for (j=i;j<size;j++)
	if (s[i] - s[j]) == target
		print i, j

- aka[1] October 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This will give you a time complexity of O(n^2), which is undesired. Try to do better than that.

- Steve November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Instead of using the nested for loops, Just use a hash to keep all the sum.

Finding sum = O(n)
Creating the hash O(n)
For each element check in has if there exists a number == required_sum - current_num
if yes return true
else return false

Overall complexity = O(n)

- Ankur December 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static ArrayList sum_target(int arr[],int target)
{


ArrayList<Integer> res=new ArrayList<>();


int sum=0;

if(arr.length<=1)
return res;

int i=0,j=arr.length;

for(i=0;i<arr.length;i++)
{

j=i;
sum=0;
while(sum<target)
{
sum+=arr[j++];
}
//System.out.println(sum);

if(sum==target)
{
break;
}

}

for(int k=i;k<j;k++)
res.add(arr[k]);


return res;


}

- sameh.shohdy84 October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c++, implementation, O(n^2)

typedef long long INT64;

bool consecutiveSubSum(vector<int>& arr, int target) {
	vector<INT64> subsum;
	int i, j;

	subsum.assign(arr.size() + 1, 0);

	for (i = 0; i < arr.size(); i++) {
		subsum[i + 1] = subsum[i] + arr[i];
	}

	for (i = 0; i < subsum.size(); i++) {
		for (j = 0; j < i; j++) {
			if (subsum[i] - subsum[j] == target) return true;
		}
	}

	return false;
}

- kyduke October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
public static boolean isTargetNumberPossible(int aTargetNumber, int[] array) {
int count = 0;
int temp = 0;
boolean startIndexFlag = true;
int startIndex = -1;
while (count < array.length) {
if (temp == aTargetNumber) {
System.out.println("Sum is possible");
return true;
} else if (temp < aTargetNumber) {
temp = temp + array[count];
if (startIndexFlag) {
startIndex = count;
startIndexFlag = false;
}
count++;
} else {
count = startIndex + 1;
temp = temp - array[startIndex];
startIndexFlag = true;
startIndex = count;
}

}

return false;

}
}

- Anonymous October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isTargetNumberPossible(int aTargetNumber, int[] array) {
		int count = 0;
		int temp = 0;
		boolean startIndexFlag = true;
		int startIndex = -1;
		while (count < array.length) {
			if (temp == aTargetNumber) {
				System.out.println("Sum is possible");
				return true;
			} else if (temp < aTargetNumber) {
				temp = temp + array[count];
				if (startIndexFlag) {
					startIndex = count;
					startIndexFlag = false;
				}
				count++;
			} else {
				count = startIndex + 1;
				temp = temp - array[startIndex];
				startIndexFlag = true;
				startIndex = count;
			}

		}

		return false;

	}

- Anonymous October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isTargetNumberPossible(int aTargetNumber, int[] array) {
		int count = 0;
		int temp = 0;
		boolean startIndexFlag = true;
		int startIndex = -1;
		while (count < array.length) {
			if (temp == aTargetNumber) {
				System.out.println("Sum is possible");
				return true;
			} else if (temp < aTargetNumber) {
				temp = temp + array[count];
				if (startIndexFlag) {
					startIndex = count;
					startIndexFlag = false;
				}
				count++;
			} else {
				count = startIndex + 1;
				temp = temp - array[startIndex];
				startIndexFlag = true;
				startIndex = count;
			}

		}

		return false;

	}

- ckverma October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Linear time (O(n)) solution.

class Solution {
  
  public static boolean containsSubarray(int[] numbers, int target){
    //input numbers is all positive
    if(target < 0) return false;
    if(target == 0) return true;
    
    int startIndex = 0;
    int runningSum = 0;
    
    for(int i = 0; i < numbers.length; i++){
      runningSum += numbers[i];
      while(runningSum > target && startIndex < i){
        runningSum -= numbers[startIndex];
        startIndex ++;
      }
      if(runningSum == target){
        return true;
      }
    }
    
    return false;
  }
  
  public static void main(String[] args) {
    int[] numbers = new int[]{1, 1, 3, 5, 7, 9};
    int target = 8;
    
    System.out.println( containsSubarray(numbers, target) );
  }
}

- Anonymous October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void targetNo(int iArr[SIZE],int iTarget)
{
	int sum =0;
	for(int j=0,i=0;i<SIZE;i++)
	{
		if(sum < iTarget)
		{
			sum = sum + iArr[i];
			if(sum > iTarget && i==SIZE-1)
			{
				sum = iArr[i] + iArr[i-1];
				j=i-1;
			}
		}
		else
		{
			j=j+1;
			sum =iArr[j];
			i=j;
			continue;
		}
		if(sum == iTarget)
		{
			cout << endl;
			for(int k =j;k<=i;k++)
			cout << iArr[k] << " ";
			break;
		}
	}
}

- sv October 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@kyduke, I as well started with subsums, but then instead of doing N^2 comparisons treated this as 2SUM problem, where a-b=TargetSum and 'a' and 'b' are from the subsums array.

public class SubArrayWithSum {
	
	public boolean hasSubArrayWithSum(int[] input, int sum) {
		return getSubArrayWithSum(input, sum) != null;
	}
	
	public int[] getSubArrayWithSum(int[] input, int sum) {
				
		int[] subSumArr = getSubSums(input);
		
		Map<Integer, Integer> pairsMap = new HashMap<>();
		for (int i =0; i<subSumArr.length; i++) {
			if (pairsMap.containsKey(Integer.valueOf(subSumArr[i]))) {
				return subArray(input, pairsMap.get(subSumArr[i]), i-1);
			} else {
				pairsMap.put(sum + subSumArr[i], Integer.valueOf(i));
			}
		}
		return null;
		
	}

	private int[] subArray(int[] input, int start, int end) {
		int[] subArr = new int[end-start+1];
		for(int i = 0; i<subArr.length; i++) {
			subArr[i] = input[i+start];
		}
		
		return subArr;
	}

	private int[] getSubSums(int[] input) {
		int[] subSums = new int[input.length+1];
		subSums[0] = 0;
		for (int i = 1; i<=input.length; i++) {
			subSums[i] = subSums[i-1] + input[i-1];
		}
		return subSums;
	}

}

- blckembr October 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C++ implementation using recursion.

using namespace std;
#include <iostream>
#include <vector>

bool addUpToTarget(vector<int> & array, int target, int startIndex, int endIndex) {
    for(int i= startIndex; i <= endIndex; ++i) {
        if(target == array[i]) {
            return true;
        } else if(target > array[i]) {
            int newTarget = target - array[i];
            if(addUpToTarget(array, newTarget, i+1, endIndex)) {
                return true;
            }
        }
    }
    return false;
}

- Newbie October 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public boolean findTargetSumInArray(int target, int[] input){
		if(target <=0) return false;
			
		int j=0;
		int sum =0;
		for(int i=0; i<input.lengh; i++){
			sum+=input[i];
			while(sum > target && j != 0){
				j--;
				sum -=input[j];	
			}
			if(sum == target){
				return true;	
			}
		}
		return false;
	}

- PJain October 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def cons_sum(numbers, sum):
    start_idx = 0
    end_idx = 0
    calc_sum = numbers[0]
    while start_idx <= end_idx and end_idx < len(numbers):
        if calc_sum == sum:
            return numbers[start_idx:end_idx+1]
        elif calc_sum < sum:
            end_idx += 1
            if end_idx < len(numbers):
                calc_sum += numbers[end_idx]
        else:
            calc_sum -= numbers[start_idx]
            start_idx += 1
            if end_idx < start_idx:
                end_idx = start_idx
    return []

- rizTaak November 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Saw a similar solution but wanted to post, The idea is to use two index and the sum of the values between them, the values are add/subtracted according to the target value, at the same time a list with this values is updated

public List<int> FindSubList(int[] values, int target)
{
	List<int> result = new List<int>();

	if (values == null || values.Length == 0)
		return result;

	int start = 0;
	int end = 0;
	int sum = values[0];
	result.Add(sum);

	while (end < values.Length)
	{
		if (sum == target)
			return result;

		if (sum < target)
		{
			end++;
			if (end < values.Length)
			{
				sum += values[end];
				result.Add(values[end]);
			}
		}
		else
		{
			sum -= values[start];
			start++;
			result.RemoveAt(0);
		}
	}

	result.Clear();
	return result;
}

- hnatsu November 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript:

function hasSum(arr, target){
    if (arr.length == 1){
    	if (arr[0] == target) return true;
        else return false;
    }
	for (var i=1; i<arr.length; i++){
        var sum = 0;
        var trace = [];
    	for (var j=0; j<=i; j++){
    		sum += arr[j];
            if (sum == target) return true;
    	}
    }
    arr.shift();
    return hasSum(arr, target);
}

- Anonymous November 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function hasSum(arr, target){
if (arr.length == 1){
if (arr[0] == target) return true;
else return false;
}
for (var i=1; i<arr.length; i++){
var sum = 0;
var trace = [];
for (var j=0; j<=i; j++){
sum += arr[j];
if (sum == target) return true;
}
}
arr.shift();
return hasSum(arr, target);
}

- Master November 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def sum_target(A, target):
    for i in range(len(A)):
        k = 0
        for j in range(i, len(A)):
            k += A[j]
            if k == target:
                return A[i:j+1]
    return("no consecutive sum found")

z = sum_target([1, 2, 3, 5, 7], 6)
print(z)

- anish531213 November 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void consecutivesum()
{
	int[] ele = {1,3,5,7,9};
	int target = 16;
	int beginIdx= 0;
	int endIdx = 1;
	int tempSum = ele[beginIdx];
	while(beginIdx <= endIdx && endIdx < ele.length)
	{
		if(tempSum == target)
		{
			System.out.print("{");
			for(int i = beginIdx;i < endIdx;i++)
			{
				System.out.print(""+i);
			}
			System.out.print("}");
			return;
		}
		
		if(tempSum < target)
		{
			tempSum += ele[endIdx];
			endIdx++;
		}
		else{
			tempSum -= ele[beginIdx];
			beginIdx++;
			
		}
	}
}

- Simple O(n) solution November 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void consecutivesum()
{
	int[] ele = {1,3,5,7,9};
	int target = 15;
	int beginIdx= 0;
	int endIdx = 1;
	int tempSum = ele[beginIdx];
	while(beginIdx <= endIdx && endIdx < ele.length)
	{
		if(tempSum == target)
		{
			System.out.print("{");
			for(int i = beginIdx;i < endIdx;i++)
			{
				System.out.print(""+ele[i]);
			}
			System.out.print("}");
			return;
		}
		
		if(tempSum < target)
		{
			tempSum += ele[endIdx];
			endIdx++;
		}
		else{
			tempSum -= ele[beginIdx];
			beginIdx++;
			
		}
	}
	
	System.out.println("No solution\n");
}

- CodeKnight November 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void findSegment(int *arr, int n, int target){
    // closest is the closest position on the left such that sum from closest to current position
    // is greater or equal target
    int closest = -1; //doesn't exist initially
    int* sum = new int[n];
    int* res = NULL;
    for (int i = 0; i < n; i++){
        //sum[i]: sum of the first i+1 elements
        if (i == 0) sum[i] = arr[i]; else sum[i] = sum[i-1] + arr[i];
        if (sum[i] < target) continue;
        // find new closest
        if (closest == -1)
            if (sum[i] >= target) closest = 0;
        while (closest <= i && sum[i] - sum[closest] + arr[closest] >= target){
            closest++;
        }
        closest--;

        if (sum[i] - sum[closest] + arr[closest] == target) {
            for (int j = 0; j < i - closest + 1; j++)
                cout << arr[closest + j] << " " ;
            return;
        }
    }
    cout << "No solution !" << endl;
}

}

- Cuong Nguyen November 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void findSegment(int *arr, int n, int target){
    // closest is the closest position on the left such that sum from closest to current position
    // is greater or equal target
    int closest = -1; //doesn't exist initially
    int* sum = new int[n];
    int* res = NULL;
    for (int i = 0; i < n; i++){
        //sum[i]: sum of the first i+1 elements
        if (i == 0) sum[i] = arr[i]; else sum[i] = sum[i-1] + arr[i];
        if (sum[i] < target) continue;
        // find new closest
        if (closest == -1)
            if (sum[i] >= target) closest = 0;
        while (closest <= i && sum[i] - sum[closest] + arr[closest] >= target){
            closest++;
        }
        closest--;

        if (sum[i] - sum[closest] + arr[closest] == target) {
            for (int j = 0; j < i - closest + 1; j++)
                cout << arr[closest + j] << " " ;
            return;
        }
    }
    cout << "No solution !" << endl;

}

- Cuong Nguyen November 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void findSegment(int *arr, int n, int target){
    // closest is the closest position on the left such that sum from closest to current position
    // is greater or equal target
    int closest = -1; //doesn't exist initially
    int* sum = new int[n];
    int* res = NULL;
    for (int i = 0; i < n; i++){
        //sum[i]: sum of the first i+1 elements
        if (i == 0) sum[i] = arr[i]; else sum[i] = sum[i-1] + arr[i];
        if (sum[i] < target) continue;
        // find new closest
        if (closest == -1)
            if (sum[i] >= target) closest = 0;
        while (closest <= i && sum[i] - sum[closest] + arr[closest] >= target){
            closest++;
        }
        closest--;

        if (sum[i] - sum[closest] + arr[closest] == target) {
            for (int j = 0; j < i - closest + 1; j++)
                cout << arr[closest + j] << " " ;
            return;
        }
    }
    cout << "No solution !" << endl;
}

- Cuong Nguyen November 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void findSegment(int *arr, int n, int target){
    // closest is the closest position on the left such that sum from closest to current position
    // is greater or equal target
    int closest = -1; //doesn't exist initially
    int* sum = new int[n];
    int* res = NULL;
    for (int i = 0; i < n; i++){
        //sum[i]: sum of the first i+1 elements
        if (i == 0) sum[i] = arr[i]; else sum[i] = sum[i-1] + arr[i];
        if (sum[i] < target) continue;
        // find new closest
        if (closest == -1)
            if (sum[i] >= target) closest = 0;
        while (closest <= i && sum[i] - sum[closest] + arr[closest] >= target){
            closest++;
        }
        closest--;

        if (sum[i] - sum[closest] + arr[closest] == target) {
            for (int j = 0; j < i - closest + 1; j++)
                cout << arr[closest + j] << " " ;
            return;
        }
    }
    cout << "No solution !" << endl;
}

- vucuong020195 November 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Swift solution:

func sumConsecutiveNumbers(numberArray: [Int], target: Int) -> Bool {
    if numberArray.count == 0 {
        return false
    }
    
    var start = 0
    var end = 0
    var sum = 0
    
    while end < numberArray.count {
        if sum > target {
            sum -= numberArray[start++]
        }
        else {
            sum += numberArray[end++]
        }
        if sum == target {
            return true
        }
    }
    
    return false
}

- Steve November 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

groovy

static boolean existConsecutiveElementsAddUpToTarget(List<Integer> integers, int target) {
        int i = 0
        while (i < integers.size() - 1) {
            int first = integers.get(i)
            int second = integers.get(i+1)
            if (first != 0 && second != 0 && first + second == target) {
                println "true {${[first, second]}}"
                return true
            }
            i++
        }
        println "false"
        return false
    }

- simona.valenti.0 December 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>

bool subArray(int A[], int sumValue, int n, int * sI, int *eI)
{
  int i=0;
  *sI=0;
  int sum= A[0];
  while (i< n)
  {
    if (sum == sumValue)
    {
      *eI= i;
      return true;
    }
    else if (sum > sumValue)
    {
      sum= sum - A[*sI];
      (*sI)++;
    }
    else
    {
      i++;
      sum= sum +  A[i];
    }     
  }
  return false;
}

int main()
{
   int A[]= {2, 3, 1, 5, 4, 6, 7};
   int len= sizeof(A)/sizeof(int);
  int sI, eI;
   if (subArray(A, 28, len, &sI, &eI))
   {
     for(int i=sI; i<=eI; i++)
       printf("%d value\n", A[i]);
   }
   else
     printf("Not fund such subArray\n");  
}

- venkatesh.duggirala December 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C#

static bool IsThereConsecutiveNumbers(int []a, int index, int m)
        {
           
            if (m == 0) { return true; }
            if (index == a.Length) { return false; }

            return IsThereConsecutiveNumbers(a, index + 1, m - a[index]) || IsThereConsecutiveNumbers(a, index + 1, m);                

        }

- Daniel December 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static bool IsThereConsecutiveNumbers(int []a, int index, int m)
        {
           
            if (m == 0) { return true; }
            if (index == a.Length) { return false; }

            return IsThereConsecutiveNumbers(a, index + 1, m - a[index]) || IsThereConsecutiveNumbers(a, index + 1, m);

}

- Daniel December 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean solution(int[] nums, int target) {
if (nums.length == 0) {
System.out.println("false");
return false;
}
int start = 0;
int sum = 0;
int end = 0;
for (; end < nums.length; end += 1) {
sum += nums[end];
while (sum > target) {
sum -= nums[start];
start += 1;
}
if (sum == target) {
System.out.println("true");
return true;
}
}

System.out.println("false");
return false;
}

- Anonymous December 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean solution(int[] nums, int target) {
if (nums.length == 0) {
System.out.println("false");
return false;
}
int start = 0;
int sum = 0;
int end = 0;
for (; end < nums.length; end += 1) {
sum += nums[end];
while (sum > target) {
sum -= nums[start];
start += 1;
}
if (sum == target) {
System.out.println("true");
return true;
}
}

System.out.println("false");
return false;
}

- kchen December 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean solution(int[] nums, int target) {
if (nums.length == 0) {
System.out.println("false");
return false;
}
int start = 0;
int sum = 0;
int end = 0;
for (; end < nums.length; end += 1) {
sum += nums[end];
while (sum > target) {
sum -= nums[start];
start += 1;
}
if (sum == target) {
System.out.println("true");
return true;
}
}

System.out.println("false");
return false;
}

- kchen December 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public bool FindConsequitve(int[] values, int target)
        {
            int sum = values[0];
            int begin = 0;
            int end = 0;
            
            while (end < values.Length)
            {
                if (sum == target)
                    return true;

                if (begin == end && values[begin] > target)
                {
                    begin++;
                    end++;
                    sum = values[begin];
                }
                else if (sum < target)
                {
                    end++;
                    if (end < values.Length)
                        sum += values[end];
                }
                else
                {
                    sum -= values[begin];
                    begin++;
                }
            }

            return false;
        }

- hnatsu December 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean existSum(int [] arr, int target)
	{
		int sum = 0;
		int count = -1;
		for(int i = 0 ; i< arr.length; i++)
		{
			sum = sum + arr[i];
			count++;
			
			if(sum > target)
			{
				sum = 0;
				i = i -count;
				count = -1;
			}
			else if (sum == target)
				return true;
		}
		return false;
	}

- Dana K. January 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Linear Solution : Time Complexity o(n); No Additional Space required.

public static int[] getTargetArray(int[] input, int target) {
		int startPos = 0;
		int endPos = 0;
		int length = input.length;
		int sum = 0;
		boolean subArrayFound = false;
		for (int i = 0; i < length; i++) {
			sum += input[i]; // 9
			if (sum > target) {
				while(sum > target) {
					sum -= input[startPos++];
					if (sum < 0)
						sum = 0;
				}
			}
			if (sum == target) {
				endPos = i;
				subArrayFound = true;
				break;
			}
		}
		if (!subArrayFound)
			return null;
		int[] subArray = new int[endPos - startPos + 1];
		for (int k = 0; k < subArray.length; k++) {
			subArray[k] = input[k+startPos];
		}
		return subArray;
	}

- coder145 January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool check_consequtive_sum(int a[], int target, int len)
{
	int sum = target;
	int pos, start;
	pos=start = 0;
	
	while (start<len)
	{
		
		if (sum==0)
		{
			return true;
		}
		else if(sum>0)
		{
			sum-=a[start++];
		} 
		else if (sum<0)
		{
			sum = target;
			pos++;
			start = pos;
		}
	}
	return false;
}
int main()
{
	int a[] = {1,3,5,7,9};
	int target[] = {8,15,6};
	
	int len1 = sizeof(a)/sizeof(*a);
	
	

	 
	int len = sizeof(target)/sizeof(*target)-1;
	while(len>=0){
		
		if (check_consequtive_sum(a,target[len--],len1)){
		cout<<"true"<<"\n";
		} else {
		cout<<"false"<<"\n";	
		}
		
		
		
	}

	return 0;
}

- Anonymous January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool check_consequtive_sum(int a[], int target, int len)
{
	int sum = target;
	int pos, start;
	pos=start = 0;
	
	while (start<len)
	{
		if (sum==0)
		{
			return true;
		}
		else if(sum>0)
		{
			sum-=a[start++];
		} 
		else if (sum<0)
		{
			sum = target;
			pos++;
			start = pos;
		}
	}
	return false;
}
int main()
{
	int a[] = {1,3,5,1,7,9};
	int target[] = {8,15,6};
	
	int len1 = sizeof(a)/sizeof(*a);
	int len = sizeof(target)/sizeof(*target)-1;
	while(len>=0){
		
		if (check_consequtive_sum(a,target[len--],len1)){
		cout<<"true"<<"\n";
		} else {
		cout<<"false"<<"\n";	
		}
		
		
		
	}

	return 0;
}

- Khan January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool check_consequtive_sum(int a[], int target, int len)
{
	int sum = target;
	int pos, start;
	pos=start = 0;
	
	while (start<len)
	{
		if (sum==0)
		{
			return true;
		}
		else if(sum>0)
		{
			sum-=a[start++];
		} 
		else if (sum<0)
		{
			sum = target;
			pos++;
			start = pos;
		}
	}
	return false;
}
int main()
{
	int a[] = {1,3,5,1,7,9};
	int target[] = {8,15,6};
	
	int len1 = sizeof(a)/sizeof(*a);
	int len = sizeof(target)/sizeof(*target)-1;
	while(len>=0){
		
		if (check_consequtive_sum(a,target[len--],len1)){
		cout<<"true"<<"\n";
		} else {
		cout<<"false"<<"\n";	
		}
		
		
		
	}

	return 0;
}

- Khan January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class example {



public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]={1,2,3,4,5};
int target = 5;
boolean c = findTarget(a, target);
System.out.println(c);


}

private static boolean findTarget(int[] b, int target) {
// TODO Auto-generated method stub
for(int i=0;i<b.length-1;i++)
{
if(b[i]+b[i+1] == target)
return true;
}
return false;
}

}

- Testee February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class example {
	
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]={1,2,3,4,5};
		int target = 5;
		boolean c = findTarget(a, target);
		System.out.println(c);
		

	}

	private static boolean findTarget(int[] b, int target) {
		// TODO Auto-generated method stub
		for(int i=0;i<b.length-1;i++)
		{
			if(b[i]+b[i+1] == target)
				return true;
		}
		return false;
	}

}

- Anonymous February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

/* Given positive int array, determine whether there is a set of consecutive ints that add up to target */


public class ConsecutiveSum {

	public static int[] arr = {1,3,5,7,9};
	public static int target = 6;

	public static Vector<Integer> findSet(int[] arr, int target){
		int i, j, sum = 0;
		int length = arr.length;

		Vector<Integer> ret = new Vector <Integer>(1);

		for(i = 0; i < length; i++){
			sum += arr[i];
			for (j = i + 1; j < length; j++){
				if(sum + arr[j] == target){
					//found
					if(ret.indexOf(arr[i]) < 0){
						ret.add(arr[i]);
					}
					ret.add(arr[j]);
					return ret;


					
				} else if(sum + arr[j] < target){
					sum += arr[j];
					if(ret.indexOf(arr[i]) < 0){
						ret.add(arr[i]);
					}
					ret.add(arr[j]);
				} else break;
			}
			sum = 0;
			ret.removeAllElements();
			ret.setSize(1);
		}

		return ret;
	}
	public static void main (String[] args){

		Vector<Integer> result = new Vector<Integer>();

		result = findSet(arr, target);
		if(result.size() < 2){
			System.out.println("False");
		} else{
			System.out.println("True");
			for(int i = 1; i < result.size(); i++){
				System.out.print(result.get(i) + " ");
			}
			System.out.println("\n");
		}



	}	
}

- Anonymous February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My Javascript solution:

function getConsecutivesThatSum(numbers, target) {
var i;
var j;
var sum;

for (i = 0; i < numbers.length; i++) {
sum = numbers[i];

for (j = i+1; j < numbers.length; j++) {
sum += numbers[j];
if (sum > target) {
break;
} else if (sum < target) {
continue;
} else {
return { success: true, result: numbers.slice(i, j + 1)};
}
}
}
return { success: false };
}

getConsecutivesThatSum([1,3,5,7,9], 8);

// { success: true, result: [3,5] }

getConsecutivesThatSum([1,2,3,4,5], 7);

// { success: true, result: [3,4]}

getConsecutivesThatSum([1,3,5,7,9], 15);

// { success: true, result: [3,5,7]}

getConsecutivesThatSum([1,3,5,7,9], 6);

// { success: false}

getConsecutivesThatSum([6], 6);

// { success: false}

- nabilgod January 14, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* 
	dynamic programming approach. Creates a O(n^2) space to store partial 
	sums which are useful in printing the path.
	for an input {1,5,3,7,9}, sum is a sparse matrix when fully populated:
       
       1
       6    5
       9    8    3
      16   15   10    7
      25   24   19   16    9
    
    Since the getSum() is called only when either decrementing i or j, and uses
    a memoized sum matrix, the complexity of algorithm is O(n + n) = O(n)
    */
    static void sumTarget(int[] array, int target){
	    int length = array.length;
	    int[][] sum = new int[length][length];
	    
	    for(int i = 0 ; i < length; i++){
	        sum[i][i] = array[i];
	    }
	    
	    boolean found = false;
	    int i = length-1;
	    int j = length-1;
	    int value = 0;
	    
	    while(true){
	        value = getSum(array, sum, i, j);
	        if(target == value){
	            found = true;
	            break;
	        }
	        if(i-1 < 0 || j-1 < 0){
	            found = false;
	            break;
	        }
	        if(target < value){
	            // can't go straight up the array, so go diagonally up
	            if (i == j)
	                j--;
	            i--;
	        }else{
	            // go left
	            j--;
	        }
	    }
	    
	    if (!found) {
	        System.out.println(target + "= false");
	    } else {
	        System.out.print(target + "= true: {");
	        
	        for (; j < i; j++)
	            System.out.print(array[j] + ",");
	            
	        System.out.println(array[j] + "}");
	    }
	}
	
	static int getSum(int[] array, int[][] sum, int i, int j){
	    if(i < 0 || j < 0){
	        return 0;
	    }
	    if(sum[i][j] == 0){
	        sum[i][j] = getSum(array, sum,i-1,j) + array[i];
	    }
	    return sum[i][j];
	    
	}

- Dhara Padia February 07, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sum = 0
res_array=list()
def findsum(item, arr):
i=0
for i in range(len(arr) - 1):
sum = arr[i]

for j in range(1,len(arr)- i):
sum = sum + arr[i+j]

if sum == item:
for x in range(i,i+j+1):
res_array.append(arr[x])


return res_array


if __name__=="__main__":
arr = [1,3,3,1,9,3,5]
item = 8
res_array=findsum(item,arr)
print res_array

- Deep March 07, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming we need to consider atleast 2 elements to compute the sum,

def findsum(self,num,target):
  d={}
  d[0]=-1
  sum=0
  for i in xrange(len(num)):
     sum+=num[i]
     if d and abs(target-sum) in d and d[abs(target-sum)] !=i:
        return bool(1)
     if sum not in d:
        d[sum]=i

  return bool(0)

- deepjoarder July 21, 2017 | Flag Reply


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