AAlgoLoopSpaced repetition for LeetCode
EASYHash Map / SetLeetCode ↗

Two Sum

The key idea

For each number, check if its complement (target - num) has been seen before; if yes, return indices. Use a hash map to store each number's index as you iterate.

Problem

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target. You may assume each input has exactly one solution, and you may not use the same element twice. Return the answer in any order.

Constraints

Examples

Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Input: nums = [3,2,4], target = 6 Output: [1,2]
Input: nums = [3,3], target = 6 Output: [0,1]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems