Implement Trie (Prefix Tree) - Leetcode 208

  Рет қаралды 212,396

NeetCode

NeetCode

Күн бұрын

Пікірлер: 174
@NeetCode
@NeetCode 3 жыл бұрын
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@evalyly9313
@evalyly9313 3 жыл бұрын
This is the best Trie introduction video I watched in youtube, very clear and concise. Bravo!
@ARkhan-xw8ud
@ARkhan-xw8ud 3 ай бұрын
watch striver series
@sucraloss
@sucraloss Жыл бұрын
You legitimately explain these concepts better than any professor I've had, and I went to one of the most highly regarded schools in the US for Computer Science. You outdid both the professors and their teaching assistants. You have a gift for explaining this stuff.
@sanjanar9198
@sanjanar9198 2 жыл бұрын
Never thought Trie would be this easy to understand, thanks a lott!!
@sprajosh
@sprajosh 2 жыл бұрын
I avoided trie for so long thinking it will be difficult to understand. Thanks for this. This was very easy.
@niravarora9887
@niravarora9887 10 ай бұрын
I am with you on this, hahaha
@z7847
@z7847 2 жыл бұрын
Neetcode really saving the day here. I watched other videos, but none explained and illustrated how to code it efficiently. Your drawing is so helpful and the clean, simple code makes sense. Thanks Neet!
@starboi_6
@starboi_6 Ай бұрын
I am usually struggling with new data structures, but you made it simple and smooth. Tanks for the great video.
@sravanikatasani6502
@sravanikatasani6502 3 жыл бұрын
Thank you so much!! I have learnt a new data structure today..
@aaab45357
@aaab45357 6 ай бұрын
A note on implementation: instead of a python class representing the node, you can simply represent each node as a dictionary of chars to dictionaries and use a placeholder (like '$') to mark the end of a word. This will be more efficient (same big-O, though) in python in both memory and time, for you are not wasting a bunch of space pre-allocating lists, you are not having to deal with python's overheads and, most importantly, you would be using a highly optimized python data structure calling c under the hood. On top of all of that, you get a cleaner implementation
@GinsuGames
@GinsuGames 2 ай бұрын
I think the class approach is much cleaner to read
@Kokurorokuko
@Kokurorokuko Ай бұрын
@@GinsuGames yeah, and it works for any kinds of strings
@elias043011
@elias043011 6 ай бұрын
Great explanation! The very important take away here was that you mark the end of a valid word with the TrieNode variable, otherwise "appl" may look like a valid word after inserting "apple"
@bugracansefercik917
@bugracansefercik917 4 ай бұрын
Thank you for the great video. If assume words are ending with a certain character like '.'. There might be a shorter and simpler solution: class Trie: def __init__(self): self.trie = dict() def insert(self, word: str) -> None: curr_trie = self.trie for l in f'{word}.': if l not in curr_trie: curr_trie[l] = dict() curr_trie = curr_trie[l] def search(self, word: str) -> bool: return self.startsWith(f'{word}.') def startsWith(self, prefix: str) -> bool: curr_trie = self.trie for l in prefix: if l not in curr_trie: return False curr_trie = curr_trie[l] return True
@kritmok1875
@kritmok1875 Жыл бұрын
never thought that I would get the best trie introduction video in a leetcode video. Thanks for the great work!
@hmanjun7260
@hmanjun7260 Жыл бұрын
Using a hash map was genius. Once I saw that, I went and redid my code before looking at the rest of ur solution
@Xavierrex3
@Xavierrex3 11 ай бұрын
Man your videos are incredible, and I've learned so much about programming in general just from your channel. Before this I was stunned about how to approach problems like this or dynamic programming but just from following solutions and understanding the concepts better I can do problems like this moderately well now
@tapasheetabassumurmi1895
@tapasheetabassumurmi1895 4 ай бұрын
I am getting addicted to this channel!! Thanks God!! You've sent this man for us!
@WalterGordyCanada
@WalterGordyCanada Жыл бұрын
These videos are literally better than the courses I took in University. Thank you!
@nou4605
@nou4605 9 ай бұрын
The code is marvelously simple considering how useful of a data structure this can be.
@1-ov947
@1-ov947 Жыл бұрын
You are the best leetcode teacher on entire KZbin!
@iugaialeksei2108
@iugaialeksei2108 Жыл бұрын
OMG, man, you possess a special talent to explain complicated things smoothly and simple. I'm a big fan of your channel!
@rkkasotiya
@rkkasotiya Жыл бұрын
Simplest video to understand Trie and implement it. Keep up the good work.
@BobbyMully
@BobbyMully 2 жыл бұрын
When I did this one before wathcing the video, my code was double the length of yours. Nice solve!
@tjsm4455
@tjsm4455 Жыл бұрын
Good explanation. After understanding the logic I implemented the code myself. Feels good.
@seanjcan
@seanjcan Жыл бұрын
Best explanation of Tries I have come across so far. Bravo!
@lymmontijo87
@lymmontijo87 8 ай бұрын
Thank you!! I had never seen tries and had been avoiding it. Its actually quite easy.
@Dhruvbala
@Dhruvbala 5 ай бұрын
This was one of the more enjoyable problems I've done
@nhuphan7112
@nhuphan7112 2 жыл бұрын
honestly just want to say your videos been great in my interview prep :) (totoal newbie at leetcode)
@Manu-et6zk
@Manu-et6zk 3 жыл бұрын
please explain time and space complexity after u solve the problem
@juliacheng4751
@juliacheng4751 3 жыл бұрын
Time is O(n*m) for insertion (n is the number of words, m is the max len), O(m) for search. Space is O(n * m)
@Kokurorokuko
@Kokurorokuko Ай бұрын
@@juliacheng4751 I think you're incorrect. Time complexity is O(m) for insertion. Space complexity is O(m).
@deniyii
@deniyii Жыл бұрын
A more useful and challenging problem would be to return a list of words that starts with a given prefix. Pretty much autocomplete. I’m not sure if that one can be solved iteratively though, I’ve only seen it done recursively.
@vashishtgupta7416
@vashishtgupta7416 2 жыл бұрын
I haven't seen better tutorials than yours for LC problems anywhere! Great work :)
@reddev9143
@reddev9143 3 жыл бұрын
Thank you so much! Just can’t tell how cool and valuable your videos are! Keep’em coming!
@unanimous8510
@unanimous8510 Жыл бұрын
What an amazing explanation for the guy who just started learning tries 👍
@antonyndungu5514
@antonyndungu5514 3 жыл бұрын
I have watched a few explanations on the tries, this is the best. Keep them coming at least for now you don't have a job
@TechOnScreen
@TechOnScreen 2 жыл бұрын
dude he is in google !.. someone truly said. Time is mightier than fate..
@antonyndungu5514
@antonyndungu5514 2 жыл бұрын
@@TechOnScreen Yah, I knew with his level of skills its just a matter of time and he will get one of those top jobs in the industry
@TechOnScreen
@TechOnScreen 2 жыл бұрын
@@antonyndungu5514 yeah dude.. hope some day we will have our luck too 😂
@antonyndungu5514
@antonyndungu5514 2 жыл бұрын
@@TechOnScreen True, can't wait for that :-)
@Z00keeper54
@Z00keeper54 10 күн бұрын
Minor gripe (at least for the JavaScript version) - the constraints indicate that word and prefix have to be at least 1 lowercase English letter, but when you go to submit, the test tries passing in empty strings.
@saumyatyagi8768
@saumyatyagi8768 2 жыл бұрын
This is the best Trie vid so far ! Excellent explaination . 👍
@Lmcrf
@Lmcrf Жыл бұрын
you don't need to create additional TrieNode class, just initialize everything in TrieNode class into Trie class. and replace every cur = self.root by cur = self and it works fine i don't know why, this new solution was much faster, may be it was leetcode bug
@saisagarsharma
@saisagarsharma 2 жыл бұрын
Dude i have been postponing this DS for an year thinking its going to be very tuff. U just confirmed it to be wrong in first ten mnts. Great job man!
@noa.leshem
@noa.leshem Жыл бұрын
Super helpful videos. Been looking at them a lot.
@NeetCode
@NeetCode Жыл бұрын
Thank you so much 🙏
@rishiraj3521
@rishiraj3521 2 жыл бұрын
Always love the way you explain things so easily and concisely.
@changlingao4609
@changlingao4609 6 ай бұрын
thank you so much! such an awesome explanation of Trie you make everything so easy to understand thanks!!
@harishkandan7910
@harishkandan7910 3 жыл бұрын
Hey, what if we insert a substring of an already existing string. Say we insert 'app' when 'apple' already exists in the Trie. Wouldn't that make the second 'p' in the 'apple' also an 'endOfWord' making the 'le' in 'apple' inaccessible?
@kamaleshs5324
@kamaleshs5324 2 жыл бұрын
No harish, because you will only be checking for the endOfWord condition when you have reached the end of the particular word you are searching for, say you are searching for apple and both the second p and the e are marked as endOfWord, then when you are searching for apple, you iterate one by one, a, p, p, l, e and after reaching the end point, only then you check for the endOfWord Condition. In case you are searching for app, then you iterate through a, p, p and then check whether the currentNode has endOfWord as true, in this case yes, so both app and apple are accessible.
@DeGoya
@DeGoya 2 жыл бұрын
@@kamaleshs5324 that doesn't answer the question though, since he asked what will happen if "we insert a substring of an already existing string"
@torin755
@torin755 2 жыл бұрын
No, it will not be inaccessible, simply because if you look again at the search function you will see the for loop runs down the tree for the length of the searched word REGARDLESS of if it finds a node with EndOfWord. Only AFTER it has gone down the length of the word, will it check if the node it LANDS on is EndOfWord=True. I.e it will NOT stop just because it found an EndOfWord, but instead traverse the word's chars entirely and then check if the node it lands on is EndOfWord=True
@janeikeliu
@janeikeliu 2 жыл бұрын
Thank you! Your explanation of of the trie data structure is so clear!
@RobinHistoryMystery
@RobinHistoryMystery 8 ай бұрын
thanks! I thought Trie is gonna be super hard, nice explanation
@krutimody91
@krutimody91 Жыл бұрын
Omg this is amazing, I have been trying to understand this for an hour now - finally I get it! Thanks!
@killeraloo3247
@killeraloo3247 7 ай бұрын
Loved the easy to understand explanation. 🧡 from remote.
@sudharahul2010
@sudharahul2010 10 ай бұрын
Great practical explanation of Trie!!
@symbol767
@symbol767 2 жыл бұрын
My favorite data structure, I just came to make sure my code was as good as the one you show, and its exactly the same thankfully. Thanks for your videos Liked!
@yakeensabha655
@yakeensabha655 Жыл бұрын
what's the complexity of search, insert, delete the word in the trie? when it's implemented using a 26 array? I'm tryna guess it? the search and insert is O(L which is the length of the word)? the all space is 26 * the number of all nodes? plz I need to know
@smartsoothing776
@smartsoothing776 11 ай бұрын
If you could have explained all the data structures like this before, My life would have become easier..
@qR7pK9sJ2t
@qR7pK9sJ2t 10 ай бұрын
But did you come earlier to get his help is the question that I want to ask from you ?
@YunChiehChiu
@YunChiehChiu 2 жыл бұрын
Thank you so much. Your videos makes everyday learning a feasible plan. Your explanation makes every single problem lots more easier to understand and reduce my imagination to the difficulty of the problem.
@diplodocus3
@diplodocus3 10 ай бұрын
skimmed through 3-4 blah blah videos, this finished the job gracefully
@murtuza.chawala
@murtuza.chawala Жыл бұрын
The best Trie Explanation
@noctua7771
@noctua7771 2 жыл бұрын
After your explanation I was able to code it in under 2 mins without looking back at the video. You sir are an absolute legend.
@osamaayman3765
@osamaayman3765 Жыл бұрын
I had no other option but to like this implementation! Thanks Kevin :)
@shreshthkaushik-hu8bz
@shreshthkaushik-hu8bz 3 ай бұрын
I solve all these questions myself after looking at how neetcode solved it and then add more commenting, name styling to make it even more easier to read ( Hopefully atleast ) """ The way we can solve this question is by creating a data structure called "TrieNode" with two attributes -- children and end. children detonoes a map of maps where we would put each our letters and as we reach the end of the word, we mark that letter as ending using the "end" attribute """ # Create a class to store the letters in form of a tree class TrieNode: def __init__(self): self.children = {} self.end = False class Trie: def __init__(self): # Initialize the TrieNode instance self.root = TrieNode() def insert(self, word: str) -> None: # Set the current pointer to the root of the tree curr = self.root # Go through each letter in the word and add that into the tree if not already for letter in word: if letter not in curr.children: curr.children[letter] = TrieNode() curr = curr.children[letter] # Since by this time, we reach the end of the word so mark the letter as end curr.end = True def search(self, word: str) -> bool: # Set the current pointer to the root of the tree curr = self.root # Go through each letter and keep going down in the tree to find if this word has been # created for letter in word: if letter not in curr.children: return False curr = curr.children[letter] # If at the end we have the letter marked as end then yes it exists return curr.end def startsWith(self, prefix: str) -> bool: # Set the current pointer to the root of the tree curr = self.root # Go through each letter and keep going down in the tree to find if this word has been # created for letter in prefix: if letter not in curr.children: return False curr = curr.children[letter] # if we never returned false, means this is the prefix or the entire word return True
@mruduladdipalli5417
@mruduladdipalli5417 2 жыл бұрын
A Big Salute To You Bro, for the solutions and great explanation , I have recommended this channel to at least more than 3 people 🙌
@ambermichellemartinez
@ambermichellemartinez Жыл бұрын
Thank you, the best trie explanation! You're amazing!!!
@keremserttas5898
@keremserttas5898 Жыл бұрын
What is the worst case time compexity? Is it exponential? If it comes .........
@janvidalal476
@janvidalal476 Жыл бұрын
this guy is making our life play on easy mode
@yuenyiupang
@yuenyiupang 2 жыл бұрын
Very good explanation, but can someone tell me which way is more efficiency(if we dont care space) on above case, Trie, or a hashmap include all combination app become a = [app], ap = [app], app = [app], and 1 more hash for just store the word, as latter way can ensure search and startwith run O(1) time?
@sirmidor
@sirmidor 2 жыл бұрын
Yes, you can achieve average O(1) for searching and startsWith this way, though your insert will be slower. For a word of length m, I believe it'll be be O(m^2): you'll be adding m strings, obtaining those through list slicing, which is O(slice length). Average slice length is about half the length of the word in this case (for a word of length 4: 1st prefix is length 1, second is 2, third is 3, last is 4), so m * m * ~0.5, which is O(m^2). Doing it this way could be better if you inserted rarely, but searched and used startsWith a lot. You said not to care about space, but this is more space-efficient as well as a hashset is a built-in optimized data structure, while a TrieNode is an entire user-defined class instance.
@8nehe
@8nehe 2 жыл бұрын
Great simple explanation
@amitrastogi1405
@amitrastogi1405 Жыл бұрын
Very well explained. Thanks!
@MP-ny3ep
@MP-ny3ep 2 жыл бұрын
You are a godsend. Thank you sooooooo much for all your work 🙏🙏
@harrywang9375
@harrywang9375 2 жыл бұрын
It should be mentioned that marking Apple as the end of the word is not just to be safe. Your function would return false for not found if your word search was searching for both Apple and Apples if you didn't have that boolean to check if it was the end of the word. If Apples existed for example, then the E in Apple would no longer be the end of the chain. Despite that fact, Apple is a very legitimate word even though it has a child node in 'S'.
@mohammedfahadnyc1385
@mohammedfahadnyc1385 2 жыл бұрын
when you enter apple, it will mark e as the end of the word, then again when u enter apples, it will run for the length of apples, and add s after e. Then if u search, u will get True for both. Just because a node is marked end = True doesnt mean u cant access or add to that Node.
@vjnvisakh
@vjnvisakh 4 ай бұрын
simple and smooth
@elachichai
@elachichai 3 жыл бұрын
crisp and clear
@TejaDuggirala
@TejaDuggirala 2 жыл бұрын
You are literally making my life easy. Thanks man 🙏🏻
@illu1na
@illu1na Жыл бұрын
Do we have to use trieNode? I used dictionary and had "None" to mark if the node is at the end.
@vivitra1022
@vivitra1022 2 жыл бұрын
Thank you very much for the very clear explanation!!!
@davi_paula
@davi_paula 2 жыл бұрын
Amazing explanation, great job!
@vishalrao5202
@vishalrao5202 2 жыл бұрын
Beautifully explained 👏🏻👏🏻👏🏻
@Joseph-ub7rh
@Joseph-ub7rh 2 жыл бұрын
My assumption for runtime complexity is O(n) where n is the number of characters in the string that we are inserting or searching for. Now for space complexity, it seems to me that it is O(n^n) because each node can have n children.
@hillarioushollywood4267
@hillarioushollywood4267 2 жыл бұрын
not n nodes can have n children, you can say, 26 chars can have n children :) That Means, O(n+m+k+.........26th l)
@hamoodhabibi7026
@hamoodhabibi7026 Жыл бұрын
@@hillarioushollywood4267 So this is Space: O(n * 26) where n is the length of our word and each character in our word can have 26 children max
@princeanthony8525
@princeanthony8525 2 жыл бұрын
Can you code up the delete functionality as well ?
@MinhNguyen-lz1pg
@MinhNguyen-lz1pg 2 жыл бұрын
Awesome explanation my man!
@ameynaik1755
@ameynaik1755 3 жыл бұрын
Neat video! Please do a video on Design Search Autocomplete System.
@shravancheekati9045
@shravancheekati9045 Жыл бұрын
Why create an additional TrieNode class? Why not just put them in Trie?
@wallaby28
@wallaby28 3 жыл бұрын
Brilliant explanation
@phantomsedge5686
@phantomsedge5686 Жыл бұрын
This is a slow method. Is there a faster way?
@farshadsaberi2740
@farshadsaberi2740 3 жыл бұрын
Thank you very much for clear explanation and truly neat code :)
@bhabishyachaudhary3495
@bhabishyachaudhary3495 11 ай бұрын
really helpful thank you so much.
@madanmohanpachouly6135
@madanmohanpachouly6135 2 жыл бұрын
Real cool explanation, Thanks Man.
@codeUrDreams
@codeUrDreams 2 жыл бұрын
Brilliant! Thank you so much!
@carloslazarin
@carloslazarin 2 жыл бұрын
Excellent explanation!! thank you a lot!
@travellercoder7298
@travellercoder7298 3 жыл бұрын
Sir i have a doubt that in apple it's two p's and since we inserted the first so will it insert the second one?? Plzz explain
@atharhussain6534
@atharhussain6534 Жыл бұрын
Data structure look like for letter apple : {"a":{"p":{"p":{"l":{"e:{}}}}}
@veedhiabhhirram4121
@veedhiabhhirram4121 3 ай бұрын
best video out there
@introvertwhiz-ll2ip
@introvertwhiz-ll2ip 5 ай бұрын
Ok I am a full stack developer currently grinding on leetcode. I just don't understand why you don't share code on github. If you have shared then provide the link. Thank you so much for you explanation.
@oliver1231033
@oliver1231033 2 жыл бұрын
what if we insert a word "super" and then a word "superman", is that gonna cause any problem when we are searching?
@mohammedfahadnyc1385
@mohammedfahadnyc1385 2 жыл бұрын
No. For super, search function will run the loop for len(super), and at r, it will see its marked end of word, so it will return True. For superman, it will run len(superman), so when it comes to r, it will just check if r exists, then move to move to a and move to n, when it reaches n, it will check if endofword is true, and return True. So it wont be an issue, the whole idea is we traverse by the length of the word, so no issue will arise
@LongVu-sm8wm
@LongVu-sm8wm 2 жыл бұрын
a great explanation !. Thanks
@wajahatali6403
@wajahatali6403 2 жыл бұрын
Excellent video, as always.
@aspiretechie1191
@aspiretechie1191 Ай бұрын
You are a GOAT Man..........
@MichaelShingo
@MichaelShingo Жыл бұрын
yess!! tries are cool
@Michalr1223
@Michalr1223 3 жыл бұрын
Great explanation! thank you :)
@jasonahern3498
@jasonahern3498 3 жыл бұрын
Thank you! Great video
@KrzysztofKoziarski
@KrzysztofKoziarski 2 жыл бұрын
Thanks
@dorondavid4698
@dorondavid4698 3 жыл бұрын
Nice explanation!
@AnnieBox
@AnnieBox 2 жыл бұрын
what's the time cost of the solution? Is it 26*len(word)?
@NeetCode
@NeetCode 2 жыл бұрын
Yeah that's correct!
@ashs3979
@ashs3979 3 жыл бұрын
You’re awesome dude ty
@deformedzebraonbike
@deformedzebraonbike 2 жыл бұрын
I have big interview tomorrow. Your videos have helped me a lot, fingers crossed!
@itachid
@itachid 2 жыл бұрын
How did it go?
@ruzaikr
@ruzaikr 9 ай бұрын
Thanks!
@XxM1G3xX
@XxM1G3xX 9 ай бұрын
Wouldn't it be better to just add another empty value node at the end of a word to designate the ending? instead of adding another variable to every single node? You would just check if after the 'e' for apple there is an empty node vs i.e. an 's' node for apples, this way you would know if apple vs apples exist. I mean for consistency this would make more sense since you are adding an empty node for the 'root' instead of adding another variable for 'stringStart'. Edit: I saw your solution of adding a hashmap for value and node, instead of having two separte char and object for each node. This would complicate things with what I said because you cannot use an empty key in a hashmap IIRC.
@servantofthelord8147
@servantofthelord8147 2 ай бұрын
Excellent.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 687 М.
The Trie Data Structure (Prefix Tree)
21:07
Jacob Sorber
Рет қаралды 82 М.
Object-Oriented Programming is Embarrassing: 4 Short Examples
28:03
Brian Will
Рет қаралды 2,1 МЛН
Coding Interview | Software Engineer @ Bloomberg (Part 1)
30:05
Keep On Coding
Рет қаралды 4,7 МЛН
L1. Implement TRIE | INSERT | SEARCH | STARTSWITH
31:25
take U forward
Рет қаралды 325 М.
What Is A Trie and How Do We Build One In Python?
18:24
Nathan Patnam
Рет қаралды 16 М.
Implement Trie (Prefix Tree) - Leetcode 208 - Trees (Python)
9:30
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 245 М.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 576 М.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 442 М.