CODING CHALLENGE · N°01

Two Sum

Easy ArraysHash Map

The classic warm-up: find the two numbers that add up to a target. Brute force is O(n²) — a hash map gets you to one pass, O(n). Solve it in Python or TypeScript, in your browser.

The problem

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and you may not use the same element twice. Return the indices in increasing order.

EXAMPLE 1
Input nums = [2, 7, 11, 15], target = 9
Output [0, 1]
nums[0] + nums[1] = 2 + 7 = 9
EXAMPLE 2
Input nums = [3, 2, 4], target = 6
Output [1, 2]
2 + 4 = 6
EXAMPLE 3
Input nums = [3, 3], target = 6
Output [0, 1]
CONSTRAINTS
  • 2 ≤ nums.length ≤ 10⁴
  • Exactly one valid answer exists.
  • Aim for O(n) time — one pass with a hash map beats the O(n²) double loop.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement two_sum(nums, target): return the two indices (increasing order) whose values sum to target. One pass with a hash map of value → index gets you O(n).

HINTS — 4 IDEAS
  1. Brute force checks every pair — O(n²). The trick is to remember what you have already seen.
  2. Walk the array once, keeping a map of value → index.
  3. At each number x, the partner you need is target - x. If it is already in the map, you are done.
  4. Store x → its index only after checking, so you never pair an element with itself.
CPython · WebAssembly