Find number of magical pairs of string of length L
Last Updated :
20 Jan, 2023
A pair of string s and r are called magical if for every index i the character of s is less than r i.e. s[i] < r[i]. The task is to count number of pairs of strings possible of length L. Since this value can be large, give answer modulo 109.
Note: The string contains only lowercase English alphabets.
Examples:
Input: L = 1
Output: 325
Since the length of the strings required is 1.
If s = “a” then r can be any one of “b”, “c”, “d”, … “z” (25 Possibilities)
If s = “b” then r can be any one of “c”, “d”, “e”, … “z” (24 Possibilities)
….
If s = “y” then r can only be “z” (1 Possibilities)
s cannot be “z” as it is the maximum lowercase character.
Hence total possibilities are 1 + 2 + 3 + … + 25 = 325
Input: L = 2
Output: 105625
Approach: For L = 1, total possibilities are 325.
For L = 2, total possibilities are 3252.
Total possibilities for any value of L will be 325L.
Since this value can be large, print the answer modulo 109.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int power( int x, unsigned int y, int p)
{
int res = 1;
x = x % p;
while (y > 0) {
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
int main()
{
int L = 2, P = pow (10, 9);
int ans = power(325, L, P);
cout << ans << "\n" ;
return 0;
}
|
Java
class GFG
{
static int power( int x, int y, int p)
{
int res = 1 ;
x = x % p;
while (y > 0 )
{
if (y % 2 == 1 )
{
res = (res * x) % p;
}
y = y >> 1 ;
x = (x * x) % p;
}
return res;
}
public static void main(String[] args)
{
int L = 2 ;
int P = ( int ) Math.pow( 10 , 9 );
int ans = power( 325 , L, P);
System.out.println(ans);
}
}
|
Python3
def power(x, y, p):
res = 1 ;
x = x % p;
while (y > 0 ):
if (y % 2 = = 1 ):
res = (res * x) % p;
y = y >> 1 ;
x = (x * x) % p;
return res;
L = 2 ; P = pow ( 10 , 9 );
ans = power( 325 , L, P);
print (ans);
|
C#
using System;
class GFG
{
static int power( int x, int y, int p)
{
int res = 1;
x = x % p;
while (y > 0)
{
if (y % 2 == 1)
{
res = (res * x) % p;
}
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static void Main()
{
int L = 2;
int P = ( int ) Math.Pow(10, 9);
int ans = power(325, L, P);
Console.WriteLine(ans);
}
}
|
PHP
<?php
function power( $x , $y , $p )
{
$res = 1;
$x = $x % $p ;
while ( $y > 0)
{
if ( $y & 1)
$res = ( $res * $x ) % $p ;
$y = $y >> 1;
$x = ( $x * $x ) % $p ;
}
return $res ;
}
$L = 2;
$P = pow(10, 9);
$ans = power(325, $L , $P );
echo $ans , "\n" ;
?>
|
Javascript
<script>
function power(x, y, p)
{
let res = 1;
x = x % p;
while (y > 0)
{
if (y % 2 == 1)
{
res = (res * x) % p;
}
y = y >> 1;
x = (x * x) % p;
}
return res;
}
let L = 2;
let P = Math.pow(10, 9);
let ans = power(325, L, P);
document.write(ans);
</script>
|
Time Complexity: O(log (L))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...