Notes

Personal notes on various topics

View on GitHub

Intuition

To find two numbers that add up to the target, we can use a hash map to store previously seen numbers and their indices. For each number, we check if its complement (target - current number) exists in the map.

Approach

Complexity

Code

from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map_ = {nums[0]: 0}

        for i in range(1, len(nums)):
            comp = target - nums[i]

            if comp in map_:
                return [map_[comp], i]

            map_[nums[i]] = i

        return [-1, -1]

Back to Problem Statement