Skip to content

Commit 268f415

Browse files
committed
Runtime: 290 ms (Top 55.58%) | Memory: 13.9 MB (Top 85.26%)
1 parent 40a7d5d commit 268f415

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

scripts/algorithms/W/Word Ladder/Word Ladder.cpp

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1+
// Runtime: 290 ms (Top 55.58%) | Memory: 13.9 MB (Top 85.26%)
12
// For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s
23

3-
class Solution
4+
class Solution
45
{
56
public:
6-
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
7+
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
78
{
89
// 1. Create a set and insert all wordList to the set to have
9-
// easy search of O(1)
10+
// easy search of O(1)
1011
unordered_set<string> wordSet;
1112
bool isEndWordPresent = false;
1213
for (string s:wordList)
@@ -20,34 +21,34 @@ class Solution
2021
}
2122
wordSet.insert(s);
2223
}
23-
24+
2425
// 2. If endWord is not present in the wordList return
2526
if (!isEndWordPresent)
2627
{
2728
return 0;
2829
}
29-
30+
3031
// 3. Create a queue for BST insert the elements of currentlevel to the queue
31-
// currentLevel is defined as all the strings that can be reached from
32-
// all the strings of the previous string by just replacing one character
33-
// and the one-char-replaced-string is present in the wordSet / wordList
32+
// currentLevel is defined as all the strings that can be reached from
33+
// all the strings of the previous string by just replacing one character
34+
// and the one-char-replaced-string is present in the wordSet / wordList
3435
queue<string> q;
3536
q.push(beginWord);
3637
int level = 0; // every time all the strings at this level are processed increment it
37-
38+
3839
// 4. Loop through all the elements in the queue
3940
while (!q.empty())
4041
{
4142
level++;
4243
int numStringsInCurLevel = q.size();
43-
// loop through all the strings in this current level
44+
// loop through all the strings in this current level
4445
// and find out if destination can be reached before
4546
// jumping to the next level of strings added to the queue
4647
while (numStringsInCurLevel--)
4748
{
4849
string curStr = q.front();
4950
q.pop();
50-
51+
5152
for (int i=0; i<curStr.length(); i++)
5253
{
5354
string tempStr = curStr;
@@ -76,8 +77,8 @@ class Solution
7677
}
7778
}
7879
}
79-
}
80-
80+
}
81+
8182
// If we are here then we couldn't reach destination
8283
// even though the destination string is present in the wordList
8384
// there is no path from source to destination for the given rules

0 commit comments

Comments
 (0)