Amazon Interview Question

Give a similar one here: Find 4 numbers in an integer array and they sum zero

Interview Answers

Anonymous

Jun 20, 2015

Why not just find all the combinations of 4 elements in the array and print out the one whose sum is equal to the required number: void get_sum(vector&vec, int n, int indx,int sum) { static vector res; if (n == 0) { int temp = 0; for (auto &a : res)temp += a; if (temp == sum) { for (auto &a : res) cout vec = { 1, 2, 3, 4, 5, 6, 7, 8 }; get_sum(vec, 4, 0, 11); }

Anonymous

Jul 21, 2015

Use four nested loops over the same array. In the most inner loop, sum up the four values, if you get a zero then use the four values as a candidate

Anonymous

Mar 5, 2015

I think the answer should be enumerating on the first two integer and find the other two using O(n). So the total should be O(n^3) I'm too nervous then to come up with this idea :(