~/workshop
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 = 9Output
[0, 1]nums[0] + nums[1] = 2 + 7 = 9
EXAMPLE 2
Input
nums = [3, 2, 4], target = 6Output
[1, 2]2 + 4 = 6
EXAMPLE 3
Input
nums = [3, 3], target = 6Output
[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.
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
- Brute force checks every pair — O(n²). The trick is to remember what you have already seen.
- Walk the array once, keeping a map of
value → index. - At each number
x, the partner you need istarget - x. If it is already in the map, you are done. - Store
x → its indexonly after checking, so you never pair an element with itself.
1
1