Algorithms

Two Sum

easyalgorithmsarrayhash-map
0:00

Problem

Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume exactly one solution exists, and you may not use the same element twice.

Your solution
Test results
Click Run tests to check your solution against the test cases.

About this challenge

Two Sum is a easy algorithms coding challenge. It tests algorithmic thinking and complexity analysis — the kind of problem-solving that shows up constantly in technical interviews. Write your solution in the editor above, run it against the test cases, and get instant feedback — free, in your browser, no sign-up.

Show a hint & approach (spoiler)

Hint: Use a hash map to store numbers you have seen along with their indices. For each number, check if target - num exists in the map.

Approach: A hash map gives O(1) lookup. Walk the array once; for each num, check whether target − num was seen before. Overall O(n) time, O(n) space.

Keep practicing

Browse all coding challenges, or build intuition for the underlying concepts with the algorithm visualizers and the developer cheatsheets.