CodeMentor.
Ask AIProblemsLearnC++TCSCore CSHRProgress
0Lv 1
ProblemsArrays

Two Sum

Easy
LeetCode
1/14
EasyArraysLeetCode #1

Two Sum — think like a teacher, not a memorizer

You get an array of integers and a target. Return indices of two numbers that add to target.

Wrong first instinct

Brute force: try every pair. Works, but O(n²). Interviews want the O(n) story.

The move

As you scan left→right, ask: "Have I already seen target - nums[i]?"

Keep a hash map: value → index.

Dry run

nums = [2,7,11,15], target = 9

  • i=0, need 7, map empty → store 2→0
  • i=1, need 2, map has 2 at 0 → return [0,1]

You already solved this on LeetCode. Rewrite it cleanly here without peeking.

Tip: Open the Animated Classroom for Two Sum — watch the map fill before you code.

Examples

Example 1

Input

4 9
2 7 11 15

Output

0 1
Example 2

Input

3 6
3 2 4

Output

1 2

Stuck? Take a nudge

C++17Autosaves