Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Pair with a given sum in an unsorted array

Easy · Target 10 minutes · Arrays and hashing· Type asked at

Given an array nums in no particular order and an integer target, return the indices of the two numbers that add up to target, smaller index first. Exactly one such pair exists, and you may not use the same element twice.

Examples

InputOutputWhy
nums = [11, 2, 15, 7], target = 9[1, 3]2 + 7 = 9.
nums = [3, 2, 4], target = 6[1, 2]2 + 4. Not [0, 0] — the 3 cannot be used twice.
nums = [3, 3], target = 6[0, 1]Two different elements that happen to be equal are fine.

Constraints

  • 2 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • Exactly one valid pair exists

Hints

Hint 1

Checking every pair works and is O(n²). Before optimising, say out loud what each inner loop is actually looking for.

Hint 2

For a value x, the inner loop is searching for one specific number: target − x. That is a lookup, and lookups are what hash maps are for.

Hint 3

Walk the array once. For each element, ask the map whether its partner has already gone past; only then add the element itself.

Where people lose marks

  • Inserting before looking up, which lets an element pair with itself.
  • Storing only the first index of each value and then being surprised by [3, 3]. Looking up before inserting makes this a non-issue.
  • Sorting to use two pointers and then returning indices into the sorted copy. The question asks for positions in the original array.
  • In C++ and Java, target − x near the integer limits overflows. Use a 64-bit type for the complement.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.