A-003● Day 032026.05.07easyleetcode #1neetcode150
Two Sum
#array#hash-table
01
Problem
· problemFind 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
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 complement│ nested
○
diff = target - n
○
diff = n - target
○
diff = target + n
○
diff = target // n
step 4· Check if complement exists│ nested
○
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 element│ nested
○
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
· solvemental 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.