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
  • DSA
  • Practice Combinatorics
  • MCQs on Combinatorics
  • Basics of Combinatorics
  • Permutation and Combination
  • Permutation Vs Combination
  • Binomial Coefficient
  • Calculate nPr
  • Calculate nCr
  • Pigeonhole Principle
  • Principle of Inclusion-Exclusion
  • Catalan Number
  • Lexicographic Rank
  • Next permutation
  • Previous Permutation
Open In App
Next Article:
C++ Program for Generating Lyndon words of length n
Next article icon

C++ Program for Generating Lyndon words of length n

Last Updated : 18 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Given an integer n and an array of characters S, the task is to generate Lyndon words of length n having characters from S.
A Lyndon word is a string which is strictly less than all of its rotations in lexicographic order. For example, the string "012" is a Lyndon word as it is less than its rotations "120" and "201", but "102" is not a Lyndon word as it is greater than its rotation "021". Note: "000" is not considered to be a Lyndon word as it is equal to the string obtained by rotating it.
Examples:
Input: n = 2, S = {0, 1, 2} Output: 01 02 12 Other possible strings of length 2 are "00", "11", "20", "21", and "22". All of these are either greater than or equal to one of their rotations. Input: n = 1, S = {0, 1, 2} Output: 0 1 2
Approach: There exists an efficient approach to generate Lyndon words which was given by Jean-Pierre Duval, which can be used to generate all the Lyndon words upto length n in time proportional to the number of such words. (Please refer to the paper "Average cost of Duval’s algorithm for generating Lyndon words" by Berstel et al. for the proof) The algorithm generates the Lyndon words in a lexicographic order. If w is a Lyndon word, the next word is obtained by the following steps:
  1. Repeat w to form a string v of length n, such that v[i] = w[i mod |w|].
  2. While the last character of v is the last one in the sorted ordering of S, remove it.
  3. Replace the last character of v by its successor in the sorted ordering of S.
For example, if n = 5, S = {a, b, c, d}, and w = "add" then we get v = "addad". Since 'd' is the last character in the sorted ordering of S, we remove it to get "adda" and then replace the last 'a' by its successor 'b' to get the Lyndon word "addb".
Below is the implementation of the above approach: C++
// C++ implementation of  // the above approach  #include<bits/stdc++.h> using namespace std;  int main() {     int n = 2;     char S[] = {'0', '1', '2' };     int k = 3;     sort(S, S + 3);          // To store the indices      // of the characters      vector<int> w;     w.push_back(-1);          // Loop till w is not empty          while(w.size() > 0)     {                  // Incrementing the last character         w[w.size()-1]++;         int m = w.size();         if(m == n)         {             string str;             for(int i = 0; i < w.size(); i++)             {                 str += S[w[i]];             }             cout << str << endl;         }              // Repeating w to get a          // n-length string         while(w.size() < n)         {             w.push_back(w[w.size() - m]);         }              // Removing the last character          // as long it is equal to          // the largest character in S          while(w.size() > 0 && w[w.size() - 1] == k - 1)         {             w.pop_back();         }     }     return 0; }  // This code is contributed by AdeshSingh1 
Output:
  01  02  12  
Please refer complete article on Generating Lyndon words of length n for more details!

Next Article
C++ Program for Generating Lyndon words of length n

K

kartik
Improve
Article Tags :
  • Strings
  • Combinatorial
  • Technical Scripter
  • C++ Programs
  • C++
  • DSA
  • Technical Scripter 2018
  • rotation
Practice Tags :
  • CPP
  • Combinatorial
  • Strings

Similar Reads

    C++ Program to Print the First Letter of Each Word of a String
    String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. Examples: Input: str = "geeks for geeks" Output: gfg Input: str = "happy coding" Out
    4 min read
    C++ Program To Print Continuous Character Pattern
    Here we will build a C++ Program To Print Continuous Character patterns using 2 different methods i.e: Using for loopsUsing while loopsInput: rows = 5Output: A B C D E F G H I J K L M N O 1. Using for loopApproach 1: Assign any character to one variable for the printing pattern. The first for loop i
    5 min read
    Program to generate random alphabets
    Prerequisite : rand() and srand() Given all alphabets in a character array, print a string of random characters of given size.We will use rand() function to print random characters. It returns random integer values. This number is generated by an algorithm that returns a sequence of apparently non-r
    4 min read
    Iterative program to generate distinct Permutations of a String
    Given a string str, the task is to generate all the distinct permutations of the given string iteratively. Examples: Input: str = "bba" Output: abb bab bba Input: str = "abc" Output: abc acb bac bca cab cba Approach: The number of permutations for a string of length n are n!. The following algorithm
    15+ min read
    Program to print reverse character bridge pattern
    For a given value N, denoting the number of Charters starting from the A, print reverse character bridge pattern.Examples : Input : n = 5 Output : ABCDEDCBA ABCD DCBA ABC CBA AB BA A A Input : n = 8 Output : ABCDEFGHGFEDCBA ABCDEFG GFEDCBA ABCDEF FEDCBA ABCDE EDCBA ABCD DCBA ABC CBA AB BA A A Recomm
    5 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