Lexicographic rank of a string with duplicate characters
Last Updated :
29 Mar, 2024
Given a string s that may have duplicate characters. Find out the lexicographic rank of s. s may consist of lower as well as upper case letters. We consider the lexicographic order of characters as their order of ASCII value. Hence the lexicographical order of characters will be 'A', 'B', 'C', ..., 'Y', 'Z', 'a', 'b', 'c', ..., 'y', 'z'.
Examples:
Input : "abab"
Output : 2
Explanation: The lexicographical order is: "aabb", "abab", "abba", "baab", "baba", "bbaa". Hence the rank of "abab" is 2.
Input: "settLe"
Output : 107
Prerequisite: Lexicographic rank of a string
Method:
The method here is a little different from the without repetition version. Here we have to take care of the duplicate characters also. Let's look at the string "settLe". It has repetition(2 'e' and 2 't') as well as upper case letter('L'). Total 6 characters and the total number of permutations are 6!/(2!*2!).
Now there are 3 characters(2 'e' and 1 'L') on the right side of 's' which come before 's' lexicographically. If there were no repetition then there would be 3*5! smaller strings which have the first character less than 's'. But starting from position 0, till the end there are 2 'e' and 2 't'(i.e. repetitions). Hence, the number of possible smaller permutations with the first letter smaller than 's' are (3*5!)/(2!*2!).
Similarly, if we fix 's' and look at the letters from index 1 to end then there is 1 character('L') lexicographically less than 'e'. And starting from position 1 there are 2 repeated characters(2 'e' and 2 't'). Hence, the number of possible smaller permutations with first letter 's' and second letter smaller than 'e' are (1*4!)/(2!*2!).
Similarly, we can form the following table:

