Problem · Array

All Index Pairs Sum to K

Learn this problem
MediumJCJPMorgan ChaseFULLTIMEPHONE SCREEN

Problem statement

Given an unsorted integer array nums and an integer target, return every pair of indices [i, j] such that:

  • 0 <= i < j < nums.length, and
  • nums[i] + nums[j] == target.

Repeated values and repeated occurrences are retained: distinct index pairs must all appear even when their values are equal.

Return the pairs in lexicographic order, comparing i first and j second. Return an empty matrix when no pair qualifies.

Function

allIndexPairsSumK(nums: int[], target: int) → int[][]

Examples

Example 1

nums = [1,5,7,-1,5]target = 6return = [[0,1],[0,4],[2,3]]

Indices 0 and 1, indices 0 and 4, and indices 2 and 3 each select values summing to 6. Both occurrences of value 5 are retained.

Example 2

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

Every choice of two different indices sums to 6. The pairs are ordered by their first index and then their second index.

Example 3

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

No two values sum to 3, so the returned matrix is empty.

Constraints

  • 0 <= nums.length <= 1000.
  • -10^9 <= nums[i] <= 10^9.
  • -10^9 <= target <= 10^9.
  • The result may contain up to nums.length * (nums.length - 1) / 2 pairs.

More JPMorgan Chase problems

drafts saved locally
public int[][] allIndexPairsSumK(int[] nums, int target) {
    // write your code here
}
nums[1,5,7,-1,5]
target6
expected[[0,1],[0,4],[2,3]]
checking account