Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Find Lexicographically Next String
Next article icon

JavaScript Program to Find Lexicographically Next String

Last Updated : 31 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
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:

Table of Content

  • Using String.fromCharCode
  • Using charCodeAt() and String.fromCharCode()

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 

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

Output
geesk 



Next Article
JavaScript Program to Find Lexicographically Next String

K

kohliami558i
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences