1. Two Sum
Debjoty Mitra
1 min read
Table of contents
YouTube Video
[A1] - Brute Force
Time: O(n^2)
Space: O(1)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return
[A2] - Hash Table
Time: O(n)
Space: O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i,e in enumerate(nums):
dict[e]=i
for i in range(len(nums)):
diff = target-nums[i]
if diff in dict and i!=dict[diff]:
return [i,dict[diff]]
return
Comment: There is another way where you can solve the problem using a single iteration. Try to do it by yourself.
0
Subscribe to my newsletter
Read articles from Debjoty Mitra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by