Problem · Array
All Pairs with Target Sum
Learn this problemProblem statement
You are given an integer array numbers and an integer target. Return one pair for every index pair (i, j) with i < j and numbers[i] + numbers[j] = target.
Represent each pair as [smallerValue, largerValue]. Different index pairs remain different results, so duplicate values may create repeated rows. Sort all returned rows lexicographically by their first value and then their second value.
Function
allPairsWithTargetSum(numbers: int[], target: int) → int[][]Examples
Example 1
numbers = [1,2,3,2,4]target = 4return = [[1,3],[2,2]]The valid index pairs contribute value pairs [1,3] and [2,2].
Example 2
numbers = [1,1,1,2,2]target = 3return = [[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]]Each of the three positions containing 1 can pair with either of the two positions containing 2, producing six distinct index pairs.
Example 3
numbers = [-2,0,2,4]target = 2return = [[-2,4],[0,2]]Both -2 + 4 and 0 + 2 equal the target. The rows are already in lexicographic order.
Constraints
1 <= numbers.length <= 2000-10^9 <= numbers[i], target <= 10^9- The number of returned rows fits in memory.