Problem 218790 · easy · Level 02 Linear Data Structures

Two Items, One Gift Card

hash maps · lists

Checking every pair of elements costs O(n^2). A hash map lets you ask "have I already seen the number I need?" in O(1), so a single pass is enough.

You hold a gift card worth exactly target and a price list nums (a refund shows up as a negative price). Exactly one pair of different items on the list together costs the card's whole value. Return the positions of those two items in the list, as a list of two integers in either order. Each item is there only once: if one price is half the card's value, you cannot buy that item twice to make up the total.

Examples

Input:  nums = [8, 14, 5, 21], target = 19
Output: [1, 2]
Explanation: nums[1] + nums[2] == 19
Input:  nums = [5, 4, 6], target = 10
Output: [1, 2]
Explanation: [0, 0] is not allowed: it buys the same item twice.

Constraints

  • 2 <= len(nums) <= 10**4
  • -10**9 <= nums[i], target <= 10**9

Goals

  • Use a dictionary to remember values you have already seen along with their positions
  • Rephrase 'find a pair' as 'for each element, look up its partner'
Starting Python…