Big O Gym › Problem

Big O Practice: Two Sum

Time and space complexity practice in Python and JavaScript. Concept tested: hashmap as a complement lookup.

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

Variables

  • n - length of the input array nums

Explanation

Single linear pass with a hash lookup at each step - **O(n)** time. The map stores at most `n` entries, giving **O(n)** auxiliary space. The hash map turns the inner search from O(n) into O(1).

More Big O practice problems · Today's daily problem