WorkFlow:
1. Initialize t_count(total count) variable
to 1(as rank starts from 1).
2. Run a loop for every character of the string, string[i]:
(i) using a loop count less_than(number of smaller
characters on the right side of string[i]).
(ii) take one array d_count of size 52 and using a
loop count the frequency of characters starting
from string[i].
(iii) compute the product, d_fac(the product of
factorials of each element of d_count).
(iv) compute (less_than*fac(n-i-1))/(d_fac).
Add it to t_count.
3. return t_count
C++
// C++ program to find out lexicographic
// rank of a string which may have duplicate
// characters and upper case letters.
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate factorial of a number.
long long fac(long long n)
{
if (n == 0 or n == 1)
return 1;
return n * fac(n - 1);
}
// Function to calculate rank of the string.
int lexRank(string s)
{
long long n = s.size();
// Initialize total count to 1.
long long t_count = 1;
// loop to calculate number of smaller strings.
for (int i = 0; i < n; i++)
{
// Count smaller characters than s[i].
int less_than = 0;
for (int j = i + 1; j < n; j++)
{
if (int(s[i]) > int(s[j]))
{
less_than += 1;
}
}
// Count frequency of duplicate characters.
vector<int> d_count(52, 0);
for (int j = i; j < n; j++)
{
// Check whether the character is upper
// or lower case and then increase the
// specific element of the array.
if ((int(s[j]) >= 'A') && int(s[j]) <= 'Z')
d_count[int(s[j]) - 'A'] += 1;
else
d_count[int(s[j]) - 'a' + 26] += 1;
}
// Compute the product of the factorials
// of frequency of characters.
long long d_fac = 1;
for (int ele : d_count)
d_fac *= fac(ele);
// add the number of smaller string
// possible from index i to total count.
t_count += (fac(n - i - 1) * less_than) / d_fac;
}
return (int)t_count;
}
// Driver Code
int main()
{
// Test case 1
string s1 = "abab";
cout << "Rank of " << s1 << " is: " << lexRank(s1)
<< endl;
// Test case 2
string s2 = "settLe";
cout << "Rank of " << s2 << " is: " << lexRank(s2)
<< endl;
return 0;
}
Java
// Java program to find out lexicographic
// rank of a String which may have duplicate
// characters and upper case letters.
class GFG {
// Function to calculate
// factorial of a number.
static long fac(long n)
{
if (n == 0 || n == 1)
return 1;
return n * fac(n - 1);
}
// Function to calculate
// rank of the String.
static int lexRank(String s)
{
long n = s.length();
// Initialize total count to 1.
long t_count = 1;
// loop to calculate
// number of smaller Strings.
for (int i = 0; i < n; i++)
{
// Count smaller
// characters than s[i].
long less_than = 0;
for (int j = i + 1; j < n; j++)
{
if (s.charAt(i)
> s.charAt(j))
{
less_than += 1;
}
}
// Count frequency of
// duplicate characters.
long[] d_count = new long[52];
for (int j = i; j < n; j++)
{
// Check whether the
// character is upper
// or lower case and
// then increase the
// specific element of
// the array.
if ((s.charAt(j) >= 'A')
&& s.charAt(j) <= 'Z')
d_count[s.charAt(j) - 'A'] += 1;
else
d_count[s.charAt(j) - 'a' + 26] += 1;
}
// Compute the product of the factorials
// of frequency of characters.
long d_fac = 1;
for (long ele : d_count)
d_fac *= fac(ele);
// add the number of smaller String
// possible from index i to total count.
t_count += (fac(n - i - 1)
* less_than) / d_fac;
}
return (int)t_count;
}
// Driver Code
public static void main(String[] args)
{
// Test case 1
String s1 = "abab";
System.out.print("Rank of " + s1
+ " is: " + lexRank(s1) + "\n");
// Test case 2
String s2 = "settLe";
System.out.print("Rank of " + s2
+ " is: " + lexRank(s2) + "\n");
}
}
// This code is contributed by gauravrajput1
Python3
# Python program to find out lexicographic
# rank of a string which may have duplicate
# characters and upper case letters.
# Function to calculate
# factorial of a number.
def fac(n):
if n == 0 or n == 1:
return 1
return n * fac(n - 1)
#Function to calculate
#rank of the String.
def lexRank(s):
n = len(s)
# Initialize total count to 1.
t_count = 1
for i in range(n):
less_than = 0
for j in range(i + 1, n):
if ord(s[i]) > ord(s[j]):
less_than += 1
d_count = [0] * 52
for j in range(i, n):
if ord(s[j]) >= ord('A') and ord(s[j]) <= ord('Z'):
d_count[ord(s[j]) - ord('A')] += 1
else:
d_count[ord(s[j]) - ord('a') + 26] += 1
d_fac = 1
for ele in d_count:
d_fac *= fac(ele)
t_count += (fac(n - i - 1) * less_than) // d_fac
return t_count
# Test case 1
s1 = "abab"
print("Rank of", s1, "is:", lexRank(s1))
# Test case 2
s2 = "settLe"
print("Rank of", s2, "is:", lexRank(s2))
C#
// C# program to find out
// lexicographic rank of a
// String which may have
// duplicate characters and
// upper case letters.
using System;
class GFG {
// Function to calculate
// factorial of a number.
static long fac(long n)
{
if (n == 0 || n == 1)
return 1;
return n * fac(n - 1);
}
// Function to calculate
// rank of the String.
static long lexRank(String s)
{
long n = s.Length;
// Initialize total
// count to 1.
long t_count = 1;
// loop to calculate number
// of smaller Strings.
for (long i = 0; i < n; i++)
{
// Count smaller characters
// than s[i].
long less_than = 0;
for (long j = i + 1; j < n; j++)
{
if (s[i] > s[j])
{
less_than += 1;
}
}
// Count frequency of
// duplicate characters.
long[] d_count = new long[52];
for (int j = i; j < n; j++)
{
// Check whether the character
// is upper or lower case and
// then increase the specific
// element of the array.
if ((s[j] >= 'A') && s[j] <= 'Z')
d_count[s[j] - 'A'] += 1;
else
d_count[s[j] - 'a' + 26] += 1;
}
// Compute the product of the
// factorials of frequency of
// characters.
long d_fac = 1;
foreach(long ele in d_count)
d_fac *= fac(ele);
// add the number of smaller
// String possible from index
// i to total count.
t_count += (fac(n - i - 1)
* less_than) / d_fac;
}
return t_count;
}
// Driver Code
public static void Main(String[] args)
{
// Test case 1
String s1 = "abab";
Console.Write("Rank of " + s1
+ " is: " + lexRank(s1) + "\n");
// Test case 2
String s2 = "settLe";
Console.Write("Rank of " + s2
+ " is: " + lexRank(s2) + "\n");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find out lexicographic
// rank of a String which may have duplicate
// characters and upper case letters.
// Function to calculate
// factorial of a number.
function fac(n)
{
if (n == 0 || n == 1)
return 1;
return n * fac(n - 1);
}
// Function to calculate
// rank of the String.
function lexRank(s)
{
n = s.length;
// Initialize total count to 1.
let t_count = 1;
// loop to calculate
// number of smaller Strings.
for (let i = 0; i < n; i++)
{
// Count smaller
// characters than s[i].
let less_than = 0;
for (let j = i + 1; j < n; j++)
{
if (s[i]
> s[j])
{
less_than += 1;
}
}
// Count frequency of
// duplicate characters.
let d_count = new Array(52);
for(let i=0;i<52;i++)
d_count[i]=0;
for (let j = i; j < n; j++)
{
// Check whether the
// character is upper
// or lower case and
// then increase the
// specific element of
// the array.
if ((s[j] >= 'A')
&& s[j] <= 'Z')
d_count[s[j].charCodeAt(0) - 'A'.charCodeAt(0)] += 1;
else
d_count[s[j].charCodeAt(0) - 'a'.charCodeAt(0) + 26] += 1;
}
// Compute the product of the factorials
// of frequency of characters.
let d_fac = 1;
for (let ele=0;ele< d_count.length;ele++)
d_fac *= fac(d_count[ele]);
// add the number of smaller String
// possible from index i to total count.
t_count += (fac(n - i - 1)
* less_than) / d_fac;
}
return t_count;
}
// Driver Code
let s1 = "abab";
document.write("Rank of " + s1
+ " is: " + lexRank(s1) + "<br>");
// Test case 2
let s2 = "settLe";
document.write("Rank of " + s2
+ " is: " + lexRank(s2) + "<br>");
// This code is contributed by patel2127
</script>
OutputRank of abab is: 2
Rank of settLe is: 107
Time complexity: O(n2)
Space complexity: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem