Lexicographic rank of a Binary String


In this article, we will explore an intriguing problem that involves binary strings and lexicographic ordering. Our task is to find the lexicographic rank of a given binary string. We'll demonstrate our solution using C++, a popular programming language known for its efficiency and flexibility.

Understanding Lexicographic Ordering

Lexicographic or lexicographical ordering (also known as alphabetical or dictionary ordering) refers to the arrangement of words based on the alphabetical order of their component letters.

Problem Statement

Given a binary string, we need to determine its lexicographic rank among all its permutations. The lexicographic rank of a string is its position in the set of all permutations of that string when they are listed in lexicographic order.

Solution Approach

Our approach involves these key steps −

  • Initialize Count  Initialize a counter to store the number of ones ('1's) in the binary string.

  • Rank Calculation  Iterate through the binary string from left to right. If the current character is '1', calculate its rank using the combination formula, decreasing the counter for each subsequent '1'.

  • Return Result  The result will be the lexicographic rank of the binary string.

C++ Implementation

Example

The following C++ code outlines our solution −

#include <bits/stdc++.h>
using namespace std;

// Function to calculate factorial
int fact(int n) {
   int res = 1;
   for (int i = 1; i <= n; i++)
      res *= i;
   return res;
}

// Function to find lexicographic rank of a binary string
int lexRank(string str) {
   int rank = 1;
   int onesCount = count(str.begin(), str.end(), '1');
   
   for (char c : str) {
      if (c == '1') {
         onesCount--;
         rank += fact(onesCount);
      }
   }
   
   return rank;
}

int main() {
   string str = "110";
   
   int result = lexRank(str);
   cout << "Lexicographic rank of the binary string: " << result << endl;
   
   return 0;
}

Output

Lexicographic rank of the binary string: 3

Explanation

Consider the binary string 

str = "110"

The permutations of this binary string are: "011", "101", "110". In lexicographic order, these permutations are: "011", "101", "110".

The rank of the binary string "110" is 3, which is the output of our program.

Conclusion

The problem of finding the lexicographic rank of a binary string is a fascinating one that builds upon our understanding of binary strings, permutations, and lexicographic order. This solution, implemented in C++, demonstrates how we can use basic programming constructs to solve it effectively.

Updated on: 18-May-2023

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements