Skip to solution
easyDSA

How do you solve the Two Sum problem efficiently?

46 views
01

Understand the problem

Explain Two Sum.

arrayshashing
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Use a hash map: for each number, check if target - num is already in the map; if so return the indices, else store num → index. This is O(n) time, beating the O(n²) brute-force double loop.

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

One-pass hash map
Run Playground
def two_sum(nums, target):
    seen = {}                       # value -> index
    for i, num in enumerate(nums):
        if target - num in seen:
            return [seen[target - num], i]
        seen[num] = i
    return []


# --- demo ---
print(two_sum([2, 7, 11, 15], 9))   # [0, 1]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 27 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.

Back to track