JavaScript Program to find Lexicographically next String
Last Updated :
29 Aug, 2024
Improve
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.
function nextWord(s) {
// If string is empty.
if (s == "")
return "a";
// Find first character from right
// which is not z.
let i = s.length - 1;
while (s[i] == 'z' && i >= 0)
i--;
// If all characters are 'z', append
// an 'a' at the end.
if (i == -1)
s = s + 'a';
// If there are some non-z characters
else
s[i] = String.fromCharCode(s[i]
.charCodeAt(0) + 1);
return s.join('');
}
// Driver code
let str = "abcd".split('');
console.log(nextWord(str));
Output
abce
Time Complexity: O(n)
Auxiliary Space: O(1)
String Manipulation Without Conversion
Idea: Process the string from the end to the start, and handle cases where characters are 'z' by incrementing and managing the carry over.
Steps:
- Process the String from End to Start: Traverse the string from the rightmost character to the leftmost.
- Handle 'z' Characters: If a 'z' is found, change it to 'a' and move to the next character to the left.
- Increment Non-'z' Characters: Once a non-'z' character is found, increment it by one and terminate further processing.
- Append 'a' if All Characters are 'z': If the string consists entirely of 'z's, append an 'a' at the end.
Example:
function nextWord(s) {
let str = s;
let arr = [...str];
let n = arr.length;
// Start from the end of the string
for (let i = n - 1; i >= 0; i--) {
if (arr[i] === 'z') {
// Change 'z' to 'a'
arr[i] = 'a';
} else {
// Increment the character and exit
arr[i] = String.fromCharCode(arr[i].charCodeAt(0) + 1);
return arr.join('');
}
}
return 'a' + arr.join('');
}
let str = "abcz";
console.log(nextWord(str));
Output
abda