all entries
A-003Day 032026.05.07easyleetcode #1neetcode150

Two Sum

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

Problem

· problem
P.003

Two Sum

leetcode #1

Find indices of two array elements that sum to a target value

constraints
  • · 2 ≤ nums.length ≤ 10^4
  • · -10^9 ≤ nums[i] ≤ 10^9
  • · -10^9 ≤ target ≤ 10^9
  • · Exactly one valid answer exists
  • · Cannot reuse the same element twice
// paraphrased summary — see source for full text
examples
example 1input → output
[2,7,11,15]
9
[0,1]
example 2input → output
[3,2,4]
6
[1,2]
example 3input → output
[3,3]
6
[0,1]
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Can we use the same element twice?
  • Can the array contain duplicate numbers?
  • Does the order of indices in the return matter?
  • Can we assume the array is sorted?
  • Can negative numbers be included?
  • Can we modify the input array?
  • Should we return the values or the indices?
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 hash map
prevMap = {}  # val -> index
prevMap = []
prevMap = set()
prevMap = defaultdict(int)
step 2· Iterate through array
for i, n in enumerate(nums):
for i in range(len(nums)):
for n in nums:
for i, n in reversed(enumerate(nums)):
step 3· Calculate complementnested
diff = target - n
diff = n - target
diff = target + n
diff = target // n
step 4· Check if complement existsnested
if diff in prevMap:
if n in prevMap:
if i in prevMap:
if diff in nums:
step 5· Return result│ │ nested
return [prevMap[diff], i]
return [i, prevMap[diff]]
return (prevMap[diff], i)
return [prevMap[diff], n]
step 6· Store current elementnested
prevMap[n] = i
prevMap[i] = n
prevMap[n] = prevMap.get(n, 0) + 1
prevMap.add(n)
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
class Solution:
2
    def twoSum(self, nums: List[int], target: int) -> List[int]:
3
        prevMap = {}  # val -> index
4
5
        for i, n in enumerate(nums):
6
            diff = target - n
7
            if diff in prevMap:
8
                return [prevMap[diff], i]
9
            prevMap[n] = i
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[2,7,11,15]
9
[0,1]
case 2
[3,2,4]
6
[1,2]
case 3
[3,3]
6
[0,1]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.