L4. Number of Distinct Substrings in a String | Trie | C++ | Java
Вставка
- Опубліковано 25 лис 2021
- 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
---------------------------------------------------------------------------------------------------------------------------------------------------- Lecture notes/C++/Java Codes - takeuforward.org/data-structu...
Pre-requisite: First Video of the Playlist: • L1. Implement TRIE | I...
In this video, we discuss the question counting the number of distinct substrings in a string.
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/3ocRQW0
Lets start a new trend, please comment "understood" in case you did :)
Understood it very well. Pretty simple implementation, was able to code it myself upon seeing the explanation! Thanks a lot raj bhaiya❤
Understood, Thanks for making hard things easy.
understood and its clever way of implementation.
Brilliant approach!
Please start dp series only you can teach best 🙏🙏🙏🙏💯
Bro check aditya dp series, it will help u
@@yogendrajhala4147 Yes I agree!! Aditya Verma is like DP God
understood, great explanation ❤️
sir there is a mistake in your code "instead of word[i] you should have written word[j] in every function you have passed" it will not execute properly..
Great...Thanks..
@take U forward what if I use unordered_map mp instead of using links[26] does space complexity will be O(n^2) in the worst case scenario. Please correct me if I am wrong
Same query
Use map then worst case will be nlogn
understood!!
Thanks Striver!
understood bhaiya
thank you bhaiya
Avoid String hashing it will give u MLE when string length is very large.
Understood 🙌
Thank you 🙏
Thanks dude
understooooood. thanks bhaiya 🙂
Node* links[26] ;
These array has default value of NULL?
Imp : if multiple words are not given, no need to construct explicit trie class
Understood!!!
Understood!
Understood!!
Understood bhaiya
understood great explaination. But I have one more doubt I am able to submit the answers , but its showing TLE. can we reduce the O(n2) complexity?
use suffix arrays
Sir, there is something wrong during you write code same code I written in python , but we try test case "ninja" it should be return 15 (14 + 1), but answer is not getting right.
I tried to solve the problem given in the problem link but I am getting TLE as a verdict and in question, it is specifically written that we have to implement the trie method. Is there any more approach better than this one?
Hashing
I'm not getting tle with trie approach
@@sarthak7438 Yes, I think they have increased time limit or decreased test cases. Same code got TLE 6th months before but now it's showing correct answer.
understood😁
Thanks
Understood 😊
Love you sir
understood
Understood
how the
worst case tc for adding to set takes logm..if there are collisions it becomes o(m) right ? can anyone explain
Understood.
Understood.. But couldn't understand why you mentioned time complexity of set.add() as logN at 4:11 . As we know that HashSet has amortized time complexity as O(1) for add operation as it uses hashmap internally. I'm assuming that hash collision will rarely occur.
Again I would say you explained it very well.
Unordered set has, not set
So why we used set here and not the unordered set?
@@mevam123 absolutely what i was thinking of. we only need the substrings, order doesn't matter to us so we can use unordered_set
@adolft_official and so is the case with Trie, I think Trie doesn't improve the time complexity over unordered_set, it only improves the space complexity.
@@tusharvlogs6333 yes
can you plz tell me the board name you are using ?
Is there any O(n) solution present for this??
use unordered set instead of set
understood..
understood :-)
why did the loop run till n-1 for the brute approach. shouldn't it run till n times. because we also need to consider the last ele of the string.
Its basically less than equal to n - 1 for(int j = 0; j
i =0 bakwas
Is creating trie class important ? Like in last question u did it, so can we solve that without creating it
Understood but why do we need a set here to strings at 4:11
At 4:06 I searched the time complexity of set operations and it said O(1) for avg case and O(N) for worst case.
The average length of a sub-string of a non-empty string of length n is (n + 2) / 3.
sir, why is space complexity of the brute soln O(n*n) * O(n) ? why is string length taken into account??
why is it not correct to say that it takes O(n*n) space?
because the average length of substring is n/2 on an average. there can be substring of size 1 as well and substring of size n as well so it averages out to be n/2 for each substring.
Cheers :)
@@vishalgupta957 but to insert a string in unordered_set take O(1) then it must be O(n^2) only ?
@@abhinavsingh6532 nope it's amortized O(1)
same content i learned in masterclass
what teaching app are you using?
Other than TRIE how to solve this problem? Would you kindly tell me the answer?
via suffix array
for those who are getting memory limit error in leetcode:
const int MAX_NODES = 500 * 500; // Maximum number of nodes in the trie (based on the problem constraints)
int trie[MAX_NODES + 5][26]; // Trie data structure: Each node can have up to 26 children (corresponding to letters 'a' to 'z')
class Solution {
public:
int countDistinct(string &str) {
int n = str.size(); // Length of the input string
int ans = 0; // Count of distinct substrings
int sz = n * n * 26 * sizeof(int); // Size of memory to initialize trie
memset(trie, 0, sz); // Initialize trie with zeros
int root = 0; // Root of the trie
int temp = root; // Temporary variable to traverse the trie
// Loop over all substrings of the input string
for (int i = 0; i < n; i++) {
// Start building substrings from index i
for (int j = i; j < n; j++) {
int d = str[j] - 'a'; // Calculate the index corresponding to the character
// Access the child node 'd' of the current node 'temp' in the trie
int &pos = trie[temp][d];
if (pos == 0) {
// If the child node doesn't exist (not visited before), create a new node
ans++; // Increment the count of distinct substrings
pos = ans; // Link the new node with its parent
}
// Move to the next node in the trie (corresponding to the character 'd')
temp = pos;
}
// Reset temp to root for the next substring starting from index i+1
temp = root;
}
return ans; // Return the total count of distinct substrings
}
};
understood ++
Time limit exceeded... ???
UnderStood
US
In code, line 4
wouldn't that be word[j] in the second for loop?
You can check the github code once… its running and accepted one
@@takeUforward yep the github code is errorless! Thank you for the reply.
@@yogeshvaishnav7856 yes since i was typing live, might just have done a typo. Thanks.
us
Sir question link thoda ur chupa Kar rakh date
why don't we need trie class here?
Ask your viewers to click on youtube Icon/Text then only they would be able to see Like and comment option.
Bro you mentioned i and putting index i instead of j that was wrong bro
cfbr
"Understood"
**********Where r more opportunities for a tier 3 college guy(in terms of getting interview call) in well funded start ups or big MNCs***********
level up your DSA you will get interview calls from both.
Happy Coding :)
working code without trie if someone needs :
#include
int countDistinctSubstrings(string &s)
{
int ans = 0;
unordered_setst;
for( int i = 0 ; i < s.size() ;i++){
string temp = "";
for( int j = i ; j < s.size() ; j++){
temp +=s[j];
st.insert(temp);
}
}
return st.size()+1;
}
Understood!
understood
Understood
us
Understood!
Understood
Understood
understood
understood
understood
understood
Understood
understood
Understood
Understood
understood
Understood
Understood
understood
understood
understood
understood
understood
understood
understood
understood
us