Indices of a Pair That Sums to Target (Set 14)

Easy

Given an array of integers nums and a target, return the indices of one pair whose values add up to target. Return the two indices as [i, j] — the order does not matter.

Every input has exactly one valid pair.

Indices of a Pair That Sums to Target (Set 14) — the data. This set runs 4 cases: nums holds arrays of 48–48 items, with values from 1 to 40; target ranges over 20–50. The hidden cases are the largest of the set.

Example 1

pairWithTargetSum()
Input
nums = [16, 12, 9, 6, 28, 14, 30, 33, 40, 31, 21, 11, 13, 26, 5, 19, 20, 35, 18, 37, 34, 23, 39, 8, 25, 32, 36, 27, 24, 17, 15, 10, 38, 3, 7, 29, 4, 1, 22, 2, 1, 1, 1, 1, 1, 1, 1, 1], target = 23
Output
[2, 5]

Why

`pairWithTargetSum` returns `[2, 5]` for this input.

Example 2

pairWithTargetSum()
Input
nums = [34, 21, 26, 3, 33, 37, 30, 7, 15, 38, 2, 40, 4, 39, 20, 5, 17, 6, 27, 29, 31, 16, 28, 23, 1, 35, 12, 32, 36, 22, 19, 10, 18, 11, 9, 8, 14, 13, 24, 25, 1, 1, 1, 1, 1, 1, 1, 1], target = 50
Output
[6, 14]

Why

`pairWithTargetSum` returns `[6, 14]` for this input.
Constraints
2 <= nums.length <= 10^4
-10^4 <= nums[i], target <= 10^4
Exactly one valid pair exists.
Every case in this set must pass: the first two are visible on Run, the last two unlock on Submit.

Topics

ArraysHash Table

Implement pairWithTargetSum in the editor and return the answer — printing it is never graded.