Problem · Array
Find Two-Sum or Three-Sum Index Combinations
Learn this problemProblem 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]withi < jandnums[i] + nums[j] = target. - For
tupleSize = 3, return every[i, j, k]withi < j < kandnums[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 <= 1000000tupleSizeis 2 or 3 and does not exceednums.length.- The number of returned combinations is at most 200000.