Open In App

JavaScript Program to find Lexicographically next String

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads