Two Sum - Leetcode 1 - Hashmaps & Sets (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

wow, the code was a little hard to understand at first, but when i coded it out myself, i finally got it. thanks greg!. Also, will this solution be accepted in coding interviews?

harshgamer
Автор

def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = dict()
for index, num in enumerate(nums):
diff = target-num
if diff in hashmap:
return [index, hashmap[diff]]
hashmap[num]=index

HumbleFool-xhq
Автор

You can simply do this with only one for-loop:
```python
def twoSum(self, nums: List[int], target: int) -> List[int]:
indices = {}
for i in range(len(nums)):
diff = target - nums[i]
if diff in indices:
return indices[diff], i
indices[nums[i]] = i
```

hamidonai
Автор

2:05 there is no point of updating this index. If the key already exists we can skip to the next iteration.

softcodeacademy
Автор

Hey Greg, the left bracket threw me up off for a bit. LOL. It looked like a reverse 3. Could you just make the middle part a bit more legible? { ... } Thanks!

hlubradio
Автор

@GregHogg hello, the hash map takes the latest occurrence's index. But what if there was an earlier occurrence of that index? Won't there be an error, not because the logic is incorrect, but the index is not of the earliest one? Might have understood, please be kind thanks.

cadentoh
Автор

I'm solving this in JAVA. And I didn't know containsKey method takes O(1) time complexity so I thought how is this O(N) time complexity, since it basically looked the same as brute force with using HashMaps.

baekBlackbeen
Автор

Make video explanation on Three Sum and Four Sum too...!

nerdyboy
Автор

How are you able to use List instead of list?

hlubradio
Автор

Why is the time complexity O(n)? Does the hashing solution contain two loops?

ApnaPakistan
Автор

Is this solution obvious for you? As a beginner, i would never get this solution😂

danangyudhatama
Автор

class Solution:
# Time complexity is O(n) and Space Complexity is O(n)
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_to_index = {} # Dictionary to store numbers and their indices
for i, n in enumerate(nums):
diff = target - n
if diff in nums_to_index:
return [nums_to_index[diff], i]
nums_to_index[n] = i
return []
Hi Greg, I would like to get to learn the code review comments from you on my code here^. It will be super helpful for my learning journey.
Looking forward to your response.

Sona-ykus
join shbcf.ru