learn deep. ship safe.Practice testsFollow ByteMunSubscribe

easyArraysHash map

Pair with Target Sum

Given an array of numbers and a target, return the indexes of the two numbers that add up to the target. A classic warm-up that tests whether you reach for a hash map.

By Tests checked by DeepakJavaScript or Python

You are given an array of integers nums and an integer target. Exactly one pair of different positions i < j has nums[i] + nums[j] === target.

Return [i, j] with the smaller index first. You may not use the same element twice.

Examples

Example 1

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Why: 2 + 7 = 9

Example 2

Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Why: 2 + 4 = 6; index 0 can't be used twice

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i], target <= 10^9
  • Exactly one valid pair exists

Hints

Hint 1

A brute-force check of every pair works, but it's O(n²). Can you do it in one pass?

Hint 2

As you walk the array, remember each number's index in a map. For the current number, what value would complete the pair?

Solution

Show the solution (try it yourself first)

Approach: one pass with a hash map

Checking every pair works but takes O(n²) time, which is too slow for 10,000 numbers. Instead, walk the array once and keep a map from each value you've seen to its index. For each number x, the partner you need is target - x. If it's already in the map, you've found the pair; otherwise store x and move on. Checking before storing stops a number pairing with itself, and duplicates like [3, 3] still work because the first 3 is stored before the second is checked.

function pairWithTargetSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return [];
}

Complexity

Time O(n): one pass with constant-time map lookups. Space O(n) for the map. Interviewers often follow up with: what if the array is sorted? Then two pointers from both ends solve it in O(1) extra space.

Case 1Input: [2,7,11,15], 9Expected: [0,1]
Case 2Input: [3,2,4], 6Expected: [1,2]

Run checks these 2 samples. Submit checks all 7 tests, including hidden ones.

  1. Search a Sorted ArrayBinary search · Arrays
    easy
  2. Maximum Subarray SumArrays · Dynamic programming
    medium
  3. Longest Substring Without RepeatsStrings · Sliding window · Hash map
    medium
  4. Group AnagramsStrings · Hash map · Sorting
    medium