01
02
03
04
05
06
07
08
09
10
11
A
A2Z Sheet

76. Two Sum & The Exact Target Matcher

Easy
Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Medium

Two Sum & The Exact Target Matcher

EasyFunction: twoSum()
ASCI Mission Breakdown • Simple as Hell
"Find the two index positions in an array whose values add up to exactly the target value."
Real-World Metaphor:

You have a $9 gift card. On the belt are prices [2, 7, 11, 15]. At index 0 you see $2; you need $7 (9 - 2), so you scribble "Saw $2 at index 0" on your sticky note. Next you see $7 at index 1. You glance at your sticky note: "Aha! I already saw $2 at index 0!" You return [0, 1] immediately!

Interactive Visual WalkthroughHASH-MAP
Step 1 / 2
Conveyor: [2, 7, 11, 15] | Target = 9
i
2
[0]
7
[1]
11
[2]
15
[3]
Memory Notepad / State Tracker
Current:2
Needed:7
Notepad:{ 2: 0 }
Evaluating

1. Inspect Index 0 (Price = 2)

Target is 9. Partner needed = 9 - 2 = 7. Notepad is empty! Record { 2: index 0 } on notepad.

How to Think About This (Mental Model)

  1. Create an empty Hash Map (your memory notepad) to remember numbers and their indices.
  2. Loop through the array one index i at a time.
  3. For the current number, calculate needed = target - nums[i].
  4. If needed is already in your notepad, return [notepad[needed], i].
  5. Otherwise, write nums[i]: i into your notepad and continue.

### The Mission You are holding a gift voucher worth an exact target balance (e.g. **$9**). You walk along a supermarket conveyor belt where items with prices are rolling past in an array: `[2, 7, 11, 15]`. Your mission is to find the **two item positions (indices)** whose combined prices sum up to exactly your gift voucher. ### Why You Can't Just Use Two Loops Checking every pair with nested loops takes **O(N²)** time — if the conveyor belt has 100,000 items, the store closes before you finish! Instead, use a **Memory Notepad (Hash Map)**: as you inspect each item, calculate what partner price you need (`target - price`). If you've already seen that partner, you win instantly in **O(N)** time!

Examples

Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]MediumtwoSum
14px
Ln 1:Col 1
9 lines•144 chars
Spaces: 2•UTF-8
JS(Node v20.12)