I received this question in an interview and was not sure how to answer. This is a regular 3SUM problem, and we all know the answer is O (n ^ 2). The question goes like this: you have 3 unsorted arrays a, b, c. Find three elements such that a [i] + b [j] + c [k] = 0. You are not allowed to use hashing in this scenario, and the solution should be <= O (n ^ 2)
Here is my answer and yes, it's still O (n ^ 3), unfortunately
public static void get3Sum(int[] a, int[] b, int[] c) { int i = 0, j = 0, k = 0, lengthOfArrayA = a.length, lengthOfArrayB = b.length, lengthOfArrayC = c.length; for (i = 0; i < lengthOfArrayA; i++) { j = k = 0; while (j < lengthOfArrayB) { if (k >= lengthOfArrayC) { j++; continue; } else if (a[i] + b[j] + c[k] == 0) {
Does anyone have any brilliant ideas to solve this less than or equal to O (N ^ 2)?
Thanks!
masti
source share