JavaScript Program to Find Lexicographically Next String
Last Updated :
09 Oct, 2023
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.
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;
if (str1.slice(-1) === 'z' ) {
num -= 26;
}
const result = num.toString(36);
console.log(result);
|
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);
|
Share your thoughts in the comments
Please Login to comment...