## Interview Question

Site Reliability Engineer Interview

-New York, NY

# Find all pairs of 3 in an array that add to n.

6

Wrote code.

Anonymous on

0

This is what I came up with, probably not the smartest way : #!/usr/bin/env python def sum_to_n(numbers, n): """ Pick the first two numbers in the list first, then add the third one. Return if the sum is equal to n. Then remove the first two, since you are done with them. Do the same thing as long as you have at least 3 elements in the list """ numbers = numbers.split(",") output = [] first = int(numbers) second = int(numbers) while len(numbers) > 2: for item in numbers[2:]: if first + second + int(item) == n: output.append((first, second, item)) numbers.pop(0) numbers.pop(1) first = int(numbers) second = int(numbers) return output numbers = raw_input("Enter a comma separated list of integers:") n = raw_input("Enter an integer:") print sum_to_n(numbers, int(n))

Anonymous on

0

public static void printPairSums(int[] array, int sum) { Arrays.sort(array); // 2 pointeurs int first = 0; int last = array.length - 1; while (first < last) { int s = array[first] + array[last]; if (s == sum) { System.out.println("( "+array[first] + " ," + array[last]+ " )"); ++first; --last; } else { if (s < sum) ++first; else --last; } } } //Exemple public static void main(String[] args) { // TODO Auto-generated method stub int[] myIntArray = new int[]{1,2,3,-1,4,5,-2,7,1}; printPairSums (myIntArray, 3); }

Me on

1

Above solution is not correct. interviewer is asking for set of 3 integers that sum to N. I think what you calculated is a set of 2 integers that sum to N. OP has posted the problem incorrectly. It should say "Find all pairs of 3 in an array that add to n" instead of Find all pairs of 3 in an array that add to n". Pairs is for 2 values. Below code should do the work: void findsets (vector v, int sum) { sort(v.begin(), v.end()); for(int i = 0; i < v.size() -2; i++){ int rem = sum - v[i]; int left = i+1; int right = (int)v.size()-1; while(left