Two Sum

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Two Sum

Approach

Iterate through the array, storing each number and its index in a hash map. For each element, compute the complement (target - current) and check if it exists in the map. If found, return both indices immediately.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Hash Map Lookup

Why It Works

The hash map provides O(1) lookup for complements. By building the map as we iterate, we ensure we only find pairs where the complement appears at a different index.

Updated Feb 2026