InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Two Sum

easy Original ↗ 00:00

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 At index `i`, exactly one value completes 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 at which index?" 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug