JavaScript Program to Find Lexicographically Next String
Last Updated :
31 May, 2024
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;
// 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);
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);
Approach 3: Using Character array and Sorting
The nextLexicographicString function generates the lexicographically next string from the input string. It iterates through the characters, finding the rightmost character to replace with a smaller one to its right. If found, it swaps this character with the smallest greater character to its right and sorts the remaining characters to the right. This ensures the smallest lexicographically greater string. If no character is found, it returns the input string.
Example:
JavaScript
function nextLexicographicString(str) {
const charArray = str.split('');
let index = -1;
// Find the rightmost character to replace
for (let i = charArray.length - 2; i >= 0; i--) {
if (charArray[i] < charArray[i + 1]) {
index = i;
break;
}
}
// If no such character is found, return the input string itself
if (index === -1) return str;
// Find the smallest character to the right of index that is greater than charArray[index]
let smallestGreater = charArray.length - 1;
while (charArray[smallestGreater] <= charArray[index]) {
smallestGreater--;
}
// Swap the characters at index and smallestGreater
[charArray[index], charArray[smallestGreater]] = [charArray[smallestGreater], charArray[index]];
// Sort the characters to the right of index in ascending order
const remaining = charArray.splice(index + 1);
remaining.sort();
charArray.push(...remaining);
return charArray.join('');
}
const inputStr = 'geeks';
const result = nextLexicographicString(inputStr);
console.log(result);
Similar Reads
JavaScript Program to find Lexicographically next String 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 : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
JavaScript Program to Compare Two Strings Lexicographically This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings. The program should return a positive value if the first st
2 min read
JavaScript Program to Find Kâth Non-Repeating Character in String The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
JavaScript Program for Printing Shortest Common Supersequence A Shortest Common Supersequence (SCS) is the shortest or smallest string that contains two given strings as a subsequence. It is a minimal combination of characters that includes all elements of both input strings. In this article, we will see different approaches for printing the shortest common su
8 min read
JavaScript Program to Search a Word in a 2D Grid of Characters In this article, we will solve a problem in which you are given a grid, with characters arranged in a two-layout(2D). You need to check whether a given word is present in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match
7 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching Given a set of strings, find the longest common prefix. Examples:Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- âgeeksforgeeksâ and âgeeksâ. What is the longest common prefix in
3 min read