InterviewPrepKit

Home / Coding / Arrays & Hashing

Two Sum

easy Original β†—
Solving tips
  • At index i you know the exact value needed: complement = target - nums[i]; the slow part is searching for it, which a hash map makes O(1).
  • One pass: for each element check if its complement is already in a value->index dict, else insert the current element; O(n) time, O(n) space.
  • Check for the complement BEFORE inserting the current element β€” this guarantees distinct indices and handles duplicates like [3,3].
  • Pitfall: the array is unsorted and values can be negative, so a sort+two-pointer approach must carry original indices and there are no sign-based shortcuts.

Problem

You are given an array of integers nums and an integer target. Find the two different positions in the array whose values add up exactly to target, and return those two indices (in any order).

You may assume every input has exactly one valid answer, and you cannot use the element at the same index twice (though two equal values at different indices are fine).

Examples

  • nums = [2, 7, 11, 15], target = 9 β†’ [0, 1] β€” because 2 + 7 = 9.
  • nums = [3, 2, 4], target = 6 β†’ [1, 2] β€” 2 + 4 = 6; note you may not use index 0 twice even though 3 + 3 = 6.
  • nums = [3, 3], target = 6 β†’ [0, 1] β€” equal values at two different indices are allowed.

Constraints

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

The array is not sorted, and with up to 10^4 elements a quadratic scan is already ~10^8 pair checks β€” the intended solution is linear.

Think about it first

Hint 1 Standing at index `i`, you already know exactly which value would complete the pair. What is it?
Hint 2 The slow part of the naive solution is *searching* for that complementary value. What data structure answers "have I seen value v, and where?" in O(1)?
Hint 3 Walk the array once, keeping a dict from value β†’ index of the elements you've already passed. At each element, look up `target - nums[i]` in the dict *before* inserting the current element β€” that also prevents matching an element with itself.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.