L3. Longest Word With All Prefixes | Complete String | Trie

Поділитися
Вставка
  • Опубліковано 14 лис 2024

КОМЕНТАРІ • 148

  • @takeUforward
    @takeUforward  3 роки тому +44

    Lets start a new trend, please comment "understood" in case you did :)

  • @manikantsharma6108
    @manikantsharma6108 2 роки тому +31

    Small correction in calling the function checkIfPrefixExists :
    It should be trie.checkIfPrefixExists(it) //Not just checkIfPrefixExists(it)
    And Thank U Striver for taking us forward!

  • @harshitsoni9103
    @harshitsoni9103 Рік тому +15

    In function isPrefix, we dont need to check if the word exists in the trie we just need to ensure that every node has flag value true because we are not asked to search for a new word.

  • @bidiptoroy6350
    @bidiptoroy6350 2 роки тому +11

    Understood, Thanks a lot.
    Implemented it on my own and this is how I did it:
    I used the search function of trie, and instead of traversing through nodes, and I checked for the string only if it is larger than the previous largest one, another thing is that in Java I stings are immutable, so I stored the index of the largest string instead of the largest string itself.

    • @crazyboy-gw7rk
      @crazyboy-gw7rk 2 роки тому

      Very well

    • @abhisekhagarwala3115
      @abhisekhagarwala3115 Рік тому

      bro could you please share the code for your implementation. i also tried to do the same by implementing the search function. but on one part i am struck. i need to check how you have implemented it

    • @IshanGuleria-l6b
      @IshanGuleria-l6b 10 місяців тому +1

      #include
      struct Node{
      bool isend = 0;
      Node* hash[26]={NULL};
      };
      class Trie{
      Node * root;
      public:
      Trie(){
      root = new Node();
      }
      void insert(string newword){
      Node* node = root;
      for(auto it : newword){
      if(!(node->hash[it-'a'])){
      node->hash[it-'a'] = new Node();
      }
      node = node->hash[it-'a'];
      }
      node->isend = 1;
      }
      bool is_pref(string searchword){
      Node* node = root;
      for(auto it : searchword){
      if(!(node->hash[it-'a'])) return 0;
      bool val = node->hash[it-'a']->isend;
      if(!val) return 0;
      node = node->hash[it-'a'];
      }
      return 1;
      }
      };
      string completeString(int n, vector &a){
      // Write your code here.
      Trie DS;
      for(auto it : a){
      DS.insert(it);
      }
      vector possible_strings;
      string prev("");
      bool flag = 1;
      for(auto it : a){
      if(DS.is_pref(it)) {
      if(flag) {prev = it;flag = 0;}
      if(it.size()>prev.size()) prev = it;
      if(it.size()==prev.size()&&it

  • @ManishKumar-kw7qe
    @ManishKumar-kw7qe Місяць тому

    I don't how i come up to this approach but it is working
    USED RECURSION
    TC -(n * m^2) n for the main for loop and m for the rec and m for the .find();
    you can use the unordered set the TC -O(n*m);
    sc-O(n) + m -->n for the set and m for the recursion stack space
    bool rec(int idx, string str, set& st, string word) {
    if (idx >= word.size()) {
    return true; // Base case: all characters have been processed
    }
    str += word[idx];
    if (st.find(str) == st.end()) {
    return false; // If prefix not found, return false
    }
    return rec(idx + 1, str, st, word);
    }
    string completeString(int n, vector& a) {
    set st(a.begin(), a.end());
    string valid = "";
    for (int i = 0; i < a.size(); i++) {
    string str="";
    if (rec(0, str, st, a[i])) {
    // Update valid string based on size and lexicographical order
    if (a[i].size() > valid.size()) {
    valid = a[i];
    } else if (a[i].size() == valid.size() && a[i] < valid) { 0 ? valid : "None";
    }

  • @chandrachurmukherjeejucse5816
    @chandrachurmukherjeejucse5816 Рік тому +1

    Understood and did it myself before watching this. All thanks to striver. ❤

  • @stith_pragya
    @stith_pragya 10 місяців тому +1

    UNDERSTOOD.....Thank You So Much for this wonderful video......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @kunalaggarwal3867
    @kunalaggarwal3867 2 роки тому +11

    Another solution for this question using maps:-
    string completeString(int n, vector &a){
    sort(a.begin(),a.end());
    string ans = "";
    unordered_mapm;
    m[""]++;
    int count = 0;
    for(auto i : a){
    string temp = i.substr(0,i.size()-1);
    if(m[temp]!=0){
    if(ans.size()

    • @nightmare_9
      @nightmare_9 8 місяців тому

      this will fail for many testcases which don't have all the substrings of the word, present in the array.

    • @trojanhorse8278
      @trojanhorse8278 4 місяці тому

      ​@@nightmare_9i don't think so. Only way a word can end up in a map is if it's prefix of length - > n-1 exists in array and would have been stored already in the map. Now recursively apply this property to its prefix existing in the map. So finally we can conclude that only if all the prefixes of a given word exist in the array, then only the word will be considered as a possible answer and would be inserted into the map. Still if u have any particular test case where it can fail, then please share.

    • @muditsinghal4191
      @muditsinghal4191 3 місяці тому

      sorting the strings make the time complexity as O(nlogn), but with tries, we can do this in O(n) itself.

  • @StudyMan-pf9tn
    @StudyMan-pf9tn 6 днів тому

    skip to 19:50 if you have seen L1 for trie implementation.

  • @Ratansingh19634
    @Ratansingh19634 2 роки тому +11

    Just a question, while iterating each input in completeString function
    Why don't you simply skip it if it's length is lower than current answer candidate. Why to even check if prefix exists or not.

    • @Cool96267
      @Cool96267 2 роки тому +4

      Finding length takes O(length) time which is similar to iterating it in Trie. So you can do whatever you want

    • @chetanraghavv
      @chetanraghavv 2 роки тому +6

      @@Cool96267 I guess in C++ STL, string::length() is constant time operation

  • @tanmaybro3812
    @tanmaybro3812 Місяць тому

    as the constraints are 1

  • @087alok9
    @087alok9 2 роки тому

    Bhaiya bahaut badhiya samjhaye hain aap. Thanks 👍🙌

  • @princysinha740
    @princysinha740 5 місяців тому +1

    wonderful just wonderful !!

  • @kushagrasrivastava1443
    @kushagrasrivastava1443 2 роки тому +3

    This is not optimal, since we are checking for each prefix from start, doing dfs would work fine.

  • @iampatelajeet
    @iampatelajeet Рік тому

    Understood everything, thanks bhaiya.

  • @rishabhkumar8115
    @rishabhkumar8115 2 роки тому +5

    string striver_Best_Explanation = "Understood";
    cout

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 роки тому +3

    Hello Striver! Thanks for all your videos.
    I don't think we have to write another function to check prefixes, we can check while inserting if already sort the strings by length, even it reduces complexity by a greater amount.
    My implementation of the idea, which passed all cases in code studio also:
    struct Node{
    vector children;
    bool isEnd;
    Node(){
    children.assign(26, NULL);
    isEnd = false;
    }
    bool containsKey(char ch){
    return children[ch - 'a']!=NULL;
    }
    void put(char ch, Node* node){
    children[ch - 'a'] = node;
    }
    Node* get(char ch){
    return children[ch - 'a'];
    }
    };
    class Trie{
    private:
    Node* root;
    public:
    Trie(){
    root = new Node();
    }
    bool insertAndCheck(string word){
    Node* node = root;
    for(int i=0; icontainsKey(word[i]) && node->isEnd){
    node = node->get(word[i]);
    } else {
    return false;
    }
    }
    node->put(word[word.length()-1], new Node());
    node->isEnd = true;
    return true;
    }
    };
    string completeString(int n, vector &a){
    sort(a.begin(), a.end(), [](string x, string y){return x.length() < y.length();});
    string longest = "";
    Trie obj;
    for(string word : a){
    if(obj.insertAndCheck(word)){
    if(word.length() > longest.length()){
    longest = word;
    } else if(word.length() == longest.length() && word < longest){
    longest = word;
    }
    }
    }
    return (longest == "" ? "None" : longest);
    }

    • @vanshsehgal9475
      @vanshsehgal9475 2 роки тому +1

      bro there is no need of checking /storing if the word ended, cuz as you are checking in increasing order of length, there is necessity that all prefixes till i-1 for that should be present. So it wont matter here. You can omit the isEnd attribute here.

    • @Anonymous-uj3jx
      @Anonymous-uj3jx 2 роки тому +1

      @@vanshsehgal9475 Yeah you're right!

    • @sumitkanth5349
      @sumitkanth5349 Рік тому

      @@vanshsehgal9475 is this correct ?
      #include
      struct Node{
      Node *child[26];
      Node(){
      for(int i=0; ichild[ind])) return false;
      if(word.length() == 1){
      Node *child = new Node();
      root->child[ind] = child;
      }
      // recursive call
      return check(root->child[ind], word.substr(1));
      }
      public:
      Trie(){
      root = new Node();
      }
      bool checkStr(string str){
      return check(root, str);
      }
      };
      string completeString(int n, vector &a){
      // Write your code here.
      sort(a.begin(), a.end());
      Trie *t = new Trie();
      string ans;
      for(int i=0; icheckStr(a[i])){
      if(a[i].size() > ans.size()) ans = a[i];
      }
      }
      if(!ans.size()) return "None";
      return ans;
      }

  • @mount2020
    @mount2020 Рік тому

    bhaiya has further made the code more readible, follow the link in the description

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 2 роки тому +1

    Understood thanks a lot

  • @aakashparmar560
    @aakashparmar560 3 роки тому +4

    Understood
    Keep em coming 🔥🔥

  • @priyanshkumar17
    @priyanshkumar17 7 місяців тому

    understood!! Great Problem & explanation. Thanks:)))!!!

  • @kousthubhtadanki1237
    @kousthubhtadanki1237 2 роки тому +1

    superb explanation!

  • @10minutes_cs
    @10minutes_cs 10 місяців тому

    time and space complexity : 12:30

  • @AbhishekVerma-zc5em
    @AbhishekVerma-zc5em 2 роки тому

    understood "Awesome Playlist"

  • @tangyao
    @tangyao Рік тому +1

    time complexity should be: O(n* it.length() * sub.string.length())
    n= for traversing the array
    it.length()= for all substring of a[i]
    substing.length()= when we are checking it in trie is it existing or not ?
    little confusion😥😥

    • @ipranavprashant
      @ipranavprashant 5 місяців тому

      The last substring.length() isn't under nested loop, it has an independent loop after insertion all the elements in the trie, hence O(n*avglen(input strings))

  • @UECAshutoshKumar
    @UECAshutoshKumar 7 місяців тому +1

    Thank you 🙏

  • @tech_wizard9315
    @tech_wizard9315 3 роки тому +5

    Is your graph n trees series enough to crack tech interviews of tech giant's (for DSA beginners)

    • @rutwickgangurde3247
      @rutwickgangurde3247 3 роки тому +5

      Practice is important. You need to know what constructs to use in what situation. You cannot predict what they'll ask. I had prepared all my algos for Uber, and I couldn't write a simple currying function. 😅

    • @shafiquemohammad2876
      @shafiquemohammad2876 2 роки тому

      @@rutwickgangurde3247 What was the question? Where have you been hired now?

    • @utkarsh_108
      @utkarsh_108 2 роки тому

      @@rutwickgangurde3247 oh

  • @girishbhargava6367
    @girishbhargava6367 3 роки тому +3

    Understood
    Please make a video on the topic, "WHAT TYPE OF QUESTIONS ARE ASKED IN INTERSHIP ROUNDS OF BIG COMPANIES"
    And how should we prepare from them...

  • @shyren_more
    @shyren_more 2 роки тому

    understood, thanks for the code explanation

  • @utkarsh_108
    @utkarsh_108 2 роки тому

    understooooood bhaiya. thanks 🙂

  • @umeshkaushik710
    @umeshkaushik710 2 роки тому

    Please make this solution avaialble on the website .

  • @dreamyme543
    @dreamyme543 Рік тому +1

    Understood:)

  • @shivashankar6043
    @shivashankar6043 Рік тому +1

    Can anyone please tell me,
    What software he’s using to write on this blackboard 9:47

  • @EditorGuru
    @EditorGuru 2 роки тому +1

    Understood 😊

  • @sandeeperukulla498
    @sandeeperukulla498 2 роки тому +6

    Hey Striver, you gave c++ solution in java solution link. Can you please provide java solution?

    • @anubhavnegi4230
      @anubhavnegi4230 11 місяців тому

      ```
      import java.util.Scanner;
      public class Trie {
      private static class Node{
      Node[] links = new Node[26];
      boolean flag = false;
      boolean containsKey(char ch){
      return links[ch -'a'] != null;
      }
      void put(char ch, Node node){
      links[ch - 'a'] = node;
      }
      Node get(char ch){
      return links[ch - 'a'];
      }
      void setEnd(){
      flag = true;
      }
      boolean isEnd(){
      return flag;
      }
      }
      private static Node root;
      public Trie(){
      root = new Node();
      }
      public static void insert(String word){
      Node node = root;
      for(int i =0; i < word.length(); i++){
      if(!node.containsKey(word.charAt(i))){
      node.put(word.charAt(i), new Node());
      }
      node = node.get(word.charAt(i));
      }
      node.setEnd();
      }
      public static boolean checkCompleteString(String word){
      Node node = root;
      for(int i= 0; i< word.length(); i++){
      if(!node.containsKey(word.charAt(i)) ){
      return false;
      }
      node = node.get(word.charAt(i));
      if(!node.flag){
      return false;
      }
      }
      return true;
      }
      }
      class Solution {
      public static String completeString(int n, String[] a) {
      Trie trie = new Trie();
      // insert all
      for(int i=0; i < a.length; i++){
      trie.insert(a[i]);
      }
      String maxString = "";
      // check for all strings
      for( int i = 0; i < n; i++){
      // if string is complete string or not
      if(trie.checkCompleteString(a[i])){
      if(maxString.length() < a[i].length()){
      maxString = a[i];
      }
      if ((maxString.length() == a[i].length()) && (maxString.compareTo(a[i]) > 0)) {
      maxString = a[i];
      }
      }
      }
      if(maxString.isEmpty()){
      return "None";
      }else{
      return maxString;
      }
      }
      }
      ```

  • @shubhrajit2117
    @shubhrajit2117 5 місяців тому

    Instead of checking for every word, we can do a dfs on the trie

  • @nishankdeep3084
    @nishankdeep3084 2 роки тому

    understood bhaiya
    thank you

  • @aayushsingh1512
    @aayushsingh1512 5 місяців тому +1

    cant we just bfs through the trie (only the nodes which are marked true)? It will have tc of O(len)

    • @6mahine_mein_google
      @6mahine_mein_google 2 місяці тому

      in the worst case its tc will still be O(sum of all lengths of the string) as you will be required to traverse every node

  • @mohdamaan5551
    @mohdamaan5551 4 місяці тому

    Wo cheez jisko dekh kar kabhi dar lagta tha,aur wo samajh aane laga to feeling hi kuch aur hoti hai.Aisa lagta hai jaise ab apna bhi kuch ho sakta hai😅

  • @omop5922
    @omop5922 Рік тому

    Ye question set se zada simply nhi hojaega?

  • @gudlaudaysai4571
    @gudlaudaysai4571 Рік тому +1

    undestood

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi 2 роки тому +1

    Hare Krishna!

  • @sivaganesh4489
    @sivaganesh4489 2 роки тому

    Thanks dude

  • @mr.jacker3951
    @mr.jacker3951 Рік тому

    I think line number 52 must be inside else statement

  • @saichaitanya4852
    @saichaitanya4852 2 роки тому

    Hi Striver, don't we need to consider the time complexity for comparing lexicographically smaller string after checkIfPrefixExists is true?

  • @lakshaysharma6550
    @lakshaysharma6550 2 роки тому

    Python Code for fellow pythonista :-
    class Node():
    def __init__(self):
    self.links=[None]*26
    self.flag=False
    def get(self,ch)-> 'Node':
    return self.links[ord(ch)-ord('a')]
    def put(self,ch,node):
    self.links[ord(ch)-ord('a')]=node
    def contains(self,ch):
    return self.links[ord(ch)-ord('a')]!=None
    def setEnd(self):
    self.flag=True
    def isEnd(self):
    return self.flag
    class Trie():
    def __init__(self) -> None:
    self.Trie=Node()
    def insert(self,word):
    node=self.Trie
    for i in word:
    if(not node.contains(i)):
    node.put(i,Node())
    node=node.get(i)
    node.setEnd()
    def checkPrefixExists(self,word):
    node=self.Trie
    for i in word:
    if(node.contains(i)):
    node=node.get(i)
    if(node.isEnd()==False):
    return False
    else:
    return False
    return True
    if __name__=='__main__':
    trie=Trie()
    prefixes=['n','ni','nin','ninj','ninja','ninga']
    for i in prefixes:
    trie.insert(i)
    longest=''
    for i in prefixes:
    if(trie.checkPrefixExists(i)):
    if(len(longest)

  • @Harshit126
    @Harshit126 2 роки тому

    Understood, thanks

  • @_-6912
    @_-6912 2 роки тому +12

    Hi Striver, your Java code is still written in C++. Could you please replace it with Java Code.

  • @SelvaArumugam-xq5mf
    @SelvaArumugam-xq5mf 3 місяці тому

    Understood brother

  • @hemantvardani1436
    @hemantvardani1436 2 роки тому

    Thanks

  • @khanakpatwari2587
    @khanakpatwari2587 9 місяців тому

    I didn't understand what exactly are we checking in check if prefix exist function, and why did we write if node is a terminal then return false? Can someone explain please?

  • @manoharmanu9240
    @manoharmanu9240 2 роки тому

    Understood 🙌

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 роки тому

    understood!

  • @arihantjammar8888
    @arihantjammar8888 Рік тому

    Understood 😊😊😊😊

  • @jaiminsolanki5478
    @jaiminsolanki5478 2 роки тому

    Understood!

  • @mananpurohit9299
    @mananpurohit9299 2 роки тому

    "understood" :)

  • @tanmaysinghal8370
    @tanmaysinghal8370 Рік тому +1

    Hello striver, The java github link for this question is also having c++ code... please update it...

  • @anshumangupta1001
    @anshumangupta1001 3 роки тому +1

    understood

  • @satyampande684
    @satyampande684 3 роки тому

    understood!!

  • @joshuamahadevan9550
    @joshuamahadevan9550 2 роки тому +1

    Here is my c++ code for this same problem. I did a dfs-like traversal on the trie. Guess it will be a bit more optimal than checking if prefix exists each time
    P.S : I names links as ref and flag as end. Its not industry standard as Boss Striver has done. Love ur content man ♥
    struct Node{
    Node* ref[26];
    bool end;
    Node(){
    for( int i=0; iend == false ) return;

    // some string has ended here
    if( path.size() > res.size() ) res=path;

    // move to the next char
    for( int i=0; iref[i]!=NULL ) {
    path+=('a'+i);
    get_ans( root->ref[i], res, path );
    path.pop_back();
    }
    }
    }
    string completeString(int n, vector &a){
    // Write your code here.

    // create a trie
    Node* root=new Node();
    root->end=true;

    // inserting each string into trie
    for( auto str: a ){
    Node* curr=root;
    for( auto c: str ){
    if( curr->ref[c-'a']==NULL ) curr->ref[c-'a'] = new Node();
    curr = curr->ref[c-'a'];
    }
    curr->end=true;
    }

    // findind answer
    string res, path;
    get_ans( root, res, path );
    if( res.size()==0 ) res="None";
    return res;
    }

    • @joshuamahadevan9550
      @joshuamahadevan9550 2 роки тому

      And.. I am studying tries now because I gave google's ot this sunday and tries qn was asked.. cldnt solve it lol ;-;

    • @josephaj8310
      @josephaj8310 2 роки тому

      Thanks to you, I was able to get to optimize my code 👍.
      string longestWord(){
      string res, path;
      dfs(path, res, this->root);
      return res;
      }
      void dfs(string &path, string &res, Node *root) {
      if(root == NULL || root->isEnd() == false) return;
      if(path.size() > res.size()){
      res = path;
      } else if(path.size() == res.size()){
      res = (path < res) ? path : res;
      }
      for(int i = 0; i < 26; i++){
      path.push_back('a' + i);
      dfs(path, res, root->get('a' + i));
      path.pop_back();
      }
      }

  • @nitinkumar5974
    @nitinkumar5974 2 роки тому +2

    bool checkAllPrefixExist(string &word)
    {
    TrieNode* cur = root;
    for(auto &ch : word){
    if(cur->links[ch-'a']!=NULL){
    cur = cur->links[ch-'a'];
    if(cur->isEnd==false)
    return false;
    }
    else
    return false;
    }
    return true;
    }

  • @RohitBindalMusic
    @RohitBindalMusic 2 роки тому +2

    U
    N
    D
    E
    R
    S
    T
    O
    O
    D

  • @arahul6098
    @arahul6098 2 роки тому

    understood..

  • @sohamsen7892
    @sohamsen7892 2 роки тому

    Understood

  • @aayush5474
    @aayush5474 2 роки тому

    I already solved the question before seeing the video but i see the video later anyways xD

  • @LevelUpJourney-d2d
    @LevelUpJourney-d2d 2 роки тому

    understood sir

  • @ManishSahu-fu5ml
    @ManishSahu-fu5ml 8 місяців тому

    Hi Striver
    Thanks a lot for making these videos.
    Could you please tell me which application you use to make these videos ?

  • @prateekgoel7248
    @prateekgoel7248 2 роки тому +1

    from typing import *
    from collections import defaultdict
    class Trie:
    def __init__(self):
    self.child = defaultdict(Trie)
    self.end = False
    def insert(self,word):
    cur=self
    for i in word:
    cur=cur.child[i]
    cur.end=True
    def search(self,word):
    cur=self
    for i in word:
    if i not in cur.child:
    return False
    cur = cur.child[i]
    return cur.end
    def checkLongest(self,word):
    cur = self
    for i in word:
    cur=cur.child[i]
    if not cur.end:
    return False
    return True


    def completeString(n: int, a: List[str])-> str:
    trie = Trie()
    for i in a:
    trie.insert(i)
    ans=""
    for i in a:
    if trie.checkLongest(i):
    if len(ans)

  • @arpitprasad2249
    @arpitprasad2249 2 роки тому +2

    Can't we use a map here? I haven't yet solved the qs and I am halfway through the video but my intuition is saying to use the map insert all the strings in the map and for each string create the prefix using substr fn and check whether the prefix is present or not. we may avoid that extra time complexity of inserting each string in a trie O(N)*O(len) where len is the average length of the string. I may be wrong

    • @devapriyanta9000
      @devapriyanta9000 2 роки тому +3

      your approach is correct. Lets calculate the Time complexity : O(n*logn) + O(n*len*logn) where len is avg leng of string, n*logn for inserting all strings in the map, and n*len*logn for taking each string, find substring and checking in the map,
      Wheres Trie approach takes 2*O(n*len),

    • @SreekantShenoy
      @SreekantShenoy 2 роки тому +1

      @Virendra Negi Here is my understanding, correct me if I am wrong.
      The time complexity will be - O(N*len(s)*LogN).
      N - traversing all string
      len(s) - each substring in a string
      logN - search time in a map.
      search time for map - log(N) and unordered_map - O(1) average, O(N) (worse).
      "unordered_map worst case usually happens when the hash function is producing collisions for every insertion in the map." It might not happen often, but its a factor.
      I believe because of this Trie works better for larger cases, without any collisions and easy traversal. (but long code lol).

  • @mohitsomvanshi9364
    @mohitsomvanshi9364 2 роки тому

    "understood"

  • @shilpagupta2056
    @shilpagupta2056 Рік тому

    Java solution k jga syd apne c++ dal dia h

  • @addityasharma6426
    @addityasharma6426 2 роки тому

    uderstood :-)

  • @deepakbasoiya975
    @deepakbasoiya975 2 роки тому

    but what about this example ni , nin , ninj, ninja , ningass its give 0 becouse for n its not true

  • @_aka5h
    @_aka5h Рік тому

    If there was one more input for the first sample test case, they would have written the N - word.

  • @kalpeshmali8498
    @kalpeshmali8498 3 роки тому +1

    UnderStood++;

  • @AmandeepSingh-uq3wp
    @AmandeepSingh-uq3wp 3 роки тому

    "Understood"

  • @d.p.fashionhub9425
    @d.p.fashionhub9425 10 місяців тому

    this code give wrong answer

  • @sumitkanth5349
    @sumitkanth5349 Рік тому

    can we do this by sorting like this:
    /*
    #include
    struct Node{
    Node *child[26];
    Node(){
    for(int i=0; ichild[ind])) return false;
    if(word.length() == 1){
    Node *child = new Node();
    root->child[ind] = child;
    }
    // recursive call
    return check(root->child[ind], word.substr(1));
    }
    public:
    Trie(){
    root = new Node();
    }
    bool checkStr(string str){
    return check(root, str);
    }
    };
    string completeString(int n, vector &a){
    // Write your code here.
    sort(a.begin(), a.end());
    Trie *t = new Trie();
    string ans;
    for(int i=0; icheckStr(a[i])){
    if(a[i].size() > ans.size()) ans = a[i];
    }
    }
    if(!ans.size()) return "None";
    return ans;
    }
    */

  • @saumilaggarwal5233
    @saumilaggarwal5233 Рік тому

    thnx i did this on my own, code:
    #include
    struct Node{
    Node* links[26];
    bool isTerminal=false;
    bool containsKey(char ch){
    return links[ch-'a']!=NULL;
    }
    void puts(char ch){
    links[ch-'a']=new Node();
    }
    Node* gets(char ch){
    return links[ch-'a'];
    }
    };
    class Trie{
    Node* root;
    public:
    Trie(){
    root= new Node();
    }
    void insert(string& str){
    Node* node= root;
    for(int i=0;icontainsKey(str[i])){
    node->puts(str[i]);
    }
    node=node->gets(str[i]);
    }
    node->isTerminal=true;
    }
    int checkSize(string& a){
    Node* node= root;
    int count=0;
    for(int i=0;igets(a[i])->isTerminal){
    return 0;
    }else{
    count++;
    }
    node= node->gets(a[i]);
    }
    return count;
    }
    };
    string completeString(int n, vector &a){
    // Write your code here.
    Trie t1;
    for(auto it: a){
    t1.insert(it);
    }

    int size=0;
    string ansString="";
    for(int i=0;i

  • @ankitkushwaha6269
    @ankitkushwaha6269 2 роки тому +1

    java simple code
    class Solution {
    static class trie{
    boolean isEnd = false;
    trie[] children = new trie[26];
    }

    static trie root;
    public static String completeString(int n, String[] a) {
    root = new trie();
    for(String str : a){
    insert(str);
    }

    String longest = "";
    for(String word : a){
    if(checkIfAllPrefixExists(word)){
    if(word.length() > longest.length()){
    longest = word;
    }
    else if((word.length() == longest.length()) && word.compareTo(longest) < 0){
    longest = word;
    }
    }
    }

    return longest == "" ? "None" : longest;
    }

    public static boolean checkIfAllPrefixExists(String word){
    trie node = root;
    boolean flag = true;
    for(char ch : word.toCharArray()){
    if(node.children[ch - 'a'] != null){
    node = node.children[ch - 'a'];
    flag = flag && node.isEnd;
    }
    else return false;
    }
    return flag;
    }

    public static void insert(String word){
    trie node = root;
    for(char ch : word.toCharArray()){
    if(node.children[ch - 'a'] == null){
    node.children[ch - 'a'] = new trie();
    }
    node = node.children[ch - 'a'];
    }
    node.isEnd = true;
    }
    }

  • @prawarmundra4931
    @prawarmundra4931 2 роки тому +1

    // getting tle
    struct Node{
    Node *list[26];
    bool flag=false;
    bool containsKey(char ch) {
    return list[ch-'a'] != NULL;
    }
    void put(char ch, Node *node) {
    list[ch-'a'] = node;
    }
    Node* get(char ch) {
    return list[ch-'a'];
    }
    void setEnd() {
    flag = true;
    }
    bool isEnd() {
    return flag;
    }
    };
    class Trie {
    private: Node *root;
    public:
    Trie() {
    root = new Node;
    }
    void insert(string word) {
    Node *node = root;
    for(int i=0;icontainsKey(word[i])) {
    node->put(word[i],new Node);
    }
    node = node->get(word[i]);
    }
    node->setEnd();
    }
    bool checkIfPrefixExists(string word) {
    Node *node = root;
    bool f = true;
    for(int i=0;icontainsKey(word[i])) {
    node = node->get(word[i]);
    f = f&node->isEnd();
    }
    else {
    return false;
    }
    }
    return f;
    }
    };
    string completeString(int n, vector &a){
    // Write your code here.
    Trie* obj = new Trie();
    for(auto it:a){
    obj->insert(it);
    }
    string longest = "";
    for(auto it : a) {
    if(obj->checkIfPrefixExists(it)) {
    if(it.size()>longest.size()){
    longest = it;
    }
    else if(it.size()==longest.size() && it

  • @prasad_rp
    @prasad_rp 2 роки тому +1

    ninga

  • @rishivalaparla7757
    @rishivalaparla7757 2 роки тому

    us

  • @shikhagupta4429
    @shikhagupta4429 7 місяців тому

    struct Node {
    Node* links[26];
    bool flag = false;
    bool containskey(char ch) {
    return links[ch - 'a'] != NULL;
    }
    Node* get(char ch) {
    return links[ch - 'a'];
    }
    void put(char ch, Node* node) {
    links[ch - 'a'] = node;
    }
    void setend() {
    flag = true;
    }
    bool isend() {
    return flag;
    }
    };
    class Trie{
    private: Node* root;
    public:
    Trie(){
    root=new Node();
    }
    public: void insert(string word){
    Node* node =root;
    for( int i=0;i< word.length();i++){
    if( !node->containskey(word[i])){
    node->put(word[i],new Node());
    }
    node=node->get(word[i]);
    }
    node->setend();
    }
    public:
    bool check(string word){
    Node* node = root;
    bool flag=true;
    for (int i = 0; i < word.length(); i++) {
    if (node->containskey(word[i])) {
    node = node->get(word[i]);
    if (node->isend()==false) return false;
    }
    else {
    return false;
    }
    }
    return true;
    }
    };
    string longestCommonPrefix(vector &arr, int n)
    {
    Trie trie;
    for (auto& it : arr) {
    trie.insert(it);
    }
    string longest = "";
    for (auto& it : arr) {
    if (trie.check(it)) {
    if (it.length() > longest.length()) {
    longest = it;
    } else if (it.length() == longest.length() && it < longest) {
    longest = it;
    }
    }
    }
    if (longest == "") return "None";
    return longest;
    } This code returns the None value for all the test cases!! can anyone telll me what's the issue ??

  • @letmehelp8927
    @letmehelp8927 Рік тому

    Understood thnks...
    #include
    struct Node{
    Node* links[26];
    bool flag = false;
    bool containskey(char ch){
    return (links[ch - 'a'] != NULL);
    }
    void put(char ch, Node* node){
    links[ch - 'a'] = node;
    }
    Node* get(char ch){
    return links[ch - 'a'];
    }
    void setEnd(){
    flag = true;
    }
    bool isEnd(){
    return flag;
    }
    };
    class trie{
    private:
    Node* root;
    public:
    trie(){
    root = new Node();
    }
    void insert(string word){
    Node* node = root;
    for(int i=0; icontainskey(word[i])){
    node->put(word[i],new Node());
    }
    node = node->get(word[i]);
    }
    node->setEnd();
    }
    bool search(string word){
    Node* node = root;
    for(int i=0; icontainskey(word[i])){
    return false;
    }
    node = node->get(word[i]);
    }
    return node->isEnd();
    }
    };
    bool cmp(string s,string ans){
    int i=0 , j=0;
    while(i

  • @vasujhawar.6987
    @vasujhawar.6987 Рік тому +1

    why do you make such accent? it feels annoying...

  • @divyangdheer7292
    @divyangdheer7292 2 роки тому +1

    c++ working code
    .
    .
    .
    #include
    struct Node{
    Node* links[26];
    bool flag = false;
    bool conatinsKey(char ch){
    return (links[ch-'a']!=NULL);
    }
    Node* get(char ch){
    return links[ch-'a'];
    }
    void put(char ch, Node* node){
    links[ch-'a'] = node;
    }
    void setEnd(){
    flag = true;
    }
    bool isEnd(){
    return flag;
    }
    };
    class Trie{
    private:
    Node* root;
    public:
    Trie(){
    root = new Node();
    }
    void insert(string word) {
    Node *node = root;
    for (int i = 0; i < word.size(); i++) {
    if (!node->conatinsKey(word[i])) {
    node->put(word[i], new Node());
    }
    node = node->get(word[i]);
    }
    node->setEnd();
    }
    bool checkAllPrefixExist(string &word)
    {
    Node* cur = root;
    for(auto &ch : word){
    if(cur->links[ch-'a']!=NULL){
    cur = cur->links[ch-'a'];
    if(cur->isEnd()==false)
    return false;
    }
    else
    return false;
    }
    return true;
    }
    };
    string completeString(int n, vector &a){
    Trie trie;
    for(auto it:a){
    trie.insert(it);
    }
    string longest = "";
    for(auto it : a) {
    if(trie.checkAllPrefixExist(it)) {
    if(it.size()>longest.size()){
    longest = it;
    }
    else if(it.size()==longest.size() && it

    • @shikhagupta4429
      @shikhagupta4429 7 місяців тому

      this is giving wrong answer ...for every test cases it returns the none value.....

    • @divyangdheer7292
      @divyangdheer7292 7 місяців тому

      @@shikhagupta4429 bhai 1 saal pehle ka code hai, wo time shi chalra tha, ab kuch changes kr diye honge me kya kru, or tune video dekhi hai toh tere se khud se code na likha jara, mene bhi toh ye khud kiya

  • @sayandey2492
    @sayandey2492 Рік тому

    Single pass C++ code:
    #include
    struct Node
    {
    Node* links[26];
    int ew=0; //if any word is ending at this node
    void put(char ch, Node* node)
    {
    links[ch-'a']=node;
    }
    };
    string completeString(int n, vector &a){
    sort(a.begin(),a.end());
    Node* root=new Node();
    root->ew=1;
    int anslen=0;
    string ans;
    for(int i=0;iput(word[j], new Node());
    if(temp->ew ==0)
    flag=false;
    temp=temp->links[word[j]-'a'];
    }
    temp->ew += 1;
    if(flag==true)
    {
    if(word.size()>anslen)
    {
    anslen=word.size();
    ans=word;
    }
    }
    }
    if(ans=="")
    return "None";
    return ans;
    }

  • @Aryan-vw7lt
    @Aryan-vw7lt 4 місяці тому +1

    understood!

  • @codingp110
    @codingp110 4 місяці тому

    Understood!

  • @kumardigambar1664
    @kumardigambar1664 Рік тому

    thanks

  • @jolly_dollyyy
    @jolly_dollyyy 3 роки тому

    understood!!

  • @vaishnavisood9699
    @vaishnavisood9699 2 роки тому

    Understood

  • @amanrai7572
    @amanrai7572 2 роки тому

    understood

  • @tusharnain6652
    @tusharnain6652 2 роки тому +1

    U N D E R S T O O D

  • @dhruvpurwar6642
    @dhruvpurwar6642 2 роки тому

    understood!!!

  • @umeshkaushik710
    @umeshkaushik710 2 роки тому

    Understood

  • @sandeeperukulla498
    @sandeeperukulla498 2 роки тому

    understood

  • @ashj1165
    @ashj1165 Місяць тому

    understood!!!

  • @sreyanssinghi8583
    @sreyanssinghi8583 2 роки тому

    Understood