Print all distinct circular strings of length M in lexicographical order in C++

In this problem, we are given a string and an integer M. our task is to print all distinct circular strings of length M in lexicographical order (alphabetical order).

Let’s take an example to understand the problem,

Input: str= “ssssn” M=3
Output: nss sns ssn sss

Explanation − all possible circular strings of length 3 are: sss sss ssn sns nss. Distinct elements in lexicographical order are sss ssn sns nss.

To solve this problem, we will iterate over the elements of the string and generate all possible substrings of length M. we will store this generated string in a set that stores distinct elements only and discards duplicates. It will store these elements in a lexicographical order. Print all elements of the set from the beginning.

This algorithm will depend on both the size of the substring and the length of a string. Time complexity = O(N*M).


This code shows the implementation of our solution −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printCircularString(string s, int l, int m) {
   set<string> circularString;
   s = s + s;
   for (int i = 0; i < l; i++) {
      circularString.insert(s.substr(i, m));
   while (!circularString.empty()) {
int main() {
   string str = "ssssn";
   int N = str.length();
   int M = 3;
   cout<<"All circular strings of length "<<M<<" from the string '"<<str<<"' are:\n";
   printCircularString(str, N, M);
   return 0;


All circular strings of length 3 from the string 'ssssn' are −
nss sns ssn sss