JavaScript Program to find Lexicographically next String
Last Updated :
13 Sep, 2023
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.
Examples:
Input : test
Output : tesu
Explanation : The last character 't' is changed to 'u'.
Input : xyz
Output : xzz
Explanation : Since we can't increase last character,
we increment previous character.
Input : z
Output : za
Explanation : If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the end.
Otherwise we find first character from end which is not z and increment it.
Approach
- If the input string s is empty, it returns “a” as the next word.
- It finds the rightmost character in the string that is not ‘z’.
- If all characters in the string are ‘z’, it appends ‘a’ at the end.
- If there are non-‘z’ characters in the string, it increments the rightmost non-‘z’ character by one.
Example: This example shows the implementation of the above mentioned approach.
Javascript
function nextWord(s) {
if (s == "" )
return "a" ;
let i = s.length - 1;
while (s[i] == 'z' && i >= 0)
i--;
if (i == -1)
s = s + 'a' ;
else
s[i] = String.fromCharCode(s[i]
.charCodeAt(0) + 1);
return s.join( '' );
}
let str = "abcd" .split( '' );
console.log(nextWord(str));
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...