Pair Sum Existence Check
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Implement two_sum_exists(nums, target), which accepts a list of integers nums and an integer target.
Return True if nums contains at least two elements located at different indices i and j (i != j) whose sum equals target (nums[i] + nums[j] == target); otherwise return False.
The two chosen positions must be distinct, although the integers stored at those two positions may have the same numeric value. In particular, a single element at index i cannot be added to itself, whereas two separate occurrences of the same value at indices i != j form a valid pair.
Examples
Example 1
nums = [14, -3, 8, 21]
target = 18
Output: True
Explanation: nums[1] = -3 and nums[3] = 21 sit at distinct positions and satisfy -3 + 21 == 18.
Example 2
nums = [5, 9, 1, 4]
target = 10
Output: True
Explanation: Even though nums[0] = 5 equals half of target, index 0 cannot be used twice. Continuing through the list, nums[1] = 9 and nums[2] = 1 sum to 10.
Example 3
nums = [6, 11, 6]
target = 12
Output: True
Explanation: Indices 0 and 2 are different positions that each store 6, giving 6 + 6 == 12.
Example 4
nums = [7, 2, 9, 15]
target = 14
Output: False
Explanation: 7 appears only once (at index 0), and no pair of distinct indices adds up to 14.
Constraints
0 <= len(nums) <= 2 * 10^5-10^9 <= nums[i] <= 10^9-2 * 10^9 <= target <= 2 * 10^9
Step-by-step walkthrough
Clarify distinct positions vs. distinct values
We receive a list of integers
numsand an integertarget, and must returnTrueif two elements at different indices add up totarget, orFalseotherwise.Notice the distinction between different indices (
i != j) and unequal values:nums = [6, 11, 6], target = 12->True(indices0and2are two separate positions that sum to12).nums = [7, 2, 9, 15], target = 14->False(index0holds7, and we cannot reuse that single position twice).
Because we only return
TrueorFalse, we can stop and returnTruethe moment we find any valid pair.Start with brute force: check every pair
The most direct solution tests every pair of positions
(i, j)withi < 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 True return FalseStarting
jati + 1guaranteesi != j, so no element is ever paired with itself. However,nelements formn * (n - 1) / 2pairs, making thisO(n²)time — roughly 20 billion additions whenn = 200,000.Why is brute force doing so much extra work? When we sit at
nums[i], we compare it against every later number even though only one exact value —target - nums[i]— could ever add withnums[i]to maketarget.Key idea: remember earlier values in a hash set
As we walk through
numsfrom left to right, suppose we keep a hash setseencontaining all numbers we have already passed. A hash set checks whether a value is present and inserts a new value inO(1)time on average.When we arrive at the current number
num:- Compute the exact partner it needs:
needed = target - num. - Check
if needed in seen: if yes, some earlier position holdsneeded, so those two distinct positions sum totarget— returnTrue! - Otherwise, add
numtoseenso future numbers can pair with it.
Notice why checking before adding is essential: - When
numis checked,numitself is not inseenyet, so a lone6withtarget = 12cannot match itself. - If a second6appears later in[6, 11, 6], the first6is already waiting insideseen, so the second6finds it immediately!- Compute the exact partner it needs:
Code the one-pass hash-set scan
def two_sum_exists(nums: List[int], target: int) -> bool: # seen: hash set of values from indices strictly before the current one, e.g. {14, -3} seen: Set[int] = set() # Sweep left to right once; check for the needed partner before recording `num`. for num in nums: needed = target - num if needed in seen: return True # Add `num` AFTER the lookup so a single element never pairs with itself # (e.g. [6] with target=12 stays False, while [6, 11, 6] with target=12 returns True). seen.add(num) return FalseTrace two tricky cases step by step
Example 2:
nums = [5, 9, 1, 4], target = 10(first element is half oftarget!)idx num needed (10 - num) seen BEFORE check needed in seen? seen AFTER add --- --- ----------------- ----------------- --------------- -------------- 0 5 5 {} No {5} 1 9 1 {5} No {5, 9} 2 1 9 {5, 9} Yes! -> return TrueAt
idx = 0,seenwas still empty when we looked for5, preventingnums[0]from pairing with itself.Example 3:
nums = [6, 11, 6], target = 12(duplicate value forms the pair)idx num needed (12 - num) seen BEFORE check needed in seen? seen AFTER add --- --- ----------------- ----------------- --------------- -------------- 0 6 6 {} No {6} 1 11 1 {6} No {6, 11} 2 6 6 {6, 11} Yes! -> return TrueCompare with sorting + two pointers
Interviews often ask how this
O(n)hash-set scan compares with sorting plus two pointers:def two_sum_sorted(nums: List[int], target: int) -> bool: values = sorted(nums) left = 0 right = len(values) - 1 while left < right: pair_sum = values[left] + values[right] if pair_sum == target: return True if pair_sum < target: left += 1 # need a larger sum else: right -= 1 # need a smaller sum return FalseApproach Time Extra Space Notes ----------------------- ------------- ------------------- ---------------------------------------- Hash set (our choice) O(n) average O(n) Fastest; keeps input untouched; streams Sort + two pointers O(n log n) O(1) in-place / O(n) Less memory if sorted in-place; mutatesUse the hash set by default for
O(n)speed; reach for two pointers when the input is already sorted (O(n)time andO(1)space!) or when memory is tightly capped and mutatingnumsin place is allowed.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def two_sum_exists(nums: List[int], target: int) -> bool: # seen: hash set of values from indices strictly before the current one, e.g. {14, -3} seen: Set[int] = set() # Sweep left to right once; check for the needed partner before recording `num`. for num in nums: needed = target - num if needed in seen: return True # Add `num` AFTER the lookup so a single element never pairs with itself # (e.g. [6] with target=12 stays False, while [6, 11, 6] with target=12 returns True). seen.add(num) return False✅ Submit now — all tests should pass.
Intuition & how it works
Imagine people walking through a doorway one by one, each holding a numbered ticket, looking for any second person whose ticket adds with theirs to target. Instead of asking every newcomer to interview everyone else in the building, a host at the door keeps a guestbook of ticket numbers already inside. When someone arrives with num, the host subtracts to find the complement (target - num — the exact missing value needed to complete target) and checks whether that number is already in the guestbook. If it is, we immediately have two different people whose tickets sum to target; if not, the host writes num into the guestbook using a hash set (a collection of unique values organized in hash buckets so lookups and insertions take O(1) constant time on average) and waves the next person forward.
Why do the obvious alternatives fall short? Testing every pair of indices (i, j) with two nested loops checks n * (n - 1) / 2 pairs, taking O(n²) quadratic time that bogs down on large arrays. Pre-building seen = set(nums) before looping is also broken: when num is exactly half of target (such as 5 with target = 10), target - num equals 5 and the single element falsely matches itself.
Walk through Example 2 (nums = [5, 9, 1, 4] with target = 10):
- Start with seen = set().
- Read 5: needed = 10 - 5 = 5. Is 5 in seen? No (seen is empty, so 5 does not pair with itself). Add 5 -> seen = {5}.
- Read 9: needed = 10 - 9 = 1. Is 1 in seen? No. Add 9 -> seen = {5, 9}.
- Read 1: needed = 10 - 1 = 9. Is 9 in seen? Yes! Return True.
Complexity
- Time:
O(n)on average, wherenislen(nums). We visit each number at most once, doing one subtraction, one hash-set lookup (O(1)average), and at most one hash-set insertion (O(1)average). In the theoretical worst case of adversarial hash collisions (many distinct numbers landing in the exact same hash bucket), operations can degrade, though for ordinary integer data lookups stay constant-time. - Space:
O(n)in the worst case, because when no pair sums totarget(or the matching pair sits at the very end),seenstores up tondistinct integers.
Edge cases
- Fewer than 2 elements (
[]or[6]):[]skips the loop and returnsFalse;[6]withtarget = 12checks6 in set()(False), adds6, finishes the loop, and returnsFalse. - Duplicate values that form the sum (
[6, 11, 6],target = 12): the first6entersseen, and the second6finds6 in seenand returnsTrue. - Single half-target value (
[7, 2, 9, 15],target = 14):7checksseenbefore7is added, so it returnsFalse. - Negative numbers and zeros (
[14, -3, 8, 21]with18, or[0, 4, 0]with0): subtractiontarget - numworks identically across positives, negatives, and zero (18 - 21 = -3). - Large integer magnitudes (
10^9and-10^9): Python integers have unlimited precision and never overflow; in Java or C++, computingtarget - numon extreme 32-bitintvalues can overflow, so cast tolong/long longfirst.
Common mistakes
- Calling
seen.add(num)beforeif needed in seen: inserting first putsnumintoseenprematurely, causing[6]withtarget = 12(or[7, 2, 9, 15]withtarget = 14) to matchnumwith itself and wrongly returnTrue. - Converting the whole list with
s = set(nums)up front: collapses duplicate counts, so you can no longer tell[6]apart from[6, 11, 6]whentarget = 12without maintaining a separate frequency map. - Requiring unequal values instead of distinct indices: Example 3 (
[6, 11, 6],target = 12->True) confirms that two elements at distinct indices may share the same integer value.
Alternative approaches
- Sorting + two-pointer technique: the two-pointer technique places one index
leftat the smallest value (0) and another indexrightat the largest value (n - 1) of a sorted array, steppingleftrightward whenvalues[left] + values[right] < target(to increase the sum) orrightleftward when the sum exceedstarget(to decrease the sum). Sorting costsO(n log n)time and the pointer sweep costsO(n). If you sort in place (such asnums.sort()), auxiliary space drops toO(1)at the cost of mutating the caller's list;sorted(nums)leaves the input intact usingO(n)space.
Follow-up questions
- How do the time, memory, and mutability trade-offs compare between a hash set and sorting with two pointers? Default to the hash set when speed matters (
O(n)vs.O(n log n)), when you must not reorder the caller's input array, or when numbers arrive as a live stream where you want to returnTrueon the first match without waiting for the entire dataset. Choose sorting + two pointers when memory is tightly constrained and in-place sorting is acceptable, when deterministicO(n log n)worst-case latency is required, or when the array is already sorted (making two pointersO(n)time andO(1)space simultaneously). - How would you adapt your code if the caller needed the two matching indices [i, j] rather than a boolean? Replace
seen = set()with a dictionaryindex_by_val = {}mapping each seen number to an earlier index where it appeared. Iterate withfor i, num in enumerate(nums):; iftarget - num in index_by_val, return[index_by_val[target - num], i], and otherwise setindex_by_val[num] = i. - Suppose nums contains billions of integers stored on disk that exceed available RAM; how would you test whether a valid pair exists? Partition the file into
Bdisk buckets using a symmetric hash keyh(min(x, target - x)) mod B. Becausemin(x, target - x)produces the exact same value whether you feed itxortarget - x, both halves of any valid pair are guaranteed to land in the same bucket file! You can then run the standard in-memoryseenset scan on one small bucket at a time, stopping as soon as any bucket returnsTrue.
Follow-up questions
- How do the time, memory, and mutability trade-offs compare between a hash set and sorting with two pointers?
- How would you adapt your code if the caller needed the two matching indices [i, j] rather than a boolean?
- Suppose nums contains billions of integers stored on disk that exceed available RAM; how would you test whether a valid pair exists?
Similar questions
- Sum Active Loan Balances Per Borrower
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One