Math Fundamentals18 sections · 814 units
Open in Course

Two Sum - Implementation

(Hash map approach)

function twoSum(arr, target):
    map = {}
    for i from 0 to arr.length - 1:
        complement = target - arr[i]
        if complement in map:
            return [map[complement], i]
        map[arr[i]] = i
    return null

Time: O(n). Space: O(n). This is better than O(n²) brute force.