Two Sum

easy Coding Interview Patterns 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement Two Sum with a single-pass hash map -- O(n) instead of the O(n^2) brute-force nested loop, and the canonical first problem that teaches "trade memory for time" via hashing.

Related Skills

Task

Implement two_sum(nums, target): for each number, check whether its complement (target - number) has already been seen; if so, return the pair of indices. Otherwise record the current number and its index and keep scanning.

Function Signature

two_sum(nums: list[int], target: int) -> list[int]

Examples

Example 1: Basic Pair
Input: nums = [2, 7, 11, 15] target = 9
Output: [0, 1]
Example 2: Answer Not at the Start
Input: nums = [3, 2, 4] target = 6
Output: [1, 2]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Exactly one valid pair exists per input, and the same element may not be used twice.
  • Return indices as [i, j] with i < j.
  • Raise ValueError if no valid pair exists (defensive -- the stated inputs always have one).
Python3Saved ✓
def two_sum(nums: list[int], target: int) -> list[int]:
"""Return the indices [i, j] (i < j) of the two numbers in nums that
add up to target. Assume exactly one valid pair exists and you may
not use the same element twice. Raise ValueError if no pair sums to
target."""
# Your implementation here
pass

Case 1: Basic Pair
Input: nums = [2, 7, 11, 15] target = 9
Expected: [0, 1]
Case 2: Answer Not at the Start
Input: nums = [3, 2, 4] target = 6
Expected: [1, 2]