

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Maximum Length Chain of Pairs
- C++ program to find number of l-r pairs for which XORed results same as summation
- Maximum Length Chain of Pairs in C++
- Magical String in C++
- Program to find number of good pairs in Python
- Program to find position of first event number of line l of a triangle of numbers in Python
- Magical String: Question in JavaScript
- Find length of a string in python (3 ways)
- Find length of longest subsequence of one string which is substring of another string in C++
- Nth Magical Number in C++
- Program to find out the number of pairs of equal substrings in Python
- Program to find length of concatenated string of unique characters in Python?
- C++ Program to Find the Length of a String
- C program to find the length of a string?
- Program to find max number of K-sum pairs in Python
Advertisements