InferenceAI

Enter at least two characters to search.

Start free

Pair With Target Sum

easyArrays & Hashing15 min10 XP

Given a list of integers nums and an integer target, return the indices [i, j] with i<ji < j such that nums[i] + nums[j] == target.

If several pairs work, return the one with the smallest j, and among those the smallest i. Return [] if no pair exists.

Requirements

  • Run in O(n)O(n) time using a hash map.
  • Do not use the same element twice.

Constraints

  • 0≤n≤1050 \le n \le 10^5
  • −109≤-10^9 \le nums[i], target ≤109\le 10^9

Examples

EXAMPLE WALKTHROUGHvalues 2 and 7

A guided view of the published example, not a trace of your code.

INPUT[[2,7,11,15],9]
TASKpair_with_target_sum()
EXPECTED OUTPUT[0,1]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Explanation: values 2 and 7

Input: nums = [3,2,4], target = 6

Output: [1,2]

Explanation: pair is not at the start

Input: nums = [1,2], target = 7

Output: []

Explanation: no valid pair

Hint 1

As you scan left to right, what value would complete a pair with the current number?

Hint 2

Store each value's first index in a dictionary before moving on.

Topics

DSAArrays & HashingPython