Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find a two-sum pair using a hash map

Find indices of two numbers that add up to a target using a hash map for O(n) time.

Python practice15 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

Given an array of integers nums and an integer target, return a tuple (i, j) of indices such that nums[i] + nums[j] == target and i < j. If multiple valid pairs exist, return the pair corresponding to the earliest j when scanning from left to right (i.e., the first pair you find in a single pass). If no such pair exists, return None. Aim for O(n) time and O(n) extra space.

Task

Use a hash map to record seen values and their indices so you can find a complementary value in O(1) time per element.

Examples

Simple two-sum

Input

nums = [2,7,11,15], target = 9

Output

(0, 1)

nums[0] + nums[1] == 9, so return indices (0,1).

Input format

two_sum_hash(nums, target) where nums is List[int] and target is int

Output format

A tuple (i, j) with i < j if a pair exists, otherwise None.

Constraints

2 <= len(nums) <= 10^5; integers are within 32-bit signed range. You may assume exactly one solution for some inputs, but your function should handle inputs with no solution by returning None.

Samples

Sample 1

Input

two_sum_hash([3,2,4], 6)

Output

(1, 2)

nums[1] + nums[2] == 6.