KatInterview

Pair Indices with Given Sum

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinghash-maptwo-pointersoptimization

Last 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.