🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@evalyly93133 жыл бұрын
This is the best Trie introduction video I watched in youtube, very clear and concise. Bravo!
@ARkhan-xw8ud3 ай бұрын
watch striver series
@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.
@sanjanar91982 жыл бұрын
Never thought Trie would be this easy to understand, thanks a lott!!
@sprajosh2 жыл бұрын
I avoided trie for so long thinking it will be difficult to understand. Thanks for this. This was very easy.
@niravarora988710 ай бұрын
I am with you on this, hahaha
@z78472 жыл бұрын
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Ай бұрын
I am usually struggling with new data structures, but you made it simple and smooth. Tanks for the great video.
@sravanikatasani65023 жыл бұрын
Thank you so much!! I have learnt a new data structure today..
@aaab453576 ай бұрын
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
@GinsuGames2 ай бұрын
I think the class approach is much cleaner to read
@KokurorokukoАй бұрын
@@GinsuGames yeah, and it works for any kinds of strings
@elias0430116 ай бұрын
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"
@bugracansefercik9174 ай бұрын
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 Жыл бұрын
never thought that I would get the best trie introduction video in a leetcode video. Thanks for the great work!
@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
@Xavierrex311 ай бұрын
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
@tapasheetabassumurmi18954 ай бұрын
I am getting addicted to this channel!! Thanks God!! You've sent this man for us!
@WalterGordyCanada Жыл бұрын
These videos are literally better than the courses I took in University. Thank you!
@nou46059 ай бұрын
The code is marvelously simple considering how useful of a data structure this can be.
@1-ov947 Жыл бұрын
You are the best leetcode teacher on entire KZbin!
@iugaialeksei2108 Жыл бұрын
OMG, man, you possess a special talent to explain complicated things smoothly and simple. I'm a big fan of your channel!
@rkkasotiya Жыл бұрын
Simplest video to understand Trie and implement it. Keep up the good work.
@BobbyMully2 жыл бұрын
When I did this one before wathcing the video, my code was double the length of yours. Nice solve!
@tjsm4455 Жыл бұрын
Good explanation. After understanding the logic I implemented the code myself. Feels good.
@seanjcan Жыл бұрын
Best explanation of Tries I have come across so far. Bravo!
@lymmontijo878 ай бұрын
Thank you!! I had never seen tries and had been avoiding it. Its actually quite easy.
@Dhruvbala5 ай бұрын
This was one of the more enjoyable problems I've done
@nhuphan71122 жыл бұрын
honestly just want to say your videos been great in my interview prep :) (totoal newbie at leetcode)
@Manu-et6zk3 жыл бұрын
please explain time and space complexity after u solve the problem
@juliacheng47513 жыл бұрын
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Ай бұрын
@@juliacheng4751 I think you're incorrect. Time complexity is O(m) for insertion. Space complexity is O(m).
@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.
@vashishtgupta74162 жыл бұрын
I haven't seen better tutorials than yours for LC problems anywhere! Great work :)
@reddev91433 жыл бұрын
Thank you so much! Just can’t tell how cool and valuable your videos are! Keep’em coming!
@unanimous8510 Жыл бұрын
What an amazing explanation for the guy who just started learning tries 👍
@antonyndungu55143 жыл бұрын
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
@TechOnScreen2 жыл бұрын
dude he is in google !.. someone truly said. Time is mightier than fate..
@antonyndungu55142 жыл бұрын
@@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
@TechOnScreen2 жыл бұрын
@@antonyndungu5514 yeah dude.. hope some day we will have our luck too 😂
@antonyndungu55142 жыл бұрын
@@TechOnScreen True, can't wait for that :-)
@Z00keeper5410 күн бұрын
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.
@saumyatyagi87682 жыл бұрын
This is the best Trie vid so far ! Excellent explaination . 👍
@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
@saisagarsharma2 жыл бұрын
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 Жыл бұрын
Super helpful videos. Been looking at them a lot.
@NeetCode Жыл бұрын
Thank you so much 🙏
@rishiraj35212 жыл бұрын
Always love the way you explain things so easily and concisely.
@changlingao46096 ай бұрын
thank you so much! such an awesome explanation of Trie you make everything so easy to understand thanks!!
@harishkandan79103 жыл бұрын
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?
@kamaleshs53242 жыл бұрын
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.
@DeGoya2 жыл бұрын
@@kamaleshs5324 that doesn't answer the question though, since he asked what will happen if "we insert a substring of an already existing string"
@torin7552 жыл бұрын
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
@janeikeliu2 жыл бұрын
Thank you! Your explanation of of the trie data structure is so clear!
@RobinHistoryMystery8 ай бұрын
thanks! I thought Trie is gonna be super hard, nice explanation
@krutimody91 Жыл бұрын
Omg this is amazing, I have been trying to understand this for an hour now - finally I get it! Thanks!
@killeraloo32477 ай бұрын
Loved the easy to understand explanation. 🧡 from remote.
@sudharahul201010 ай бұрын
Great practical explanation of Trie!!
@symbol7672 жыл бұрын
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 Жыл бұрын
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
@smartsoothing77611 ай бұрын
If you could have explained all the data structures like this before, My life would have become easier..
@qR7pK9sJ2t10 ай бұрын
But did you come earlier to get his help is the question that I want to ask from you ?
@YunChiehChiu2 жыл бұрын
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.
@diplodocus310 ай бұрын
skimmed through 3-4 blah blah videos, this finished the job gracefully
@murtuza.chawala Жыл бұрын
The best Trie Explanation
@noctua77712 жыл бұрын
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 Жыл бұрын
I had no other option but to like this implementation! Thanks Kevin :)
@shreshthkaushik-hu8bz3 ай бұрын
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
@mruduladdipalli54172 жыл бұрын
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 Жыл бұрын
Thank you, the best trie explanation! You're amazing!!!
@keremserttas5898 Жыл бұрын
What is the worst case time compexity? Is it exponential? If it comes .........
@janvidalal476 Жыл бұрын
this guy is making our life play on easy mode
@yuenyiupang2 жыл бұрын
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?
@sirmidor2 жыл бұрын
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.
@8nehe2 жыл бұрын
Great simple explanation
@amitrastogi1405 Жыл бұрын
Very well explained. Thanks!
@MP-ny3ep2 жыл бұрын
You are a godsend. Thank you sooooooo much for all your work 🙏🙏
@harrywang93752 жыл бұрын
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'.
@mohammedfahadnyc13852 жыл бұрын
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.
@vjnvisakh4 ай бұрын
simple and smooth
@elachichai3 жыл бұрын
crisp and clear
@TejaDuggirala2 жыл бұрын
You are literally making my life easy. Thanks man 🙏🏻
@illu1na Жыл бұрын
Do we have to use trieNode? I used dictionary and had "None" to mark if the node is at the end.
@vivitra10222 жыл бұрын
Thank you very much for the very clear explanation!!!
@davi_paula2 жыл бұрын
Amazing explanation, great job!
@vishalrao52022 жыл бұрын
Beautifully explained 👏🏻👏🏻👏🏻
@Joseph-ub7rh2 жыл бұрын
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.
@hillarioushollywood42672 жыл бұрын
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 Жыл бұрын
@@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
@princeanthony85252 жыл бұрын
Can you code up the delete functionality as well ?
@MinhNguyen-lz1pg2 жыл бұрын
Awesome explanation my man!
@ameynaik17553 жыл бұрын
Neat video! Please do a video on Design Search Autocomplete System.
@shravancheekati9045 Жыл бұрын
Why create an additional TrieNode class? Why not just put them in Trie?
@wallaby283 жыл бұрын
Brilliant explanation
@phantomsedge5686 Жыл бұрын
This is a slow method. Is there a faster way?
@farshadsaberi27403 жыл бұрын
Thank you very much for clear explanation and truly neat code :)
@bhabishyachaudhary349511 ай бұрын
really helpful thank you so much.
@madanmohanpachouly61352 жыл бұрын
Real cool explanation, Thanks Man.
@codeUrDreams2 жыл бұрын
Brilliant! Thank you so much!
@carloslazarin2 жыл бұрын
Excellent explanation!! thank you a lot!
@travellercoder72983 жыл бұрын
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 Жыл бұрын
Data structure look like for letter apple : {"a":{"p":{"p":{"l":{"e:{}}}}}
@veedhiabhhirram41213 ай бұрын
best video out there
@introvertwhiz-ll2ip5 ай бұрын
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.
@oliver12310332 жыл бұрын
what if we insert a word "super" and then a word "superman", is that gonna cause any problem when we are searching?
@mohammedfahadnyc13852 жыл бұрын
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-sm8wm2 жыл бұрын
a great explanation !. Thanks
@wajahatali64032 жыл бұрын
Excellent video, as always.
@aspiretechie1191Ай бұрын
You are a GOAT Man..........
@MichaelShingo Жыл бұрын
yess!! tries are cool
@Michalr12233 жыл бұрын
Great explanation! thank you :)
@jasonahern34983 жыл бұрын
Thank you! Great video
@KrzysztofKoziarski2 жыл бұрын
Thanks
@dorondavid46983 жыл бұрын
Nice explanation!
@AnnieBox2 жыл бұрын
what's the time cost of the solution? Is it 26*len(word)?
@NeetCode2 жыл бұрын
Yeah that's correct!
@ashs39793 жыл бұрын
You’re awesome dude ty
@deformedzebraonbike2 жыл бұрын
I have big interview tomorrow. Your videos have helped me a lot, fingers crossed!
@itachid2 жыл бұрын
How did it go?
@ruzaikr9 ай бұрын
Thanks!
@XxM1G3xX9 ай бұрын
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.