Pair Indices with Given Sum
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests hash table usage and algorithm optimization to locate two array positions that sum to a target value.
You are given an array of integers nums and an integer target.
Find two different positions in the array whose values add up to target. Return their indices as a list [i, j] where i < j.
If no such pair of positions exists, return an empty list [].
You may assume that each valid input has at most one solution, but you must handle cases where no solution exists.
Constraints:
1 ≤ len(nums) ≤ 10⁴-10⁹ ≤ nums[i] ≤ 10⁹-10⁹ ≤ target ≤ 10⁹- The two indices must be distinct (you cannot use the same position twice)
- If multiple valid pairs exist, return any one of them
Examples
Example 1
Input: find_pair_sum([2, 7, 11, 15], 9)
Output: [0, 1]
Example 2
Input: find_pair_sum([3, 2, 4], 6)
Output: [1, 2]
Example 3
Input: find_pair_sum([3, 3], 6)
Output: [0, 1]
Hints
Hint 1
What value would you need to have already seen when you encounter each element?
Hint 2
A hash table can tell you in constant time whether you've seen a specific value before.
Hint 3
Make sure to check for the complement before adding the current element to avoid pairing an element with itself.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to reframe the problem: instead of checking all possible pairs, ask for each element "have I already encountered the value that would complete this sum?"
For each element at position i with value v, we need another element with value target - v. By maintaining a hash table that maps values to their first occurrence index, we can check for the required complement in constant time.
The algorithm scans the array once:
- Calculate the complement needed:
complement = target - current_value - Check if this complement already exists in our hash table
- If yes, we've found our pair—return the stored index and current index
- If no, record the current value and its index (only if not already stored)
The crucial detail is checking for the complement before inserting the current element. This prevents an element from incorrectly pairing with itself when the target is exactly twice its value.
Why It Works
Consider any valid solution pair at positions (a, b) where a < b. When we reach position b during our scan, position a has already been processed and its value is in our hash table. Therefore, we will find nums[a] when looking up target - nums[b], and we return immediately.
We cannot return an invalid pair because we only return when the sum actually equals the target, and the stored index is always less than the current index (ensuring distinct positions).
Complexity
Time: O(n) where n is the length of the array. We make a single pass through the array, and each hash table operation (lookup and insertion) takes O(1) expected time.
Space: O(n) in the worst case. When no valid pair exists, we store nearly every distinct value in the hash table. If the array contains many duplicates, the space usage is correspondingly smaller.
Alternative Approaches
A sorting-based solution using two pointers would achieve O(n log n) time but requires O(n) space to preserve original indices (by sorting value-index pairs). The hash table approach is optimal for this problem.
from typing import List
def find_pair_sum(nums: List[int], target: int) -> List[int]:
seen = {}
for i, value in enumerate(nums):
complement = target - value
if complement in seen:
return [seen[complement], i]
if value not in seen:
seen[value] = i
return []