Target-Sum Index Pair
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement two_sum(nums: List[int], target: int) -> List[int], which receives an unsorted list of integers nums and a desired integer sum target.
Locate two different 0-based positions i and j (i != j) in nums such that nums[i] + nums[j] == target, and return [i, j].
Your implementation should satisfy these rules:
- No self-pairing: You may never reuse the same array position twice, even when
2 * nums[i] == target. However, two identical numbers located at distinct positions (i != j) are valid partners. - Arbitrary integer signs: Entries in
numsas well astargetcan be negative, zero, or positive, andnumsis not ordered. - Multiple or missing solutions: When more than one valid pair of positions exists, returning any single valid pair is accepted. When no two distinct positions add up to
target(including lists with fewer than two items), return[]. - Efficiency: Aim for
O(n)average runtime by trading auxiliary memory for fast lookups.
Examples
Example 1
nums = [9, 4, 12, 5]
target = 14
# Output: [0, 3]
Explanation: nums[0] + nums[3] = 9 + 5 = 14, and no other pair of distinct positions produces 14.
Example 2
nums = [5, -2, 7, 12]
target = 10
# Output: [1, 3]
Explanation: Position 0 holds 5, which cannot be added to itself because i != j is required. Pairing position 1 (-2) with position 3 (12) gives -2 + 12 = 10.
Example 3
nums = [6, 1, 6]
target = 12
# Output: [0, 2]
Explanation: Duplicate values at separate positions are allowed: nums[0] and nums[2] are both 6, so [0, 2] sums to 12.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9
Step-by-step walkthrough
Clarify the rules and boundary behaviors
We receive an unsorted integer list
numsand an integertarget, and we must return[i, j](i != j) wherenums[i] + nums[j] == target.Pin down the tricky cases before writing code:
- Distinct positions (
i != j), not distinct values:[6, 1, 6]withtarget = 12returns[0, 2], whereas[5, 7]withtarget = 10has no valid pair because index0cannot be used twice. - Negatives and zeros: Allowed anywhere in
numsortarget([5, -2, 7, 12]withtarget = 10returns[1, 3]), so we must never skip values larger thantarget. - Missing solution: When no two distinct indices add up to
target(orlen(nums) < 2), returning[]fits theList[int]return type cleanly.
- Distinct positions (
Brute force: why checking all pairs takes O(n²)
The straightforward baseline compares every pair of positions
i < j:def two_sum_brute(nums, target): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return []This uses
O(1)extra space, which is optimal for memory, but inspects up ton * (n - 1) / 2pairs — roughly 5 billion checks atn = 100,000. Whenever the outer scan stands atnums[j], only one exact partner value can complete the sum:target - nums[j]. Re-scanning earlier indices on every step is what costsO(n)per element.Key idea: trade O(n) memory for O(1) complement lookups
At
current_indexwith valuenum, letcomplement = target - numbe the exact partner we need. Rather than scanning backward, we keep a hash map (a Pythondict, providingO(1)average-time key lookups) namedseen_indexthat maps each already-visited number to an index where it appeared:target = 14, nums = [9, 4, 12, 5] current_index = 0, num = 9: complement = 14 - 9 = 5 -> is 5 in seen_index {}? No. record seen_index[9] = 0 -> seen_index is {9: 0} current_index = 1, num = 4: complement = 14 - 4 = 10 -> is 10 in {9: 0}? No. record seen_index[4] = 1 -> seen_index is {9: 0, 4: 1} current_index = 2, num = 12: complement = 14 - 12 = 2 -> is 2 in {9: 0, 4: 1}? No. record seen_index[12] = 2 -> seen_index is {9: 0, 4: 1, 12: 2} current_index = 3, num = 5: complement = 14 - 5 = 9 -> is 9 in seen_index? YES, at index 0! return [0, 3] immediatelyA single left-to-right pass finds any valid pair
i < j: when the loop visits the earlier positioni, it storesnums[i]inseen_index, so when the loop reaches the later positionj,complement = target - nums[j] = nums[i]is already waiting in the dictionary.Why lookup must happen before insert
On each iteration we check
complement in seen_indexand writeseen_index[num] = current_index. Doing the lookup first prevents an element from matching itself whentarget == 2 * num:Case A: nums = [5, 7], target = 10 (only ONE 5 -> must NOT match itself) index 0, num = 5, complement = 5: 1. Lookup 5 in {} -> NOT found (5 has not been inserted yet) 2. Insert seen_index[5] = 0 Case B: nums = [6, 1, 6], target = 12 (TWO 6s -> MUST match [0, 2]) index 0, num = 6: lookup 6 in {} -> miss; insert seen_index[6] = 0 index 1, num = 1: lookup 11 in {6: 0} -> miss; insert seen_index[1] = 1 index 2, num = 6: lookup 6 in {6: 0, 1: 1} -> HIT at index 0! Return [0, 2]Checking before inserting guarantees every index stored in
seen_indexis strictly smaller thancurrent_index: - No position ever pairs with itself (seen_index[complement] < current_index). - Duplicate numbers work automatically ([6, 1, 6]matches index0when visiting index2; if a duplicate has not completedtargetyet, overwritingseen_index[num]still leaves a valid earlier index for any later element). - The returned pair[seen_index[complement], current_index]comes out in ascending index order.from typing import Dict, List def two_sum(nums: List[int], target: int) -> List[int]: seen_index: Dict[int, int] = {} for current_index, num in enumerate(nums): complement = target - num if complement in seen_index: return [seen_index[complement], current_index] seen_index[num] = current_index return []Trace Example 2 and compare the three main designs
Trace
nums = [5, -2, 7, 12],target = 10step by step:current_index=0, num=5: complement = 10 - 5 = 5 5 in {}? No -> seen_index becomes {5: 0} current_index=1, num=-2: complement = 10 - (-2) = 12 12 in {5: 0}? No -> seen_index becomes {5: 0, -2: 1} current_index=2, num=7: complement = 10 - 7 = 3 3 in {5: 0, -2: 1}? No -> seen_index becomes {5: 0, -2: 1, 7: 2} current_index=3, num=12: complement = 10 - 12 = -2 -2 in {5: 0, -2: 1, 7: 2}? Yes, at index 1! -> return [1, 3]Notice how
5at index0avoided pairing with itself, and12 > targetstill combined with-2to hit10.Approach Time Extra Space Trade-off Brute force (all pairs) O(n²)O(1)Zero extra memory, but far too slow for large n.Sort (value, orig_idx)+ two pointersO(n log n)O(n)Still uses O(n)memory to remember original positions before sorting.One-pass hash map O(n)avgO(n)Fastest runtime; trades O(n)dictionary memory forO(1)average lookups.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def two_sum(nums: List[int], target: int) -> List[int]: # seen_index: {number: index_of_an_earlier_occurrence}, e.g. {5: 0, -2: 1} seen_index: Dict[int, int] = {} # Phase 1: Scan left to right, pairing each number against earlier numbers. for current_index, num in enumerate(nums): complement = target - num # Phase 2: Check seen_index BEFORE inserting num so an element at # current_index never pairs with itself (e.g. nums=[5, 7], target=10). if complement in seen_index: return [seen_index[complement], current_index] # Phase 3: Record num's index for future elements to match against. # Overwriting an older duplicate index is safe because any single earlier # index with this value forms an equally valid distinct pair. seen_index[num] = current_index # No two distinct indices sum to target. return []✅ Submit now — all tests should pass.
Intuition & how it works
Picture numbered tiles sliding past you one by one on a conveyor belt while you look for two tiles that add up to 10. Instead of grabbing each new tile and walking all the way back to inspect every earlier tile on the belt, you keep a labeled storage rack (a hash map, or Python dict) recording each value you have already seen and its position. When 12 arrives, the exact partner needed to reach 10 — its complement — is 10 - 12 = -2, so you check slot -2 on the rack: if an earlier index is sitting there, you return both indices right away; otherwise you place 12's index into slot 12 and move on.
The naive nested-loop solution compares every pair (i, j), performing up to n * (n - 1) / 2 additions — roughly 5 billion checks when n = 100,000 — because it repeatedly scans the same prefix of numbers. Spending O(n) memory on a dictionary turns each backward scan into an O(1) average-time lookup, finishing the entire search in a single O(n) pass.
Walk through nums = [5, -2, 7, 12] with target = 10:
1. current_index = 0, num = 5: complement = 10 - 5 = 5. seen_index is {}, so 5 is not present yet; store seen_index[5] = 0.
2. current_index = 1, num = -2: complement = 10 - (-2) = 12. 12 is not in {5: 0}; store seen_index[-2] = 1.
3. current_index = 2, num = 7: complement = 10 - 7 = 3. 3 is not in {5: 0, -2: 1}; store seen_index[7] = 2.
4. current_index = 3, num = 12: complement = 10 - 12 = -2. -2 is in {5: 0, -2: 1, 7: 2} at index 1, so return [1, 3].
Complexity
- Time:
O(n)on average, wherenislen(nums). We step throughnumsat most once, doing oneO(1)average-time dictionary lookup and at most oneO(1)average-time insertion per element. (In a pathological worst case where crafted integer keys cause repeated hash collisions — many distinct keys landing in the same internal bucket — lookups degrade toO(n), givingO(n²)worst-case time; on normal inputs runtime is linear.) - Space:
O(n)extra memory in the worst case (specificallyO(u)forudistinct values visited prior to a match), sinceseen_indexholds at most one index per unique number when no pair matches until the end.
Edge cases
- Empty list or single item (
[],[5]): Fewer than two elements cannot form a pair, so the loop finishes and returns[]. - No matching pair (
[1, 2, 3, 9],target = 100): Every element entersseen_indexwithout a hit and[]is returned cleanly. - Half-target single value vs duplicate (
target = 12on[6, 1]vs[6, 1, 6]): Checking before inserting returns[]on[6, 1](never pairing index0with itself) and[0, 2]on[6, 1, 6]. - Duplicates separated by unrelated items (
[1, 5, 2, 5],target = 10): Index1recordsseen_index[5] = 1, which index3later matches to return[1, 3]. - Negative values and zeros (
[-3, 4, 3, 90]withtarget = 0, or[0, 5, 0]withtarget = 0):target - numworks identically regardless of sign, returning[0, 2]. - Fixed-width integer overflow in other languages: Python integers have unbounded precision, whereas in C++ or Java
target - numcan overflow 32-bitint(such asINT_MIN - 1) unless computed inlong long/long.
Common mistakes
- Writing
seen_index[num] = current_indexbefore testingcomplement in seen_index: Causes[5, -2, 7, 12]withtarget = 10to match index0(5) with itself and return[0, 0]. - Building
{num: idx}in a separate first pass without checkingseen_index[complement] != current_index: Also pairs a half-target element with itself unless guarded by an index inequality check. - Sorting
numsin place for two pointers and returning the sorted indices: Loses the original positions requested by the caller; you must pair each value with its original index before sorting. - Ignoring elements where
num > target: Fails whenever negative numbers appear ([5, -2, 7, 12]needs12 > 10to pair with-2). - Returning
[complement, num](the numbers) rather than[i, j](their 0-based positions).
Alternative approaches
- Sort
(value, index)pairs + two pointers: Attach each element's original index, sort by value inO(n log n)time, and walkleftandrightpointers inward. Because keeping original positions still costsO(n)extra memory, it is slower thanO(n)hashing on unsorted lists, though if a variant only asked forTrue/Falseand allowed in-place sorting, two pointers would avoid dictionary allocation.
Follow-up questions
- How can you achieve O(1) extra memory if the input list is already sorted in non-decreasing order? Apply the two-pointer technique (starting
left = 0at the minimum element andright = len(nums) - 1at the maximum element, stepping one boundary inward per iteration): whennums[left] + nums[right] < target, advanceleftto raise the sum; when the sum exceedstarget, moverightleftward to lower it; when equal, return[left, right]. Each comparison permanently eliminates one end without allocating a dictionary, givingO(n)time andO(1)auxiliary space. - What changes if you need to return every valid pair rather than stopping at the first match? First clarify whether the caller wants all index pairs
(i, j)or all unique value pairs(a, b). For index pairs, map each value to a list of prior positions (seen_indices[num].append(j)) and emit(i, j)for everyiinseen_indices[complement], running inO(n + k)time forkoutput pairs (up toO(n²)if every entry is0andtarget = 0). For unique value pairs, maintain avisitedset and insert(min(num, complement), max(num, complement))into apairsset inO(n)average time. - How would you extend this approach to find three distinct indices whose values add up to target? Pair every number with its original position, sort by value in
O(n log n)time, loopifrom0ton - 3to anchor the first element, and run an inward two-pointer scan acrossi + 1 .. n - 1targetingtarget - nums[i]. That brings runtime down fromO(n³)brute force toO(n²)usingO(n)space for the index pairs (orO(1)extra space when returning deduplicated value triples from an in-place sort while skipping adjacent duplicates).
Follow-up questions
- How can you achieve O(1) extra memory if the input list is already sorted in non-decreasing order?
- What changes if you need to return every valid pair rather than stopping at the first match?
- How would you extend this approach to find three distinct indices whose values add up to target?
Similar questions
- Single-Game Tennis Scoreboard
- Column and Group Mean Imputation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance