All problems
Two-Sum Indices with Hash Set
Problem
Return the indices of two values in nums that add up to target.
Scan once with a dictionary from value to index; for each element check whether target minus that element has already been seen. Use the earliest j that works.
Return [i, j] with i < j, or an empty list when no pair exists.
Hint
Store each value's first index and look up the complement before inserting.
Test cases
case 1
in: [[2,7,11,15],9]
expected: [0,1]
case 2
in: [[3,2,4],6]
expected: [1,2]
case 3
in: [[3,3],6]
expected: [0,1]
case 4
in: [[1,2,3],7]
expected: []
case 5
in: [[],5]
expected: []
Starter codePython
def two_sum_indices(nums, target):
# Your code here
pass5 test cases · run your code against them in the editor