all entries
A-001Day 012026.05.05easyleetcode #1neetcode150

Two Sum

#array#hash
leetcode #1 · two-sum
01

Problem

· problem
P.001

Two Sum

leetcode #1

Given an unsorted int array nums and target, return indices [i, j] such that nums[i] + nums[j] == target. Exactly one solution exists. Cannot use the same element twice.

constraints
  • · 2 ≤ nums.length ≤ 1e4
  • · −1e9 ≤ nums[i], target ≤ 1e9
  • · 정답이 정확히 1쌍 존재
// paraphrased summary — see source for full text
examples
example 1input → output
nums = [2, 7, 11, 15]
target = 9
[0, 1]
example 2input → output
nums = [3, 2, 4]
target = 6
[1, 2]
example 3input → output
nums = [3, 3]
target = 6
[0, 1]
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Can values be negative?
  • Can we reuse the same element?
  • What if multiple answers exist?
  • Need overflow handling?
  • Is the input sorted?
  • Array size limit?
  • Will strings come as input?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize
seen = {}
result = []
a = sorted(nums)
step 2· Loop
for num in nums:
for i, num in enumerate(nums):
for i in range(len(nums)):
step 3· In loop — helpernested
complement = target - num
pair_sum = nums[i] + num
mid = (i + len(nums)) // 2
step 4· Branch conditionnested
if complement in seen:
if num == target / 2:
if i + 1 < len(nums):
step 5· On true — return│ │ nested
return [seen[complement], i]
return (complement, num)
result.append([seen[complement], i])
step 6· Loop tail — updatenested
seen[num] = i
seen[i] = num
continue
step 7· After loop — fallback
return []
pass
raise ValueError("no pair")
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
def two_sum(nums, target):
2
    seen = {}
3
    for i, num in enumerate(nums):
4
        complement = target - num
5
        if complement in seen:
6
            return [seen[complement], i]
7
        seen[num] = i
8
    return []
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
nums=[2,7,11,15], target=9
[0, 1]
case 2
nums=[3,2,4], target=6
[1, 2]
case 3
nums=[3,3], target=6
[0, 1]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.