03-1 : Two Sum

Arrays / Hashing

I walk you through how to solve Leetcode problem 1. Two Sum. I highlight a couple of approaches to solving it. As usual, there are various trade-offs between time and space complexity respective to each approach.

Approach 1: Brute Force

def twoSum(nums, target):
    for i in range(len(nums) - 1):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i,j]

Time Complexity: O(N²)
Space Complexity: O(1)

Approach 2: HashMap

def twoSum(nums, target):
        numbersSeen = {}
        for index, num in enumerate(nums):
            diff = target - nums[index]
            if diff in numbersSeen:
                return [numbersSeen[diff], index]
            numbersSeen[nums[index]] = index

Time Complexity: O(N)
Space Complexity: O(N)