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

  1. Clarify distinct positions vs. distinct values

    We receive a list of integers nums and an integer target, and must return True if two elements at different indices add up to target, or False otherwise.

    Notice the distinction between different indices (i != j) and unequal values:

    • nums = [6, 11, 6], target = 12 -> True (indices 0 and 2 are two separate positions that sum to 12).
    • nums = [7, 2, 9, 15], target = 14 -> False (index 0 holds 7, and we cannot reuse that single position twice).

    Because we only return True or False, we can stop and return True the moment we find any valid pair.

  2. Start with brute force: check every pair

    The most direct solution tests every pair of positions (i, j) with 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 True
        return False
    

    Starting j at i + 1 guarantees i != j, so no element is ever paired with itself. However, n elements form n * (n - 1) / 2 pairs, making this O(n²) time — roughly 20 billion additions when n = 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 with nums[i] to make target.

  3. Key idea: remember earlier values in a hash set

    As we walk through nums from left to right, suppose we keep a hash set seen containing all numbers we have already passed. A hash set checks whether a value is present and inserts a new value in O(1) time on average.

    When we arrive at the current number num:

    1. Compute the exact partner it needs: needed = target - num.
    2. Check if needed in seen: if yes, some earlier position holds needed, so those two distinct positions sum to target — return True!
    3. Otherwise, add num to seen so future numbers can pair with it.

    Notice why checking before adding is essential: - When num is checked, num itself is not in seen yet, so a lone 6 with target = 12 cannot match itself. - If a second 6 appears later in [6, 11, 6], the first 6 is already waiting inside seen, so the second 6 finds it immediately!

  4. 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 False
    
  5. Trace two tricky cases step by step

    Example 2: nums = [5, 9, 1, 4], target = 10 (first element is half of target!)

    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 True
    

    At idx = 0, seen was still empty when we looked for 5, preventing nums[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 True
    
  6. Compare 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 False
    
    Approach                 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; mutates
    

    Use the hash set by default for O(n) speed; reach for two pointers when the input is already sorted (O(n) time and O(1) space!) or when memory is tightly capped and mutating nums in place is allowed.

  7. 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, where n is len(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 to target (or the matching pair sits at the very end), seen stores up to n distinct integers.

Edge cases

  • Fewer than 2 elements ([] or [6]): [] skips the loop and returns False; [6] with target = 12 checks 6 in set() (False), adds 6, finishes the loop, and returns False.
  • Duplicate values that form the sum ([6, 11, 6], target = 12): the first 6 enters seen, and the second 6 finds 6 in seen and returns True.
  • Single half-target value ([7, 2, 9, 15], target = 14): 7 checks seen before 7 is added, so it returns False.
  • Negative numbers and zeros ([14, -3, 8, 21] with 18, or [0, 4, 0] with 0): subtraction target - num works identically across positives, negatives, and zero (18 - 21 = -3).
  • Large integer magnitudes (10^9 and -10^9): Python integers have unlimited precision and never overflow; in Java or C++, computing target - num on extreme 32-bit int values can overflow, so cast to long / long long first.

Common mistakes

  • Calling seen.add(num) before if needed in seen: inserting first puts num into seen prematurely, causing [6] with target = 12 (or [7, 2, 9, 15] with target = 14) to match num with itself and wrongly return True.
  • 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] when target = 12 without 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 left at the smallest value (0) and another index right at the largest value (n - 1) of a sorted array, stepping left rightward when values[left] + values[right] < target (to increase the sum) or right leftward when the sum exceeds target (to decrease the sum). Sorting costs O(n log n) time and the pointer sweep costs O(n). If you sort in place (such as nums.sort()), auxiliary space drops to O(1) at the cost of mutating the caller's list; sorted(nums) leaves the input intact using O(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 return True on 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 deterministic O(n log n) worst-case latency is required, or when the array is already sorted (making two pointers O(n) time and O(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 dictionary index_by_val = {} mapping each seen number to an earlier index where it appeared. Iterate with for i, num in enumerate(nums):; if target - num in index_by_val, return [index_by_val[target - num], i], and otherwise set index_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 B disk buckets using a symmetric hash key h(min(x, target - x)) mod B. Because min(x, target - x) produces the exact same value whether you feed it x or target - x, both halves of any valid pair are guaranteed to land in the same bucket file! You can then run the standard in-memory seen set scan on one small bucket at a time, stopping as soon as any bucket returns True.

Follow-up questions

Similar questions

More LendingClub interview questions

All 2 LendingClub questions →