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

  Рет қаралды 64,704

take U forward

take U forward

2 жыл бұрын

Check our Website:
In case you are thinking to buy courses, please check below:
Link to get 20% additional Discount at Coding Ninjas: bit.ly/3wE5aHx
Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
Linkedin/Instagram/Telegram: linktr.ee/takeUforward
---------------------------------------------------------------------------------------------------------------------------------------------------- Pre-requisite: First Video of the Playlist: • L1. Implement TRIE | I...
In this video, we discuss the question longest word with all prefixes!
Please share this channel as much as you can. Also, it's an earnest request to drop a comment "understood" if you are watching this video, so that I get to know you understood from this video.
SDE-Sheet/Linkedin/Telegram/Instagram: linktr.ee/takeUforward
-------------------------------------------------------------------------------------------------------------
Problem Link: bit.ly/3n3kedU
C++ Code: github.com/striver79/Strivers...
Javahttps:github.com/striver79/Strivers...

Пікірлер: 144
@takeUforward
@takeUforward 2 жыл бұрын
Lets start a new trend, please comment "understood" in case you did :)
@sukhpreetsingh5200
@sukhpreetsingh5200 Жыл бұрын
understood
@manikantsharma6108
@manikantsharma6108 2 жыл бұрын
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 Жыл бұрын
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.
@chandrachurmukherjeejucse5816
@chandrachurmukherjeejucse5816 11 ай бұрын
Understood and did it myself before watching this. All thanks to striver. ❤
@bidiptoroy6350
@bidiptoroy6350 2 жыл бұрын
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 Жыл бұрын
Very well
@abhisekhagarwala3115
@abhisekhagarwala3115 9 ай бұрын
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
@user-fn2mt5ut2j
@user-fn2mt5ut2j 5 ай бұрын
#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
@stith_pragya
@stith_pragya 5 ай бұрын
UNDERSTOOD.....Thank You So Much for this wonderful video......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@087alok9
@087alok9 2 жыл бұрын
Bhaiya bahaut badhiya samjhaye hain aap. Thanks 👍🙌
@saichaitanya4852
@saichaitanya4852 2 жыл бұрын
Hi Striver, don't we need to consider the time complexity for comparing lexicographically smaller string after checkIfPrefixExists is true?
@kousthubhtadanki1237
@kousthubhtadanki1237 2 жыл бұрын
superb explanation!
@iampatelajeet
@iampatelajeet Жыл бұрын
Understood everything, thanks bhaiya.
@aakashparmar560
@aakashparmar560 2 жыл бұрын
Understood Keep em coming 🔥🔥
@priyanshkumariitd
@priyanshkumariitd 3 ай бұрын
understood!! Great Problem & explanation. Thanks:)))!!!
@princysinha740
@princysinha740 18 күн бұрын
wonderful just wonderful !!
@sukhpreetsingh5200
@sukhpreetsingh5200 Жыл бұрын
Understood thanks a lot
@shyren_more
@shyren_more Жыл бұрын
understood, thanks for the code explanation
@Ratansingh19634
@Ratansingh19634 2 жыл бұрын
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.
@atulraj3010
@atulraj3010 2 жыл бұрын
yes,you can do this as well
@Cool96267
@Cool96267 2 жыл бұрын
Finding length takes O(length) time which is similar to iterating it in Trie. So you can do whatever you want
@chetanraghavv
@chetanraghavv 2 жыл бұрын
@@Cool96267 I guess in C++ STL, string::length() is constant time operation
@utkarsh_108
@utkarsh_108 2 жыл бұрын
understooooood bhaiya. thanks 🙂
@AbhishekVerma-zc5em
@AbhishekVerma-zc5em 2 жыл бұрын
understood "Awesome Playlist"
@aayushsingh1512
@aayushsingh1512 19 күн бұрын
cant we just bfs through the trie (only the nodes which are marked true)? It will have tc of O(len)
@shivashankar6043
@shivashankar6043 8 ай бұрын
Can anyone please tell me, What software he’s using to write on this blackboard 9:47
@Harshit126
@Harshit126 Жыл бұрын
Understood, thanks
@sivaganesh4489
@sivaganesh4489 2 жыл бұрын
Thanks dude
@mount2020
@mount2020 Жыл бұрын
bhaiya has further made the code more readible, follow the link in the description
@kunalaggarwal3867
@kunalaggarwal3867 Жыл бұрын
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 4 ай бұрын
this will fail for many testcases which don't have all the substrings of the word, present in the array.
@trojanhorse8278
@trojanhorse8278 3 күн бұрын
​@@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.
@UECAshutoshKumar
@UECAshutoshKumar 3 ай бұрын
Thank you 🙏
@satyampande684
@satyampande684 2 жыл бұрын
understood!!
@rishabhkumar8115
@rishabhkumar8115 2 жыл бұрын
string striver_Best_Explanation = "Understood"; cout
@_-6912
@_-6912 2 жыл бұрын
Hi Striver, your Java code is still written in C++. Could you please replace it with Java Code.
@EditorGuru
@EditorGuru 2 жыл бұрын
Understood 😊
@kushagrasrivastava1443
@kushagrasrivastava1443 Жыл бұрын
This is not optimal, since we are checking for each prefix from start, doing dfs would work fine.
@ManishSahu-fu5ml
@ManishSahu-fu5ml 4 ай бұрын
Hi Striver Thanks a lot for making these videos. Could you please tell me which application you use to make these videos ?
@mohdamaan5551
@mohdamaan5551 15 күн бұрын
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😅
@tanmaysinghal8370
@tanmaysinghal8370 Жыл бұрын
Hello striver, The java github link for this question is also having c++ code... please update it...
@umeshkaushik710
@umeshkaushik710 Жыл бұрын
Please make this solution avaialble on the website .
@khanakpatwari2587
@khanakpatwari2587 5 ай бұрын
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?
@jaiminsolanki5478
@jaiminsolanki5478 2 жыл бұрын
Understood!
@Tarunkumar_Gatla
@Tarunkumar_Gatla 2 жыл бұрын
What if all the strings in thr vector are of length 1? Does that mean that the length of longest complete string will also be 1? Please answer 🙏
@shubham320
@shubham320 2 жыл бұрын
@Tarunkumar Gatla I checked on leetcode by giving several custom inputs to internal solution. Answer turns out to be "yes". If all strings have length 1 or there is string of length 1 present in the list, it can be considered for ans. The reason according to me is, you start with empty string and pick a string from list one by one such that your string must be prefix of the string from the list and they differ in length by 1.
@abhishekm1502
@abhishekm1502 Жыл бұрын
@@shubham320 is this question available on leetcode
@Anonymous-uj3jx
@Anonymous-uj3jx 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@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; }
@sandeeperukulla498
@sandeeperukulla498 2 жыл бұрын
Hey Striver, you gave c++ solution in java solution link. Can you please provide java solution?
@anubhavnegi4230
@anubhavnegi4230 6 ай бұрын
``` 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; } } } ```
@nishankdeep3084
@nishankdeep3084 Жыл бұрын
understood bhaiya thank you
@manoharmanu9240
@manoharmanu9240 Жыл бұрын
Understood 🙌
@tech_wizard9315
@tech_wizard9315 2 жыл бұрын
Is your graph n trees series enough to crack tech interviews of tech giant's (for DSA beginners)
@rutwickgangurde3247
@rutwickgangurde3247 2 жыл бұрын
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
@tangyao
@tangyao Жыл бұрын
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 20 күн бұрын
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))
@Anonymous-uj3jx
@Anonymous-uj3jx 2 жыл бұрын
understood!
@original_gangsta_
@original_gangsta_ 3 ай бұрын
Understood
@dreamyme543
@dreamyme543 Жыл бұрын
Understood:)
@girishbhargava6367
@girishbhargava6367 2 жыл бұрын
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...
@hemantvardani1436
@hemantvardani1436 Жыл бұрын
Thanks
@anshumangupta1001
@anshumangupta1001 2 жыл бұрын
understood
@omop5922
@omop5922 Жыл бұрын
Ye question set se zada simply nhi hojaega?
@kumardigambar1664
@kumardigambar1664 Жыл бұрын
thanks
@gudlaudaysai4571
@gudlaudaysai4571 7 ай бұрын
undestood
@shubhrajit2117
@shubhrajit2117 25 күн бұрын
Instead of checking for every word, we can do a dfs on the trie
@aayush5474
@aayush5474 2 жыл бұрын
I already solved the question before seeing the video but i see the video later anyways xD
@nbavideos4487
@nbavideos4487 2 жыл бұрын
understood sir
@arahul6098
@arahul6098 Жыл бұрын
understood..
@arihantjammar8888
@arihantjammar8888 8 ай бұрын
Understood 😊😊😊😊
@mananpurohit9299
@mananpurohit9299 2 жыл бұрын
"understood" :)
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi 2 жыл бұрын
Hare Krishna!
@mr.jacker3951
@mr.jacker3951 Жыл бұрын
I think line number 52 must be inside else statement
@addityasharma6426
@addityasharma6426 Жыл бұрын
uderstood :-)
@user-do1eq7tl3e
@user-do1eq7tl3e 5 ай бұрын
time and space complexity : 12:30
@RohitBindalMusic
@RohitBindalMusic 2 жыл бұрын
U N D E R S T O O D
@mohitsomvanshi9364
@mohitsomvanshi9364 2 жыл бұрын
"understood"
@joshuamahadevan9550
@joshuamahadevan9550 2 жыл бұрын
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 Жыл бұрын
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(); } }
@kalpeshmali8498
@kalpeshmali8498 2 жыл бұрын
UnderStood++;
@arpitprasad2249
@arpitprasad2249 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 жыл бұрын
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 жыл бұрын
@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).
@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)
@AmandeepSingh-uq3wp
@AmandeepSingh-uq3wp 2 жыл бұрын
"Understood"
@nitinkumar5974
@nitinkumar5974 Жыл бұрын
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; }
@deepakbasoiya975
@deepakbasoiya975 Жыл бұрын
but what about this example ni , nin , ninj, ninja , ningass its give 0 becouse for n its not true
@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; } */
@prateekgoel7248
@prateekgoel7248 Жыл бұрын
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)
@shilpagupta2056
@shilpagupta2056 Жыл бұрын
Java solution k jga syd apne c++ dal dia h
@_aka5h
@_aka5h Жыл бұрын
If there was one more input for the first sample test case, they would have written the N - word.
@rishivalaparla7757
@rishivalaparla7757 2 жыл бұрын
us
@ankitkushwaha6269
@ankitkushwaha6269 2 жыл бұрын
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; } }
@saumilaggarwal5233
@saumilaggarwal5233 8 ай бұрын
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
@Rohit-zv6ev
@Rohit-zv6ev 2 жыл бұрын
ninga
@d.p.fashionhub9425
@d.p.fashionhub9425 5 ай бұрын
this code give wrong answer
@prawarmundra4931
@prawarmundra4931 2 жыл бұрын
// 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
@coding8000
@coding8000 2 жыл бұрын
Thanks man!
@shikhagupta4429
@shikhagupta4429 2 ай бұрын
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 Жыл бұрын
why do you make such accent? it feels annoying...
@divyangdheer7292
@divyangdheer7292 Жыл бұрын
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 2 ай бұрын
this is giving wrong answer ...for every test cases it returns the none value.....
@divyangdheer7292
@divyangdheer7292 2 ай бұрын
@@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 9 ай бұрын
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; }
@jolly_dollyyy
@jolly_dollyyy 2 жыл бұрын
understood!!
@codingp110
@codingp110 15 күн бұрын
Understood!
@Aryan-vw7lt
@Aryan-vw7lt 16 күн бұрын
understood!
@sohamsen7892
@sohamsen7892 2 жыл бұрын
Understood
@utkarshsharma1185
@utkarshsharma1185 2 жыл бұрын
understood
@tusharnain6652
@tusharnain6652 2 жыл бұрын
U N D E R S T O O D
@LowkeyCoder
@LowkeyCoder 6 ай бұрын
"Understood"
@dhruvpurwar6642
@dhruvpurwar6642 2 жыл бұрын
understood!!!
@vaishnavisood9699
@vaishnavisood9699 2 жыл бұрын
Understood
@amanrai7572
@amanrai7572 2 жыл бұрын
understood
@umeshkaushik710
@umeshkaushik710 Жыл бұрын
Understood
@sandeeperukulla498
@sandeeperukulla498 2 жыл бұрын
understood
@ShivaSundarRRajagiri
@ShivaSundarRRajagiri 11 ай бұрын
Understood
@komalyadav5599
@komalyadav5599 10 ай бұрын
Understood
L4. Number of Distinct Substrings in a String | Trie | C++ | Java
18:10
HOW DID HE WIN? 😱
00:33
Topper Guild
Рет қаралды 18 МЛН
Vivaan  Tanya once again pranked Papa 🤣😇🤣
00:10
seema lamba
Рет қаралды 31 МЛН
The child was abused by the clown#Short #Officer Rabbit #angel
00:55
兔子警官
Рет қаралды 23 МЛН
Must-have gadget for every toilet! 🤩 #gadget
00:27
GiGaZoom
Рет қаралды 12 МЛН
100+ Linux Things you Need to Know
12:23
Fireship
Рет қаралды 155 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 301 М.
LeetCode 14. Longest Common Prefix Solution Explained - Java
6:33
Live Mock Interview with @Striver | MAANG Format | GeeksforGeeks
53:14
L5. Bit PreRequisites for TRIE Problems
9:29
take U forward
Рет қаралды 35 М.
L7. Maximum XOR With an Element From Array | Queries | C++ | Java
24:15
Best Order to Learn Algorithms & Data Structures
1:00
NeetCodeIO
Рет қаралды 140 М.
HOW DID HE WIN? 😱
00:33
Topper Guild
Рет қаралды 18 МЛН