
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Magical Pairs of String of Length L in C++
Suppose we have two strings str1 and str2, we have to find a number of magical pairs of length L. Two strings will be magical if for every index I, the str1[i] < str2[i]. We have to count a number of pairs since the number is very large, then return the answer using modulo 109. The strings will hold only lowercase letters.
The approach is simple. As we can see, if the length is L = 1, and index i = 1 is holding ‘a’, in str1 then index i = 1 of str2 will hold from ‘b’ to ‘z’ so 25 combination, for next character it will be 24 combinations, so it will be 25 + 24 + . . . + 1 = 325. Now for L = 2, it will be 3252. For length L, it will be 325L. If it is very large, then find modulus 109.
Example
#include<iostream> #include<cmath> using namespace std; int power(int a, unsigned int b, int mod) { int res = 1; a = a % mod; while (b > 0) { if (b & 1) res = (res * a) % mod; b = b >> 1; a = (a * a) % mod; } return res; } int main() { int L = 2, P = pow(10, 9); int res = power(325, L, P); cout << "Combinations: " << res << endl; }
Output
Combinations: 105625
Advertisements