Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire 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 atCitadelTwo Sigma

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.

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.