LeetCode 1 Two Sum - Implementation

The approach

Store each number's index in a hash map. For each number, check if its complement (target minus current) exists in the map.

Here's the solution:

function twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

O(n)O(n) time, O(n)O(n) space.