Implement Trie (Prefix Tree) - Leetcode 208

Sdílet
Vložit
  • čas přidán 9. 07. 2024
  • 🚀 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.
  • Věda a technologie

Komentáře • 159

  • @NeetCode
    @NeetCode  Před 3 lety +32

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤

  • @evalyly9313
    @evalyly9313 Před 2 lety +168

    This is the best Trie introduction video I watched in youtube, very clear and concise. Bravo!

  • @sanjanar9198
    @sanjanar9198 Před 2 lety +63

    Never thought Trie would be this easy to understand, thanks a lott!!

  • @sucraloss
    @sucraloss Před 10 měsíci +15

    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 Před 2 lety +19

    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 Před 2 lety +13

    I avoided trie for so long thinking it will be difficult to understand. Thanks for this. This was very easy.

  • @reddev9143
    @reddev9143 Před 3 lety +8

    Thank you so much! Just can’t tell how cool and valuable your videos are! Keep’em coming!

  • @kritmok1875
    @kritmok1875 Před rokem +2

    never thought that I would get the best trie introduction video in a leetcode video. Thanks for the great work!

  • @aaab45357
    @aaab45357 Před 2 měsíci +1

    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

  • @sravanikatasani6502
    @sravanikatasani6502 Před 3 lety +31

    Thank you so much!! I have learnt a new data structure today..

  • @Xavierrex3
    @Xavierrex3 Před 7 měsíci +1

    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

  • @rishiraj3521
    @rishiraj3521 Před rokem

    Always love the way you explain things so easily and concisely.

  • @saumyatyagi8768
    @saumyatyagi8768 Před rokem +1

    This is the best Trie vid so far ! Excellent explaination . 👍

  • @seanjcan
    @seanjcan Před rokem

    Best explanation of Tries I have come across so far. Bravo!

  • @TejaDuggirala
    @TejaDuggirala Před 2 lety

    You are literally making my life easy. Thanks man 🙏🏻

  • @krutimody91
    @krutimody91 Před rokem

    Omg this is amazing, I have been trying to understand this for an hour now - finally I get it! Thanks!

  • @rkkasotiya
    @rkkasotiya Před 11 měsíci

    Simplest video to understand Trie and implement it. Keep up the good work.

  • @vashishtgupta7416
    @vashishtgupta7416 Před 2 lety +6

    I haven't seen better tutorials than yours for LC problems anywhere! Great work :)

  • @janeikeliu
    @janeikeliu Před rokem

    Thank you! Your explanation of of the trie data structure is so clear!

  • @WalterGordyCanada
    @WalterGordyCanada Před 10 měsíci +1

    These videos are literally better than the courses I took in University. Thank you!

  • @nhuphan7112
    @nhuphan7112 Před 2 lety +2

    honestly just want to say your videos been great in my interview prep :) (totoal newbie at leetcode)

  • @farshadsaberi2740
    @farshadsaberi2740 Před 2 lety +1

    Thank you very much for clear explanation and truly neat code :)

  • @lymmontijo87
    @lymmontijo87 Před 3 měsíci

    Thank you!! I had never seen tries and had been avoiding it. Its actually quite easy.

  • @1-ov947
    @1-ov947 Před 10 měsíci +1

    You are the best leetcode teacher on entire CZcams!

  • @MP-ny3ep
    @MP-ny3ep Před rokem

    You are a godsend. Thank you sooooooo much for all your work 🙏🙏

  • @mruduladdipalli5417
    @mruduladdipalli5417 Před rokem

    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!!!

  • @osamaayman3765
    @osamaayman3765 Před rokem

    I had no other option but to like this implementation! Thanks Kevin :)

  • @davi_paula
    @davi_paula Před rokem

    Amazing explanation, great job!

  • @changlingao4609
    @changlingao4609 Před měsícem

    thank you so much! such an awesome explanation of Trie you make everything so easy to understand thanks!!

  • @YunChiehChiu
    @YunChiehChiu Před rokem

    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.

  • @vivitra1022
    @vivitra1022 Před 2 lety

    Thank you very much for the very clear explanation!!!

  • @wajahatali6403
    @wajahatali6403 Před 2 lety

    Excellent video, as always.

  • @Michalr1223
    @Michalr1223 Před 2 lety +1

    Great explanation! thank you :)

  • @iugaialeksei2108
    @iugaialeksei2108 Před 8 měsíci

    OMG, man, you possess a special talent to explain complicated things smoothly and simple. I'm a big fan of your channel!

  • @amitrastogi1405
    @amitrastogi1405 Před 8 měsíci

    Very well explained. Thanks!

  • @emmatime2016
    @emmatime2016 Před 2 lety

    You are always the best!

  • @carloslazarin
    @carloslazarin Před rokem

    Excellent explanation!! thank you a lot!

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg Před 2 lety +1

    Awesome explanation my man!

  • @Dhruvbala
    @Dhruvbala Před měsícem +1

    This was one of the more enjoyable problems I've done

  • @noa.leshem
    @noa.leshem Před rokem +2

    Super helpful videos. Been looking at them a lot.

  • @vishalrao5202
    @vishalrao5202 Před 2 lety

    Beautifully explained 👏🏻👏🏻👏🏻

  • @tjsm4455
    @tjsm4455 Před 8 měsíci

    Good explanation. After understanding the logic I implemented the code myself. Feels good.

  • @codeUrDreams
    @codeUrDreams Před rokem

    Brilliant! Thank you so much!

  • @unanimous8510
    @unanimous8510 Před 9 měsíci

    What an amazing explanation for the guy who just started learning tries 👍

  • @elias043011
    @elias043011 Před měsícem

    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"

  • @BobbyMully
    @BobbyMully Před 2 lety +1

    When I did this one before wathcing the video, my code was double the length of yours. Nice solve!

  • @madanmohanpachouly6135

    Real cool explanation, Thanks Man.

  • @sudharahul2010
    @sudharahul2010 Před 5 měsíci

    Great practical explanation of Trie!!

  • @jasonahern3498
    @jasonahern3498 Před 2 lety

    Thank you! Great video

  • @saisagarsharma
    @saisagarsharma Před 2 lety

    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!

  • @LongVu-sm8wm
    @LongVu-sm8wm Před 2 lety

    a great explanation !. Thanks

  • @Manu-et6zk
    @Manu-et6zk Před 3 lety +25

    please explain time and space complexity after u solve the problem

    • @juliacheng4751
      @juliacheng4751 Před 2 lety +23

      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)

  • @nou4605
    @nou4605 Před 4 měsíci

    The code is marvelously simple considering how useful of a data structure this can be.

  • @killeraloo3247
    @killeraloo3247 Před 3 měsíci

    Loved the easy to understand explanation. 🧡 from remote.

  • @ashs3979
    @ashs3979 Před 2 lety

    You’re awesome dude ty

  • @wallaby28
    @wallaby28 Před 3 lety

    Brilliant explanation

  • @umairbijapure7584
    @umairbijapure7584 Před 2 lety

    Amazing explanation

  • @bhabishyachaudhary3495
    @bhabishyachaudhary3495 Před 6 měsíci

    really helpful thank you so much.

  • @8nehe
    @8nehe Před 2 lety

    Great simple explanation

  • @RobinHistoryMystery
    @RobinHistoryMystery Před 3 měsíci

    thanks! I thought Trie is gonna be super hard, nice explanation

  • @hmanjun7260
    @hmanjun7260 Před rokem

    Using a hash map was genius. Once I saw that, I went and redid my code before looking at the rest of ur solution

  • @dorondavid4698
    @dorondavid4698 Před 2 lety

    Nice explanation!

  • @barcannon
    @barcannon Před 2 lety

    Great explanation

  • @DeepakKumar-wu4dt
    @DeepakKumar-wu4dt Před 2 lety

    Thanks Man!

  • @elachichai
    @elachichai Před 2 lety

    crisp and clear

  • @tarushgupta6616
    @tarushgupta6616 Před 9 měsíci

    Excellent explanation

  • @ameynaik1755
    @ameynaik1755 Před 3 lety +1

    Neat video! Please do a video on Design Search Autocomplete System.

  • @antonyndungu5514
    @antonyndungu5514 Před 2 lety +4

    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 Před 2 lety

      dude he is in google !..
      someone truly said.
      Time is mightier than fate..

    • @antonyndungu5514
      @antonyndungu5514 Před 2 lety

      @@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 Před 2 lety +1

      @@antonyndungu5514 yeah dude.. hope some day we will have our luck too 😂

    • @antonyndungu5514
      @antonyndungu5514 Před 2 lety +1

      @@TechOnScreen True, can't wait for that :-)

  • @ruzaikr
    @ruzaikr Před 4 měsíci

    Thanks!

  • @hoyinli7462
    @hoyinli7462 Před 2 lety

    great video!

  • @diplodocus3
    @diplodocus3 Před 5 měsíci

    skimmed through 3-4 blah blah videos, this finished the job gracefully

  • @lingyundai964
    @lingyundai964 Před 11 měsíci

    brilliant!

  • @AngelH2m
    @AngelH2m Před 3 lety

    Awesome!

  • @murtuza.chawala
    @murtuza.chawala Před 10 měsíci

    The best Trie Explanation

  • @smartsoothing776
    @smartsoothing776 Před 6 měsíci +1

    If you could have explained all the data structures like this before, My life would have become easier..

    • @qR7pK9sJ2t
      @qR7pK9sJ2t Před 5 měsíci

      But did you come earlier to get his help is the question that I want to ask from you ?

  • @arnabpersonal6729
    @arnabpersonal6729 Před 2 lety

    neatly implemented

  • @deniyii
    @deniyii Před 10 měsíci

    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.

  • @MichaelShingo
    @MichaelShingo Před rokem

    yess!! tries are cool

  • @sundararajannarasiman5613

    Very helpful

  • @ariansergi7929
    @ariansergi7929 Před 2 lety

    good job

  • @symbol767
    @symbol767 Před 2 lety +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!

  • @princeanthony8525
    @princeanthony8525 Před rokem

    Can you code up the delete functionality as well ?

  • @hwang1607
    @hwang1607 Před 6 měsíci

    helpful video

  • @noctua7771
    @noctua7771 Před rokem +1

    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.

  • @KrzysztofKoziarski
    @KrzysztofKoziarski Před rokem

    Thanks

  • @harrywang9375
    @harrywang9375 Před 2 lety +1

    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 Před rokem +1

      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.

  • @janvidalal476
    @janvidalal476 Před rokem

    this guy is making our life play on easy mode

  • @4498rx
    @4498rx Před 2 lety

    you are the best

  • @raghavendharreddydarpally2125

    Keep doing more videos

  • @Lmcrf
    @Lmcrf Před 11 měsíci

    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

  • @harishkandan7910
    @harishkandan7910 Před 2 lety +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 Před 2 lety +4

      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 Před 2 lety

      @@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 Před 2 lety +1

      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

  • @illu1na
    @illu1na Před 8 měsíci

    Do we have to use trieNode? I used dictionary and had "None" to mark if the node is at the end.

  • @b9944236
    @b9944236 Před rokem

    Perfect

  • @travellercoder7298
    @travellercoder7298 Před 2 lety +1

    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 Před rokem

      Data structure look like for letter apple :
      {"a":{"p":{"p":{"l":{"e:{}}}}}

  • @edwardteach2
    @edwardteach2 Před 2 lety

    U a God

  • @Joseph-ub7rh
    @Joseph-ub7rh Před 2 lety

    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 Před rokem

      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 Před rokem

      @@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

  • @shadowsw8020
    @shadowsw8020 Před měsícem

    I like this one

  • @yuenyiupang
    @yuenyiupang Před 2 lety +1

    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 Před rokem

      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.

  • @osoyoki
    @osoyoki Před 2 lety

    I love you bro