Javatpoint Logo
Javatpoint Logo

Lexicographic rank of a String in C++

In this article, we will discuss the lexicographic rank of a string in C++. But before going to its implementation, we must know about the Lexicographic.

Lexicographic or lexicographical ordering (commonly referred to as alphabetical or dictionary arranging) is the organization of words according to the alphabetical order of each component letter.

Problem statement:

Find the rank of a string str among all its modifications when sorted lexicographically.

Example:

Explanation: If all the given string's permutations are organized lexicographically, they will look like "abc", "acb", "bac", "bca", "cab", and "cba". It is clear from this that the rank of the string is 5.

The naive approach is to produce all the permutations in lexicographic sequence and save the rank of the current string. Check if the created permutation matches the input string and return the rank of the string.

Algorithm

Filename: StringOrder.cpp

Output:

2617

Using the permutation concept, compute the lexicographic rank of a String:

The problem can be solved using the concept of permutation, which is based on the following idea:

Determine how many lexicographically smaller strings may be created when all characters up to that index are fixed. It will return the strings that are smaller than that, and we will be able to determine the rank.

To put the concept into practice, take the following actions:

  • Iterate through the string from i = 0 to the length of the string:
  • Determine the number of characters that are less than the current character.
  • Calculate the number of lexicographically smaller strings.
  • Add that value to the rank.
  • Finally, multiply 1 by rank and return the result as the required answer.

Filename: StringOrder2.cpp

Output:

2617

A String's lexicographic rank in linear time:

The solution follows the same logic as the preceding technique. The time complexity can be decreased by establishing an auxiliary array of size 256. Let's create an array that stores the total number of characters in the string that are less than the ith character and update it following each index of the given string during string iterations.

Filename: StringRank.cpp

Output:

The rank of the string is 2617

Complexity:

Time Complexity: O(N)

Space Complexity: O(1)







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA