Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created July 15, 2024 21:31
Show Gist options
  • Save primaryobjects/f6aa07dd9bba2470824de04c3ec56832 to your computer and use it in GitHub Desktop.
Save primaryobjects/f6aa07dd9bba2470824de04c3ec56832 to your computer and use it in GitHub Desktop.
Two Sum solved in Python using brute force and hash map https://leetcode.com/problems/two-sum/
class Solution:
def twoSum1(self, nums: List[int], target: int) -> List[int]:
# O(n^2)
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if target - nums[i] == nums[j]:
return [i, j]
return None
def twoSum(self, nums: List[int], target: int) -> List[int]:
# O(n)
hash = {}
for i in range(len(nums)):
current = nums[i]
remainder = target - current
if remainder in hash:
return [hash[remainder], i]
else:
hash[current] = i
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment