Problem · Array

Find Two-Sum or Three-Sum Index Combinations

Learn this problem
MediumGoogle logoGoogleFULLTIMEONSITE INTERVIEW
See Google hiring insights

Problem statement

Given an integer array nums, an integer target, and tupleSize equal to 2 or 3, return every index combination whose values sum to target.

  • For tupleSize = 2, return every [i, j] with i < j and nums[i] + nums[j] = target.
  • For tupleSize = 3, return every [i, j, k] with i < j < k and nums[i] + nums[j] + nums[k] = target.

Each distinct index combination appears once, even when values repeat. Return combinations in lexicographic index order.

Function

findTargetIndexCombinations(nums: int[], target: int, tupleSize: int) → int[][]

Examples

Example 1

nums = [2,7,11,15]target = 9tupleSize = 2return = [[0,1]]

Indices 0 and 1 contain 2 and 7, which sum to 9.

Example 2

nums = [-1,0,1,2,-1,-4]target = 0tupleSize = 3return = [[0,1,2],[0,3,4],[1,2,4]]

The repeated value -1 occurs at different indices, so all three distinct index triples are retained.

Example 3

nums = [0,0,0,0]target = 0tupleSize = 2return = [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]]

All six pairs of different indices are valid and appear in lexicographic order.

Constraints

  • 2 <= nums.length <= 200
  • -1000000 <= nums[i], target <= 1000000
  • tupleSize is 2 or 3 and does not exceed nums.length.
  • The number of returned combinations is at most 200000.

More Google problems

drafts saved locally
public int[][] findTargetIndexCombinations(int[] nums, int target, int tupleSize) {
    // Write your code here.
}
nums[2,7,11,15]
target9
tupleSize2
expected[[0,1]]
checking account