Find All Anagrams in a String - Leetcode 438 - Python

  Рет қаралды 77,337

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: / discord
🐦 Twitter: / neetcode1
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
📚 STACK PLAYLIST: • Stack Problems
Problem Link: leetcode.com/problems/find-al...
0:00 - Read the problem
2:30 - Drawing Explanation
6:54 - Coding Explanation
leetcode 438
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#coding #interview #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 60
@venkatasriharsha4227
@venkatasriharsha4227 2 жыл бұрын
After watching so many problems u solved, it's just a cake walk for me to solve this. Thanks a ton bro ❤️
@srinadhp
@srinadhp 2 жыл бұрын
As usual very aesthetic explanation and solution!
@auroshisray9140
@auroshisray9140 2 жыл бұрын
Really helpful ...from approach to code is always a tough part
@MP-ny3ep
@MP-ny3ep Жыл бұрын
This solution is awesome . Thank you so much !
@7Ibby
@7Ibby 2 жыл бұрын
Hi. Really enjoy your videos and have been learning a lot from you. Just wanted to share my way I did this problem, if that's cool. After checking the edge case of length of p being greater than length of s, I created two dictionaries/hashmaps and initialized them with all the letters from set(s+p) with 0. This allows you to skip the check if the letter in the dictionary/hashmap is zero and pop it. Then incremented the first (length of p) letters in both dictionaries/hashmaps. After, I just use a for loop, check if the dictionaries are equal and then decrement the left letter and increment the next letter in string s until the end. I'd share my code if you're cool with it or if you're interested.
@EagerEggplant
@EagerEggplant 2 жыл бұрын
you dont need a for loop to check if the dicts are equal
@chethan0
@chethan0 2 жыл бұрын
@Neetcode : I think you should increment the left pointer only after appending it to the result if the counts match, Otherwise you will be appending the index+1 into the results
@pritz9
@pritz9 Жыл бұрын
Nope, check the algorithm ,its absolutely fine...make a dry run ,u will get it.
@kumarspandanpattanayak3489
@kumarspandanpattanayak3489 Жыл бұрын
Thanks Man , good one :)
@vedgantilles9379
@vedgantilles9379 2 жыл бұрын
If the size of alphabet not a constant, this solution has O(n^2) asymptotic in worst case. Actually, there is O(n) solution in this case. You should calculate the number of symbols , which counts in p equal to counts in current window And when this number will be equal to number of keys in pCount, it's the answer
@MyPodie
@MyPodie Жыл бұрын
Is there a way to solve it with just one for loop? Or is the first loop necessary and why is that? I keep trying to come up with one but can't. Thanks!!
@zihaoli9683
@zihaoli9683 2 жыл бұрын
wow this is pretty brilliant
@viggicodes
@viggicodes Жыл бұрын
One more approach using char counter -> represent the string as count of each alphabet. def findAnagrams(self, s: str, p: str) -> List[int]: l = 0 res = [] counter = [0] *26 for c in p: index = ord(c) - ord('a') counter[index] = counter[index] + 1 counter2 = [0] * 26 for r in range(len(s)): index = ord(s[r]) - ord('a') counter2[index] = counter2[index] + 1 while r - l + 1 == len(p): if counter2 == counter: res.append(l) index = ord(s[l]) - ord('a') counter2[index] = counter2[index] -1 l = l + 1 return res
@sam_pnw
@sam_pnw 2 жыл бұрын
Good job
@garwar1234
@garwar1234 2 жыл бұрын
Getting time limit exceeded on leetcode for this solution. I coded in swift.
@krateskim4169
@krateskim4169 Жыл бұрын
Thank You
@mingjuhe1514
@mingjuhe1514 2 жыл бұрын
Thanks bro
@fayequehannan2473
@fayequehannan2473 Жыл бұрын
There can be also one more optimisation we can do if we found a char which is not present in p then we can simply move the left pointer to the position of that char in s +1 and apply the same algo from there...please let me know if it can be considered as a optimisation or not
@Bullimicporkupine
@Bullimicporkupine 4 ай бұрын
yes it is, shift right by len(p)
@isabelayala7477
@isabelayala7477 2 жыл бұрын
This makes so much sense. I had a similar approach in mind but just couldn’t figure out how to implement it. Thanks so much!
@Rishabhsingh-ev7ii
@Rishabhsingh-ev7ii 2 жыл бұрын
what is logic here in 16 line can anyone explain me
@user-ff2ep5kk5i
@user-ff2ep5kk5i 6 ай бұрын
@@Rishabhsingh-ev7ii since we are comparing the maps, we need to pop the key when there is a 0 count for that key.
@xyz-vv5tg
@xyz-vv5tg 9 ай бұрын
Folks is there anyone like me who first sees the question, thinks a lot about it and have absolutely no idea how to even approach the problem, and then later checks neetcode just see the solution? I'm afraid that I can't even think of solutions to basic problems
@johndong4754
@johndong4754 9 ай бұрын
Absolutely nothing wrong with that! It's better to check the solution than to spend too much time trying to solve it on your own. Just make sure you understand why the solution works and how to come up with it
@xyz-vv5tg
@xyz-vv5tg 9 ай бұрын
@@johndong4754 Thanks a lot for the affirmation John. I'm able to understand why the solution works.
@VarunMittal-viralmutant
@VarunMittal-viralmutant 2 жыл бұрын
Using deque, islice and Counter :) p_c = Counter(p) anagrams = [] it = iter(s) sliding_window = deque(islice(it, len(p)), maxlen=len(p)) s_c = Counter(sliding_window) if s_c == p_c: anagrams.append(0) for index, char in enumerate(it, start=1): s_c[char] += 1 s_c[s[index-1]] -= 1 if s_c == p_c: anagrams.append(index) return anagrams
@daniyaljavaid329
@daniyaljavaid329 3 ай бұрын
was creating map for every substring when sliding a window & now using only single map for sliding, improved from 1300ms to 450ms kotlin
@shreyabhattacherjee6388
@shreyabhattacherjee6388 5 ай бұрын
Thanks a lot for the solution, this is very helpful, how is it ensured that the keys in the two hash maps are in the same order ? If they are not the same then the comparison of the two dictionaries will result in False
@ramyaarathnakumar7468
@ramyaarathnakumar7468 2 жыл бұрын
Have a doubt here, if we're anyways creating a hashmap sliding window over s, why not start from 0, the operation is anyway the same, why do we need to create a separate for loop initially?
@shreyabhattacherjee6388
@shreyabhattacherjee6388 5 ай бұрын
I have the same question
@swarnabhkashyap5764
@swarnabhkashyap5764 2 жыл бұрын
Great video. Just one doubt. Why are we decrementing the count of the character represented by the left pointer by 1 instead of removing the character from sCount dictionary?
@rajkumarkhatri8119
@rajkumarkhatri8119 2 жыл бұрын
Think of ‘aaaaaaa’ if your left pointer is at first ‘a’ then left += 1, if you remove ‘a’ from count dictionary, that is misleading because you several other occurrences of ‘a’ in your sliding window
@naveenprasanthsa3749
@naveenprasanthsa3749 2 жыл бұрын
Happy diwali💥💣
@Chirayu19
@Chirayu19 11 ай бұрын
Another similar approach: Create two pointers L and R Check both the maps: If you find any freq lesser than the other map-> Increment R If you find any freq greater than the other map-> Increment L If all are eqaul -> Updater answer and increment both L and R
@Witch_Quiz
@Witch_Quiz 6 ай бұрын
I also think like you
@lilyh4573
@lilyh4573 2 жыл бұрын
Are all medium problems this tricky and hard?!? Oh man DX thanks for trying to teach us noobs Neet!!
@asrahussain8642
@asrahussain8642 11 ай бұрын
10:44 why did we pop s[l] ?
@SAROJKUMAR-xe8vm
@SAROJKUMAR-xe8vm 8 ай бұрын
so the time complexity will be O(len(s)*len(p)), because comparing two dictionaries will take O(len(keys))
@ngneerin
@ngneerin 2 жыл бұрын
Can't compare two hashmaps in javascript in one sentence. It is a O(n) operation
@mocamoca_enh
@mocamoca_enh 2 жыл бұрын
It is also O(n) in Python. He explains that comparing the 2 hashmaps in this specific problem to be O(26) since there are constraints on the anagram string to be only using a-z. Despite the size of string p either hashmap will have a maximum size of 26.
@sagarpotnis1215
@sagarpotnis1215 2 жыл бұрын
how is the complexity of the solution O(n) ? should it be O(s x p)
@nioi
@nioi Жыл бұрын
The size of the hashmap is at max O(26). Therefore it is O(p + s * 26)
@xenky0
@xenky0 Жыл бұрын
Me too, the dict comparison should take O(p) right?
@faizanahmed6072
@faizanahmed6072 Жыл бұрын
def findAnagrams(self, s: str, p: str) -> List[int]: if len(s) < len(p): return [] c=Counter(p) res=[] for i in range(len(s)-len(p)+1): temp=Counter(s[i:i+len(p)]) if temp==c: res.append(i) return res
@Rishabhsingh-ev7ii
@Rishabhsingh-ev7ii 2 жыл бұрын
what is logic here in 16 line can anyone explain me
@hero_py
@hero_py 2 жыл бұрын
We increment the left pointer. As such, we are no longer pointing at a character (and we're pointing at a new character at the left pointer), so we decrement the count of that character in sCount. If the count of that character is 0, we remove it from the dictionary.
@gladyouseen8160
@gladyouseen8160 2 жыл бұрын
Hey bro i follow your videos. The most of videos are pythonic way. It would be good if you tell some logic that can be possible to optmise more. For e.g. Here we could have reduced one dictionary and use a variable called "distinct_letters_in_d" and when ever it reaches to 0 we could have added the "l" to res
@ritwik121
@ritwik121 2 жыл бұрын
share ur code
@nagendrabommireddi8437
@nagendrabommireddi8437 Жыл бұрын
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: a=Counter(list(p)) print(a) d=[] i=0 j=0 while j
@nagadinesh8364
@nagadinesh8364 Жыл бұрын
Baeause u are using Counter function , Time Complexity for Counter Function is O(n)
@nagendrabommireddi8437
@nagendrabommireddi8437 Жыл бұрын
@@nagadinesh8364 thank you bro
@pratyakshsinha6292
@pratyakshsinha6292 Жыл бұрын
Laughs in C++
@parulvats
@parulvats Жыл бұрын
wow
@friction5001
@friction5001 2 жыл бұрын
First comment
@foreverbowie2720
@foreverbowie2720 Ай бұрын
Share my super simple solution: def findAnagrams(self, s: str, p: str) -> List[int]: res = [] p = sorted(p) l = 0 for r in range(len(p) - 1, len(s)): if sorted(s[l:r + 1]) == p: res.append(l) l += 1 return res
@varunshrivastava2706
@varunshrivastava2706 2 жыл бұрын
Just one suggestion @NeetCode please avoid using one-liners they are not readable and cause ambiguity.
@fa11en1ce
@fa11en1ce 2 жыл бұрын
Looks fine to me imo
@B-Billy
@B-Billy 4 ай бұрын
No issues in that...
Decode String - Leetcode 394 - Python
16:26
NeetCode
Рет қаралды 80 М.
Sliding Window Maximum - Monotonic Queue - Leetcode 239
15:46
NeetCode
Рет қаралды 226 М.
Now THIS is entertainment! 🤣
00:59
America's Got Talent
Рет қаралды 38 МЛН
Count Occurrences Of Anagrams | Sliding Window
39:56
Aditya Verma
Рет қаралды 216 М.
Object-Oriented Programming is Embarrassing: 4 Short Examples
28:03
This video will change your mind about the AI hype
17:07
NeetCode
Рет қаралды 135 М.
Permutation in String - Leetcode 567 - Python
19:40
NeetCode
Рет қаралды 198 М.
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 281 М.
Longest Repeating Character Replacement - Leetcode 424 - Python
20:44
The Algorithm Behind Spell Checkers
13:02
b001
Рет қаралды 408 М.
Kumanda İle Bilgisayarı Yönetmek #shorts
0:29
Osman Kabadayı
Рет қаралды 486 М.
Look, this is the 97th generation of the phone?
0:13
Edcers
Рет қаралды 4,7 МЛН
تجربة أغرب توصيلة شحن ضد القطع تماما
0:56
صدام العزي
Рет қаралды 58 МЛН
Отдых для геймера? 😮‍💨 Hiper Engine B50
1:00
Вэйми
Рет қаралды 1,3 МЛН
Лазер против камеры смартфона
1:01
NEWTONLABS
Рет қаралды 346 М.