Last Substring in Lexicographical Order LeetCode solution in JavaScript

1
// Second Solution
2
// Efficient
3
/*
4
The substring starting with the largest character is the answer. Hence we advance j and try to find the biggest character
5
while we use i to keep track of the current maximum string.
6
What if there is more than one largest character?
7
- we will need to compare both substrings starting with the largest character.
8
- (1) the substring with bigger next character is the answer.
9
- (2) if the shorter substring is exactly the same to the longer substring up to its end, the longer substring is the answer.
10

11
i is the starting index of the answer
12
j is the pointer iterating through given string
13
k is the offset to use when we find two substrings starting with the same character
14
*/
15
var lastSubstring = function (s) {
16
let i = 0,
17
j = 1,
18
k = 0;
19
while (j + k < s.length) {
20
k = 0;
21
while (s[i + k] === s[j + k]) {
22
k += 1;
23
if (j + k === s.length) break;
24
// if the shorter substring is exactly the same to the longer substring up to its end,
25
// the longer substring is the answer.
26
// hence, if j+k reaches the end, s.substring(i) will be the answer since we maintain i < j
27
}
28
if (s[i + k] > s[j + k]) {
29
j = j + 1 + k; // because there is no chance s[i+k] <= s[j+k]
30
} else if (s[i + k] < s[j + k]) {
31
i = i + 1 + k; // because there is no chance s[i+k] >= s[j+k]
32
}
33
// to ensure that i < j
34
if (i >= j) {
35
j = i + 1;
36
}
37
}
38
return s.substring(i);
39
// T.C: O(N)
40
// S.C: O(1)
41
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0