Open In App

JavaScript Program to Find Lexicographically Next String

Last Updated : 09 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Lexicographically next string in JavaScript. A lexicographically next string is the immediate string in a sorted order that comes after a given string when considering character sequences. It’s determined by rearranging characters to find the smallest change that results in a string greater than the given one.

Example:

Input : geeks
Output : geekt
The last character 's' is changed to 't'.

There are several methods that can be used to Lexicographically next string in JavaScript, which are listed below:

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using String.fromCharCode

in this approach, Using String.fromCharCode(), you can increment the last character of a string by converting its character code to the next character and handle wrap-around to ‘a’ if needed, returning the lexicographically next string.

Syntax:

String.fromCharCode(n1, n2, ..., nX)

Example: In this example, Convert the string ‘Geeks’ to an integer in base-36, increment it by 1, and then convert it back to a base-36 string to obtain ‘Geekt,’ the lexicographically next string.

Javascript




const str1 = 'Geekz';
let num = parseInt(str1, 36) + 1;
  
// Check if the last character is 'z' 
// and adjust the result accordingly
if (str1.slice(-1) === 'z') {
    // Subtract 26 to wrap around to 'a'
    num -= 26;
}
  
const result = num.toString(36);
console.log(result);


Output

geeka

Approach 2 : Using charCodeAt() and String.fromCharCode()

In this approach, we are using the charCodeAt() to get a character’s ASCII code, increment it, and convert it back to a character using String.fromCharCode(). This finds the lexicographically next string character.

Syntax:

str.charCodeAt(index)  //charCodeAt()
String.fromCharCode(n1, n2, ..., nX) //String.fromCharCode()

Example: In this example, the nextLexicographicString function takes an input string, iterates through its characters, and increments each character to find the lexicographically next string, handling wrap-around from ‘z’ to ‘a’ and ‘Z’ to ‘A.’

Javascript




function lexicographicString(str) {
    let arr = str.split('');
    for (let i = arr.length - 1; i >= 0; i--) {
        const charCode = arr[i].charCodeAt(0);
        arr[i] = charCode === 
            90 ? 'A' : charCode === 122 ? 'a' :
                String.fromCharCode(charCode + 1);
        if (arr[i] !== 'A' && arr[i] !== 'a') {
            return arr.join('');
        }
    }
    return arr.join('');
}
  
const inputStr = 'geeks';
const result = lexicographicString(inputStr);
console.log(result);


Output

geekt


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads