VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographic-rank-of-a-string-among-all-its-substrings/

⇱ Lexicographic rank of a string among all its substrings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographic rank of a string among all its substrings

Last Updated : 15 Jul, 2025

Given string str, the task is to find the rank of the given string among all its substrings arranged lexicographically.

Examples:

Input: S = "enren"
Output: 7
Explanation:
All the possible substrings in the sorted order are {"e", "e", "en", "en", "enr", "enre", "enren", "n", "n", "nr", "nre", "nren", "r", "re", "ren"}.
Therefore, the rank of the given string "enren" is 7.

Input: S = "geeks"
Output: 12
Explanation:
All possible substrings in the sorted order are {"e", "e", "ee", "eek", "eeks", "ek", "eks", "g", "ge", "gee", "geek", "geeks", "k", "ks", "s"}.
Therefore, the rank of the given string "geeks" is 12.

Approach: Follow the steps below to solve the problem:

  1. Initialize an array arr[] of vectors of length 26 to store the indices of the characters present in the string and rank as 0.
  2. Store the indices of each character. Indices of a will be stored in arr[0], for b, arr[1] will store all its indices, and so on.
  3. Traverse each index stored in the array arr[] up to the characters which are smaller than the first character of the string S.
  4. For each index i, total substrings starting from that index is N - i. Add N - i to rank as all characters with these indices are smaller.
  5. Now, after traversing, store all the substrings starting from the first character of S and sort those substrings in lexicographical order.
  6. Traverse the sorted substrings and compare each substring with the string S and increment the rank until substring equals to S is found.
  7. Print the value of rank + 1 to get the rank of the given string.

Below is the implementation of the above approach:


Output: 
7

Time Complexity: O(N3)
Auxiliary Space: O(N)

Comment