Code-Memo

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

nums = [2, 7, 11, 15]
target = 9
# Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)

Simple Approach: Nested Loops

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

Explanation:

Optimized Approach: HashMap

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_map = {}
        for i in range(len(nums)):
            current_number = nums[i]
            difference = target - current_number
            if difference in nums_map:
                return [nums_map[difference], i]
            nums_map[current_number] = i
        return []

Explanation: