CORE.DUMP

1. Two Sum

Find indices of two numbers that add up to a target.

Easy#1ArrayHash TableLeetCode

Approach 1: Two-Pass Hash Map

Algorithm:

  1. First pass builds the full map
  2. Second pass looks up complements
    • Skipping the element itself
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for i, num in enumerate(nums):
            seen[num] = i

        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen and seen[complement] != i:
                return [i, seen[complement]]

        return []
  • Time: O(n)O(n) — two linear passes.
  • Space: O(n)O(n) — the value→index map.

Approach 2: One-Pass Hash Map

Why one-pass is sufficient:

  • The valid answer is some pair (i, j) where i < j.
  • When the loop reaches index j, index i has already been visited and stored in the map.

The one-pass approach avoids the self-use edge case entirely.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen:
                return [i, seen[complement]]
            seen[num] = i

        return []
  • Time: O(n)O(n) — single pass over the array.
  • Space: O(n)O(n) — the hash map of seen values.

Takeaway

ApproachTimeSpace
Brute ForceO(n2)O(n^2)O(1)O(1)
Two-Pass Hash MapO(n)O(n)O(n)O(n)
One-Pass Hash MapO(n)O(n)O(n)O(n)

The one-pass hash map is optimal: it matches the best time complexity while making a single traversal and handling the duplicate-index case cleanly.

Last updated on