Pair and Sum of Pair in Large Sorted Array
Anonymous User
778

Given a very large array of integers (sorted, no duplicates), ouput all the possible combinations (a, b, c) such that a + b = c. No other data storage should be used.

Example:
[1, 2, 3, 4, 5, 7, 8, 9, 11, ....]
Output: [[1, 2, 3], [1, 3, 4], [1, 7, 8], [1, 8, 9], [2, 3, 5],...]

My solution:

public List<List<Integer>> solution(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < nums.length - 2; i++) {
            int j = i + 1;
            int k = j + 1;
            while (j < k) {
                int target = nums[i] + nums[j];
                while (k < nums.length && nums[k] <= target) {
                    if (nums[k] == target) {
                        result.add(Arrays.asList(new Integer[]{nums[i], nums[j], nums[k]}));
                        break;
                    }
                    k++;
                }
                j++;
            }
        }

        return result;
    }

I was thinking of the best solution I could find for 3Sum which is O(n^2) (CMIIW) but interviewer wants better solution.

How to make this more efficient?

[EDIT] My solution is O(n^3) which I mistakenly thought was O(n^2)

Comments (3)