JavaScript required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
Gallery
Algoschool
Algocircle
More
Share
Explore
Level 1
Two pointers problems
n ^ 2 solution
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target and i != j:
return [i, j]
return [-1, -1]
hash map O(n)
class Solution(object):
def twoSum(self, nums, target):
m = {}
for i, n in enumerate(nums):
m[n] = i
for i in range(len(nums)):
diff = target - nums[i]
if diff in m and i != m[diff]:
return [m[diff], i]
return [-1, -1]
one pass
class Solution(object):
def twoSum(self, nums, target):
m = {}
for i in range(len(nums)):
diff = target - nums[i]
if diff in m:
return [m[diff], i]
m[nums[i]] = i
return [-1, -1]
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.