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.11
i is the starting index of the answer12
j is the pointer iterating through given string13
k is the offset to use when we find two substrings starting with the same character15
var lastSubstring = function (s) {19
while (j + k < s.length) {21
while (s[i + k] === s[j + k]) {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 < j28
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]33
// to ensure that i < j38
return s.substring(i);