Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too, you don't 😞 Do follow me on Instagram: striver_79
@ayushpatel2171 Жыл бұрын
Honestly I feel that the hard part about this question was figuring out that it is a graph question. But since I was following the playlist I already knew that it is a graph question. Which is why upon looking the question the intuition came easily to me.
@ridj41 Жыл бұрын
naah since,src and dest pointers were there, it was easy to figure out it was a graph,but rest was difficult
@sahilbani70203 ай бұрын
How is this even a Graph problem?
@topgunn66832 жыл бұрын
Watching your lectures before the Google on-site interview
@harshdasila66802 жыл бұрын
if you got selected refer me too :)
@aryashjain78932 жыл бұрын
linkedln id dedo bhaiya XD
@gp70602 жыл бұрын
I have my google on-site next month.. want to discuss on prep so can we connect on LinkedIn ?
@shyren_more Жыл бұрын
how did it go?
@anonymousanonymous750711 ай бұрын
Ok Googler
@vaarigupta6332 Жыл бұрын
Instead of erasing the string from the set, you can take unordered_map and mark it as true which is generally used in BFS for marking visited nodes.
@infinityzero2321 Жыл бұрын
ya but that will unnecessarily increase the space complexity
@jagannathan1014 Жыл бұрын
Terrible idea as it not only increases SC , but also increases COLLISIONS leading to worst case in hashmap
@abhinavgupta704811 ай бұрын
@@jagannathan1014 can you please elaborate why it is a terrible idea and how will it increase collisions
@priyanshkumar176 ай бұрын
yeah you can do it too...
@Predator-pv7of4 ай бұрын
@@abhinavgupta7048 it is generally advised to not use unordered sets and maps, and due to collisions, the worst case time complexity to access elements becomes O(n)
@manasranjanmahapatra37292 жыл бұрын
Understood. Graph is slightly tough, but you are making it easy for us thank you🤘.
@prashantkashyap171 Жыл бұрын
For second time I was able to solve GFG hard problem on my own , such a nice teaching. Though I doubt if such approach would've hit, if it hadn't been a part of Graph series.
@tanya83532 ай бұрын
The patience with which you do dry run is really commendable!!!!🔥
@gorilla_coder-el6kf Жыл бұрын
thank you striver i was able to solve this problem on my own because of your graph playlist. heartiful thanks for this playlist.this is the best out there.
@arjunjadhav627510 ай бұрын
i just watched the logic you have used and i was able to write code by myself , Thanks..🙏
@anshjain56734 ай бұрын
I solved this question in the following way which gives me the time complexity of O(n*m). I basically created the graph using adj list method and performed normal BFS instead of checking words in the set after modifying each letter of word. class Solution { public: bool checkDiff(string a, string b){ int ptr=0, count=0; while(ptr!=a.size()){ if(a[ptr]==b[ptr]){ ptr++; continue; } ptr++; count++; } return count==1; } int ladderLength(string beginWord, string endWord, vector& wordList) { wordList.insert(wordList.begin(), beginWord); int n = wordList.size(); vector adj[n]; //Create undirected graph for(int i=0; i
@pramukhjain17422 ай бұрын
The graph creation will take time = (N^2)*M (where N is length of words array & M is length of longest word).
@sam_55555Ай бұрын
Thank you so much Striver for explaining problems in a very understandable way. Kudos to you for achieving lot at a very young age in the world of Top-tech
@manasvinsharma174010 ай бұрын
One more approach can be making the graph first & then finding the shortest path in it. We can make a graph where there will be a edge between all those nodes who differ by only 1 character. The graph creation will take time = (N^2)*M (where N is length of words array & M is length of longest word). Once graph is made we can apply BFS & also handle the case where target cannot reach.
@abhisheksen799010 ай бұрын
I was thinking the same way
@jyothiyadav259510 ай бұрын
i tried this but it says tle?? class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ def issimilar(s1,s2): if len(s1)!=len(s2): return False l=len(s1) flag=True for i in range(l): if s1[i]!=s2[i] and flag==False: return False if s1[i]!=s2[i]: flag=False return True if endWord in wordList: final=wordList.index(endWord) que=[] n=len(wordList) adj=[[] for _ in range(n)] visited=[0 for _ in range(n)] for i in range(n-1): for j in range(1,n): if issimilar(wordList[i],wordList[j]): adj[i].append(j) adj[j].append(i) for i in range(n): if issimilar(wordList[i],beginWord): que.append((i,2)) visited[i]=1 while que: v,dis=que.pop(0) if v==final: return dis for i in adj[v]: if visited[i]==0: que.append((i,dis+1)) visited[i]=1 return 0 can someone help??
@aruna586911 ай бұрын
Understood. You are brilliant in finding the suitable example to explain the algorithm....!! Thanks a lot🙌❤
@harshvaghani42834 ай бұрын
You gave me the confidence of solving a leetcode hard! The step by step explanation is wonderful!!
@santanu29 Жыл бұрын
I remember this problem came in Leetcode daily in Feb 2022. Just copied the code and did not understand anything. One year later I understood the code. Thank you for the explanation.
@priyanshkumar176 ай бұрын
excellent memory brother
@cinime2 жыл бұрын
Understood! What an excellent explanation as always, thank you very much!!
@anandkalpe21552 жыл бұрын
Hey @striver this solution is exceeding time limit in leetcode, so instead of assigning all letter from a-z , I tried with letters only in wordList and it worked. I just added below function to get all the letters into vector- private: vector letters(vector&wordList){ unordered_set st; vector result; for(auto it: wordList){ for(int i=0;i
@subratkumar73592 жыл бұрын
I wrote the same code and it didn't give TLE.
@aryashjain78932 жыл бұрын
Understood , a big fan of your zero typing errors !!!!! awesome video as always thank you sir ji
@QuantaBytes Жыл бұрын
Hey Striver !! Your Videos are reaallly really helpful, easy to understand, and hats off for your amazing work and efforts.
@AyushMishra-b8w11 ай бұрын
you can make any difficult question way too easy. Just loved your teaching style .😊😊😊😊
@tanujaSangwan2 ай бұрын
My approach is different: This can be visualised as an undirected weighted graph with unit weights. We can created graph with word as each node and all neighbours are the words with only one character changed. Then apply exact same BFS as we implement in the previous video. No code changes at all. Quite simple and passes all testcases. bool isAdjacent(const string& word1, const string& word2) { int diff = 0; for (int i = 0; i < word1.size(); ++i) { if (word1[i] != word2[i]) { diff++; if (diff > 1) return false; } } return diff == 1; } // Function to create the adjacency list graph unordered_map buildGraph(vector& wordList) { unordered_map graph; // Add an empty list for each word for (const string& word : wordList) { graph[word] = {}; } // Connect each word with its adjacent words for (int i = 0; i < wordList.size(); ++i) { for (int j = i + 1; j < wordList.size(); ++j) { if (isAdjacent(wordList[i], wordList[j])) { graph[wordList[i]].push_back(wordList[j]); graph[wordList[j]].push_back(wordList[i]); } } } return graph; } int wordLadderLength(string startWord, string targetWord, vector& wordList) { // If targetWord is not in the wordList, no valid transformation is possible if (find(wordList.begin(), wordList.end(), targetWord) == wordList.end()) { return 0; } // Include the startWord in the word list if it's not already there if (find(wordList.begin(), wordList.end(), startWord) == wordList.end()) { wordList.push_back(startWord); } // Build the graph from the word list unordered_map graph = buildGraph(wordList); // Perform BFS to find the shortest path unordered_map distance; for (const string& word : wordList) { distance[word] = INT_MAX; // Initialize distances with infinity } distance[startWord] = 1; queue q; q.push(startWord); while (!q.empty()) { string currentWord = q.front(); q.pop(); // Traverse all neighbors of the current word for (const string& neighbor : graph[currentWord]) { if (distance[neighbor] == INT_MAX) { // If not visited distance[neighbor] = distance[currentWord] + 1; q.push(neighbor); // If we reach the target word, return the distance if (neighbor == targetWord) { return distance[neighbor]; } } } } // If BFS completes without finding the targetWord, return 0 return 0; }
@manjotsingh81572 ай бұрын
can u share the code?
@divyareddy7622Ай бұрын
love it, just higher time complexity while building the graph--can go up to N^2
@tanujaSangwanАй бұрын
@@divyareddy7622 yeah
@SumitKeshariMCS Жыл бұрын
Bravo, amazing!! I was always afraid of this question. But you explained it sooooo well. Thanks a lot striver.
@sypher4735 Жыл бұрын
Yeah, it came out to be very simple.
@harishchoudhary9662 Жыл бұрын
It took me around one day to solve these question using my method but in the end it got TLE on leetcode and now after seeing the solution the questions seems easy.
@rajatsaraf237 Жыл бұрын
Thanks striver, Was able to solve it by myself although my approach was different from this, I considered every node has a edge to every other node and each edge has a weight equal to the difference b/w the 2 vertices(words) Then just used the shortest distance for an undirected graph using BFS algo
@arjunrai8126 Жыл бұрын
By node you mean the words right
@rajatsaraf237 Жыл бұрын
@@arjunrai8126 yes
@arjunrai8126 Жыл бұрын
@@rajatsaraf237 by difference bw the words you mean the number of positions where the chars are different , right? Great solution
@rajatsaraf237 Жыл бұрын
@@arjunrai8126 yes, that char difference can be considered as the weight b/w two words
@rishabhinc2936 Жыл бұрын
W bro
@mahipatel96722 ай бұрын
Happy Teacher's day to you. You have helped so many of us to get their DSA concepts right. Kudos to you and thanks a lot :)
@niteshbaith635011 күн бұрын
Your explanation is brilliant, bro!!
@gugli282 ай бұрын
Simple bruteForce can be : for each element(say "hit") in list, compare it with the all other elements. If the only 1 char varies that we can add as part of adjacency List of "hit" and so on.
@deepakagrawal7687 Жыл бұрын
we can create graph from the word list and do topological sort on it. that will give only limited characters that exists in word list and we can try out replacing characters present in word list only. with topological sort the we get array as h,d,l,c,o,t,g. Now I know before o I have 4 characters to try for first place i.e. h,d,l,c. then for g I have 2 characters o and t with same BFS algoritm we can avoid trying out all a-z combination and also it makes sense logically because after transformation if word should be from word list then try out with characters that are only in wordlist. if z is not present in wordlist in any word why to try out with that. Considering if there is no cycle in it. This needs to be asked to interviewer whether there will be cycle in the graph. If cycle exists then the other approach is to iterate through all the wordlist and put them in set. Atleast you will be comparing less characters then a-z
@stith_pragya11 ай бұрын
Thank You So Much for this wonderful video..........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@ITSuyashTiwariАй бұрын
your explanation made it too easy🤗
@mriduljain6809 Жыл бұрын
Was able to solve the problem on my own only because of you...Thank U😊😊 Understood Bhaiya..
@_lifestylefusion6 ай бұрын
Very clear explanation. Hats off to your effort .
@yashveernathawat81545 ай бұрын
For string set.find() method takes O(N) instead of logn.... It increases the complexity
@KratosProton2 жыл бұрын
Understood, quality content!
@gutkaganggaming2 жыл бұрын
The other way we can do is Instead of making combination from current word Just check if we can make current word from any word present in the word list.
@parallax8916 Жыл бұрын
Briliiantly explained When I read the question for the first time, I was so scared and I had no clue how to proceed. I was thing of sets and recursion but I did not even try coz Iwas scared. But u made it soo simple that after watching half of the video, I did it in 1 go . U r amazing striver. please continue to bring such playlists , its so helpful
@priyanshkumar176 ай бұрын
were you thinking about backtracking too in first go?
@studynewthings17277 ай бұрын
understood. Able to write the code by myself after getting the intuition.
@psydook4 ай бұрын
once i knew it was a graph question, i tried this myself : class Solution { private: bool check(const string& w1, const string& w2) { int differences = 0; for (int i = 0; i < w1.length(); ++i) { if (w1[i] != w2[i]) { differences++; if (differences > 1) return false; } } return true; } public: int ladderLength(string beginWord, string endWord, vector& wordList) { bool possible = false; int index = -1; for (int i = 0; i < wordList.size(); i++) { if (wordList[i] == endWord) { index = i; possible = true; break; } } if (!possible) return 0; wordList.insert(wordList.begin(), beginWord); int n = wordList.size(); vector adj(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (check(wordList[i], wordList[j])) { adj[i].push_back(j); adj[j].push_back(i); } } } vector distance(n, INT_MAX); queue q; q.push({0, 0}); distance[0] = 0; while (!q.empty()) { int node = q.front().first; int dist = q.front().second; q.pop(); for (int val : adj[node]) { if (distance[val] > dist + 1) { distance[val] = dist + 1; q.push({val, dist + 1}); } } } if (distance[index + 1] < INT_MAX) return distance[index + 1] + 1; return 0; } };
@Sara-ed3jq Жыл бұрын
Best series on graph
@yasaswinikarumuri95902 жыл бұрын
Such a great explanation! Please continue the playlist
@Engineer_Padai Жыл бұрын
thanks striver bhai, for this awesome series
@senvikas19462 жыл бұрын
I did like and kya hi samjhate ho yrr bhaiya, maza hi aa gaya. UNDERSTOOD
@sukhpreetsingh5200 Жыл бұрын
excellent explanation as always, thank you very much!! Amazing playlist
@kaichang81862 ай бұрын
understood, thanks for the detail explanation
@priyanshkumar176 ай бұрын
One can figure out that it was a graph question by looking at src & dest strings, & shortest sequence of transformations were asked...So, some 'feeling' of shortest path from src (beginWord) to dest (endWord) comes...
@gauravgupta72804 күн бұрын
A Small Optimization Can be MADE further ... So currently, for each index of the string we are traversing 26 times representing 26 characters / alphabets in the English Dictionary. But what if we exactly store the possible set of characters that are only available in wordList. There comes the optimization where we store set of all alphabets for each index & always iterate those in the while loop of queue.
@charan775Ай бұрын
another approach is to use bi-directional BFS. same time complexity but half the runtime
@empvaibhav97995 ай бұрын
Instead of converting str to all the possible strings we can simply compare str with all the strings in word_List and see if the difference btw them is 1 or less and if so then add in queue to do BFS.
@harleenkaur7751 Жыл бұрын
Thanks a lot, Striver. Best explanation . 😀
@vatsalvasoya5243 Жыл бұрын
Understood!! Very well explained!!!
@Health_asset Жыл бұрын
best method to solve this question 😁thanks striver I got your algo and tried myself , just make a little mistake but it was corrected bcoz of your code
@user-rf3he9uv5m Жыл бұрын
UNDERSTOOD striver!
@techatnyc73202 ай бұрын
Great work, Raj!
@pradhuman_ramawat Жыл бұрын
I have a different solution, i created a graph representation using adjacency list (word is the key, words it can transform into are list values), then applied shortest distance method using dijkstra's algorithm.
@AnushkaVijay-cv7tk Жыл бұрын
can u please share your code....im having difficulty in making adjacency list
@harshdiwase19415 ай бұрын
this question was amazing , thanks striver
@breakthecode83232 жыл бұрын
Striver, thank you so much for graph series, per please can you also make series on segement trees, tried learning from so many places, but nowhere satisfactory content is found, bana do na ek series please
@disciplines4 Жыл бұрын
thanks striver for such wonderful explanation.
@amanasrani64057 ай бұрын
yours HArdwork is really ❤
@Amitkumar-nk5mo Жыл бұрын
understood....your explainations are lucid ....keep up the good work...
@mohammadkaif8143 Жыл бұрын
Hi, awesome video. Just add one base condition to handle this case, according to your code it will give 1 but it should return 0.. 1 der der der
@rushikeshg252 жыл бұрын
Thank you for such a wonderful Explanation !!!!
@1tav02 жыл бұрын
understood! amazing like always.
@shreycpaunwala14205 ай бұрын
Hey Striver! Understood the concept thoroughly. Had one doubt, my first intuition was to use DP in this question instead of graph. SO why graph is more optimal then dp?
@brokegod58714 ай бұрын
1) The question has a source to destination pattern, it's guiding you a path that you start from this word and end somewhere... This intends graph... Also they are saying "shortest" while giving you source and destination so you should think of shortest path algorithm 2) Reason why you thought of Recursion/DP is because we are trying every letter combination which is fair to think but you apply DP when you have a vast search space and you have no clue which can be the answer but here they've given you the dictionary list so they are telling you the search space
@GM-rw5fl Жыл бұрын
How u make the hard question like a cake work amazing brother ......
@devangsingh29502 жыл бұрын
One different approach is make a graph with edges between hit and hot, hot and dot, hot and dot, hot and lot, .... And now you have to find the shortest distance between two points (beginWord and endWord) using BFS.
@priyanshkumar176 ай бұрын
Yeah
@raghavmanish246 ай бұрын
thnaku striver ...you are making my carrir
@rishavkumar2182 Жыл бұрын
great explanation!!
@nagame859 Жыл бұрын
really don't understand why this is marked as "hard", this is one of the easiest problems, and it can also be considered as tree too.. regardless.. thank you Striver❤
@pratikshadhole6694 Жыл бұрын
GOAT❤ you are great striver
@sambhavagarwal58712 жыл бұрын
Understood! What an excellent explanation as always, thank you very much!! Amazing playlist thanks striver is this playlist is completed or not please confirm
@takeUforward2 жыл бұрын
It will have more videos.
@sambhavagarwal58712 жыл бұрын
Can u please upload fast
@vikas75884 ай бұрын
It's a high time youtube should add a super like button.
@aditikumari82042 жыл бұрын
understood..thanks bhaiya
@anchaldevrani2055 Жыл бұрын
Understood 🎉
@ultimatecreed5144 Жыл бұрын
is use of unorderedmap better of unordered set and why??
@_hulk748 Жыл бұрын
Understood sir thankyou sir❤🙏🙇♂️
@sakethkumarpeddi20895 ай бұрын
Great explanation. But, can anyone confirm me that we can also get this problem done by using DFS right? By creating the adjacency list to backtrack again when particular node's dfs is over. I know this will take more time and space, but I want to know whether we can achieve this by doing DFS or not?
@AyushSingh-fu1yp8 ай бұрын
The hard part about the question is to figure out that it is a graph question, otherwise, doesn't have any substance.
@a2_63_vimalmishra92 жыл бұрын
At instead of set i have used map O(1) in every case : )
@priyanshkumar176 ай бұрын
there can be collisions in a hashmap
@DharnaMittal-vz9fi5 ай бұрын
Striver you are the best
@abhishek__anand__ Жыл бұрын
Nicely Explained
@ayushmaanpandey52335 ай бұрын
one doubt : why don't we replace the char of the word string with the respective char withthe same index of string present in the set, not from the 26 alphabet???.it will save time if give wordlist length is less than 26 otherwise above code is okay
@nirupamkumar6760 Жыл бұрын
very nice explanation
@sherlockholmes16052 жыл бұрын
Amazing explanation and logic! kuch bhi bolo, Striver bhai is built different!
@lethalgaming7087 Жыл бұрын
Here is the Java Implementation: class Solution { static class Pair { String st; int step; Pair(String st, int pair) { this.st=st; this.step=pair; } } public int wordLadderLength(String startWord, String targetWord, String[] wordList) { Set set=new HashSet(); for(String s:wordList) set.add(s); set.remove(startWord); Deque q=new ArrayDeque(); q.add(new Pair(startWord,1)); while(!q.isEmpty()) { Pair p=q.pollFirst(); char[] word=p.st.toCharArray(); int step=p.step; if(p.st.equals(targetWord)) return step; for(int i=0;i
@anshumansingh27152 жыл бұрын
As mentioned in question "startWord may or may not be part of the wordList" but in code of C++ at line 13, you delete it every time without searching whether it is there or not, and still your code is running fine. can you pls state the reason for that? @striver
@AB-yl5sz2 жыл бұрын
set.erase() function returns 1 if it deletes the element from set or return 0 if element doesn't present in set. So no error and code runs fine
@LBK3 Жыл бұрын
understood ❤
@GoodLuck-dv2zu2 жыл бұрын
As always AMAZING!
@Siddhartha_Bose5 ай бұрын
one of the toughest question in this playlist
@jaishriharivishnu5 ай бұрын
no, just because in starting he said tough, doesn't make it tough. Just usual BFS question.
@KratosProton2 жыл бұрын
Great explaination
@srujanveshkotha7286 Жыл бұрын
brute force approach using simple recursion: class Solution { public int wordLadderLength(String startWord, String targetWord, String[] wordList) { Set set = new HashSet(); for(String s : wordList) { set.add(s); } List stepList = new ArrayList(); wordLadderLength(startWord, targetWord, wordList,set,startWord,0,stepList); int ans=1000000000; for(int i=0;i
@udaytewary3809 Жыл бұрын
Understood bhaiya
@arjunbajpai3514 Жыл бұрын
If we have an unordered set of strings and suppose we have to search for a particular string in it what will the complexity be ... is it constant or order of string length? Kindly confirm.
@UECAshutoshKumar Жыл бұрын
Thank you sir
@sumanthreddy76707 ай бұрын
can this be done using DFS approach instead of BFS?
@AppaniMadhavi5 ай бұрын
It means the brute is the optimised right??
@2000UK-v8c6 ай бұрын
Kudos to you sir!!
@MMNayem-dq4kd Жыл бұрын
Understood,sir.
@akuma_1682 ай бұрын
what if we first arrived at odisha by following the 2nd path instead of first?
@DevashishJose9 ай бұрын
understood, Thank you.
@vijayanks17146 ай бұрын
Watching your lecture before the Meta phone screen round