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

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 8) — the data. This set runs 4 cases: nums holds arrays of 31–46 items, with values from 1 to 40; target ranges over 11–70. The hidden cases are the largest of the set.

Example 1

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

Why

`pairWithTargetSum` returns `[1, 16]` for this input.

Example 2

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

Why

`pairWithTargetSum` returns `[2, 3]` 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.