Leetcode 1: Two Sum

Finding a pair of numbers that add up to a target dynamically using a one-pass Hash Map.

The original problem is here.

Hash Map Approach

Algorithm

Instead of just tracking values, our Hash Map cache must map the actual numbers seen natively to their original index positions in the string array, because the prompt explicitly demands we return the indices.

  1. First pass: Loop through the nums array linearly. Fill in the hash map where key is num and value is index.
  2. Second pass: Calculate the complement for each num, and check if the complement is in the hash map. If yes, return the index of the complement and the current index.
    • when complement = num, we need to distinguish between one occurrence and two occurrences. We should add if statement in in statement.

My solution

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

Complexity Analysis