Тёмный

Implement Trie (Prefix Tree) - Leetcode 208 

NeetCode
Подписаться 767 тыс.
Просмотров 184 тыс.
50% 1

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Twitter: / neetcode1
Discord: / discord
Coding Solutions: • Coding Interview Solut...
Dynamic Programming Playlist: • House Robber - Leetco...
Tree Playlist: • Invert Binary Tree - D...
Linked List Playlist: • Reverse Linked List - ...
Problem Link: neetcode.io/problems/implemen...
0:00 - Read the problem
1:53 - Drawing Explanation
11:40 - Coding Explanation
leetcode 208
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#trie #prefix #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Наука

Опубликовано:

 

27 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 162   
@NeetCode
@NeetCode 3 года назад
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@evalyly9313
@evalyly9313 2 года назад
This is the best Trie introduction video I watched in youtube, very clear and concise. Bravo!
@sanjanar9198
@sanjanar9198 2 года назад
Never thought Trie would be this easy to understand, thanks a lott!!
@aaab45357
@aaab45357 3 месяца назад
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
@sucraloss
@sucraloss 10 месяцев назад
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.
@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!
@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 6 месяцев назад
I am with you on this, hahaha
@reddev9143
@reddev9143 3 года назад
Thank you so much! Just can’t tell how cool and valuable your videos are! Keep’em coming!
@sravanikatasani6502
@sravanikatasani6502 3 года назад
Thank you so much!! I have learnt a new data structure today..
@kritmok1875
@kritmok1875 Год назад
never thought that I would get the best trie introduction video in a leetcode video. Thanks for the great work!
@Xavierrex3
@Xavierrex3 7 месяцев назад
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
@saumyatyagi8768
@saumyatyagi8768 Год назад
This is the best Trie vid so far ! Excellent explaination . 👍
@rishiraj3521
@rishiraj3521 Год назад
Always love the way you explain things so easily and concisely.
@seanjcan
@seanjcan Год назад
Best explanation of Tries I have come across so far. Bravo!
@nhuphan7112
@nhuphan7112 2 года назад
honestly just want to say your videos been great in my interview prep :) (totoal newbie at leetcode)
@janeikeliu
@janeikeliu Год назад
Thank you! Your explanation of of the trie data structure is so clear!
@krutimody91
@krutimody91 Год назад
Omg this is amazing, I have been trying to understand this for an hour now - finally I get it! Thanks!
@vashishtgupta7416
@vashishtgupta7416 2 года назад
I haven't seen better tutorials than yours for LC problems anywhere! Great work :)
@WalterGordyCanada
@WalterGordyCanada 10 месяцев назад
These videos are literally better than the courses I took in University. Thank you!
@rkkasotiya
@rkkasotiya Год назад
Simplest video to understand Trie and implement it. Keep up the good work.
@farshadsaberi2740
@farshadsaberi2740 2 года назад
Thank you very much for clear explanation and truly neat code :)
@mruduladdipalli5417
@mruduladdipalli5417 Год назад
A Big Salute To You Bro, for the solutions and great explanation , I have recommended this channel to at least more than 3 people 🙌
@TejaDuggirala
@TejaDuggirala 2 года назад
You are literally making my life easy. Thanks man 🙏🏻
@1-ov947
@1-ov947 10 месяцев назад
You are the best leetcode teacher on entire RU-vid!
@YunChiehChiu
@YunChiehChiu Год назад
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.
@lymmontijo87
@lymmontijo87 4 месяца назад
Thank you!! I had never seen tries and had been avoiding it. Its actually quite easy.
@osamaayman3765
@osamaayman3765 Год назад
I had no other option but to like this implementation! Thanks Kevin :)
@MP-ny3ep
@MP-ny3ep Год назад
You are a godsend. Thank you sooooooo much for all your work 🙏🙏
@iugaialeksei2108
@iugaialeksei2108 8 месяцев назад
OMG, man, you possess a special talent to explain complicated things smoothly and simple. I'm a big fan of your channel!
@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!
@davi_paula
@davi_paula Год назад
Amazing explanation, great job!
@Michalr1223
@Michalr1223 2 года назад
Great explanation! thank you :)
@ambermichellemartinez
@ambermichellemartinez Год назад
Thank you, the best trie explanation! You're amazing!!!
@vivitra1022
@vivitra1022 2 года назад
Thank you very much for the very clear explanation!!!
@wajahatali6403
@wajahatali6403 2 года назад
Excellent video, as always.
@BobbyMully
@BobbyMully 2 года назад
When I did this one before wathcing the video, my code was double the length of yours. Nice solve!
@changlingao4609
@changlingao4609 2 месяца назад
thank you so much! such an awesome explanation of Trie you make everything so easy to understand thanks!!
@MinhNguyen-lz1pg
@MinhNguyen-lz1pg 2 года назад
Awesome explanation my man!
@noa.leshem
@noa.leshem Год назад
Super helpful videos. Been looking at them a lot.
@NeetCode
@NeetCode Год назад
Thank you so much 🙏
@carloslazarin
@carloslazarin Год назад
Excellent explanation!! thank you a lot!
@vishalrao5202
@vishalrao5202 2 года назад
Beautifully explained 👏🏻👏🏻👏🏻
@tjsm4455
@tjsm4455 8 месяцев назад
Good explanation. After understanding the logic I implemented the code myself. Feels good.
@unanimous8510
@unanimous8510 10 месяцев назад
What an amazing explanation for the guy who just started learning tries 👍
@amitrastogi1405
@amitrastogi1405 8 месяцев назад
Very well explained. Thanks!
@emmatime2016
@emmatime2016 2 года назад
You are always the best!
@madanmohanpachouly6135
@madanmohanpachouly6135 2 года назад
Real cool explanation, Thanks Man.
@jasonahern3498
@jasonahern3498 2 года назад
Thank you! Great video
@codeUrDreams
@codeUrDreams Год назад
Brilliant! Thank you so much!
@bugracansefercik917
@bugracansefercik917 11 дней назад
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
@tapasheetabassumurmi1895
@tapasheetabassumurmi1895 15 дней назад
I am getting addicted to this channel!! Thanks God!! You've sent this man for us!
@LongVu-sm8wm
@LongVu-sm8wm 2 года назад
a great explanation !. Thanks
@ameynaik1755
@ameynaik1755 3 года назад
Neat video! Please do a video on Design Search Autocomplete System.
@sudharahul2010
@sudharahul2010 6 месяцев назад
Great practical explanation of Trie!!
@Manu-et6zk
@Manu-et6zk 3 года назад
please explain time and space complexity after u solve the problem
@juliacheng4751
@juliacheng4751 2 года назад
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)
@umairbijapure7584
@umairbijapure7584 3 года назад
Amazing explanation
@wallaby28
@wallaby28 3 года назад
Brilliant explanation
@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
@antonyndungu5514
@antonyndungu5514 2 года назад
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 :-)
@elias043011
@elias043011 2 месяца назад
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"
@killeraloo3247
@killeraloo3247 4 месяца назад
Loved the easy to understand explanation. 🧡 from remote.
@ashs3979
@ashs3979 2 года назад
You’re awesome dude ty
@8nehe
@8nehe 2 года назад
Great simple explanation
@dorondavid4698
@dorondavid4698 2 года назад
Nice explanation!
@RobinHistoryMystery
@RobinHistoryMystery 4 месяца назад
thanks! I thought Trie is gonna be super hard, nice explanation
@bhabishyachaudhary3495
@bhabishyachaudhary3495 7 месяцев назад
really helpful thank you so much.
@barcannon
@barcannon 2 года назад
Great explanation
@tarushgupta6616
@tarushgupta6616 9 месяцев назад
Excellent explanation
@princeanthony8525
@princeanthony8525 Год назад
Can you code up the delete functionality as well ?
@deniyii
@deniyii 10 месяцев назад
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.
@Dhruvbala
@Dhruvbala Месяц назад
This was one of the more enjoyable problems I've done
@elachichai
@elachichai 2 года назад
crisp and clear
@murtuza.chawala
@murtuza.chawala 11 месяцев назад
The best Trie Explanation
@hoyinli7462
@hoyinli7462 2 года назад
great video!
@nou4605
@nou4605 5 месяцев назад
The code is marvelously simple considering how useful of a data structure this can be.
@DeepakKumar-wu4dt
@DeepakKumar-wu4dt 2 года назад
Thanks Man!
@harishkandan7910
@harishkandan7910 2 года назад
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
@ruzaikr
@ruzaikr 5 месяцев назад
Thanks!
@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!
@illu1na
@illu1na 9 месяцев назад
Do we have to use trieNode? I used dictionary and had "None" to mark if the node is at the end.
@arnabpersonal6729
@arnabpersonal6729 2 года назад
neatly implemented
@noctua7771
@noctua7771 Год назад
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.
@janvidalal476
@janvidalal476 Год назад
this guy is making our life play on easy mode
@vjnvisakh
@vjnvisakh 9 дней назад
simple and smooth
@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 Год назад
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.
@lingyundai964
@lingyundai964 Год назад
brilliant!
@travellercoder7298
@travellercoder7298 2 года назад
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:{}}}}}
@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
@ariansergi7929
@ariansergi7929 2 года назад
good job
@AngelH2m
@AngelH2m 3 года назад
Awesome!
@diplodocus3
@diplodocus3 6 месяцев назад
skimmed through 3-4 blah blah videos, this finished the job gracefully
@sundararajannarasiman5613
@sundararajannarasiman5613 2 года назад
Very helpful
@rifathasan6017
@rifathasan6017 2 года назад
Is it possible to write the code without the TrieNode class? Can we do it in one class like a normal tree?
@meowmaple
@meowmaple 2 года назад
Doubt you will be able to do it without the code getting much more messier
@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 Год назад
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.
@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
@raghavendharreddydarpally2125
@raghavendharreddydarpally2125 3 года назад
Keep doing more videos
@nokigaming6651
@nokigaming6651 2 года назад
i need a printwords method implemented .please help
@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
@KrzysztofKoziarski
@KrzysztofKoziarski Год назад
Thanks
@AnnieBox
@AnnieBox 2 года назад
what's the time cost of the solution? Is it 26*len(word)?
@NeetCode
@NeetCode 2 года назад
Yeah that's correct!
@hwang1607
@hwang1607 7 месяцев назад
helpful video
Далее
Trie Data Structure Implementation (LeetCode)
11:50
Просмотров 70 тыс.
How I would learn Leetcode if I could start over
18:03
Просмотров 374 тыс.
Я КУПИЛ САМЫЙ МОЩНЫЙ МОТОЦИКЛ!
59:15
Угадай МОБА 1 🥵 | WICSUR #shorts
01:00
Просмотров 1,7 млн
STOP Using Classes In JavaScript | Prime Reacts
14:02
Просмотров 228 тыс.
The Algorithm Behind Spell Checkers
13:02
Просмотров 409 тыс.
8 patterns to solve 80% Leetcode problems
7:30
Просмотров 271 тыс.
5 Useful F-String Tricks In Python
10:02
Просмотров 284 тыс.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Просмотров 146 тыс.
The Trie Data Structure (Prefix Tree)
21:07
Просмотров 74 тыс.
How to Soldering wire in Factory ?
0:10
Просмотров 4,8 млн
MSI сделали свой Steam Deck
12:54
Просмотров 40 тыс.