Find the count of M character words which have at least one character repeated
Given two integers N and M, the task is count the total words of M character length formed by the given N distinct characters such that the words have at least one character repeated more than once.
Examples:
Input: N = 3, M = 2
Output: 3
Suppose the characters are {‘a’, ‘b’, ‘c’}
All 2 length words that can be formed with these characters
are “aa”, “ab”, “ac”, “ba”, “bb”, “bc”, “ca”, “cb” and “cc”.
Out of these words only “aa”, “bb” and “cc” have
at least one character repeated more than once.
Input: N = 10, M = 5
Output: 69760
Approach:
Total number of M character words possible from N characters, total = NM.
Total number of M character words possible from N characters where no character repeats itself, noRepeat = NPM.
So, total words where at least a single character appear more than once is total – noRepeat i.e. NM – NPM.
Below is the implementation of the above approach:
C++
#include <math.h>
#include <iostream>
using namespace std;
int fact( int n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
int nPr( int n, int r)
{
return fact(n) / fact(n - r);
}
int countWords( int N, int M)
{
return pow (N, M) - nPr(N, M);
}
int main()
{
int N = 10, M = 5;
cout << (countWords(N, M));
return 0;
}
|
Java
class GFG {
static int fact( int n)
{
if (n <= 1 )
return 1 ;
return n * fact(n - 1 );
}
static int nPr( int n, int r)
{
return fact(n) / fact(n - r);
}
static int countWords( int N, int M)
{
return ( int )Math.pow(N, M) - nPr(N, M);
}
public static void main(String[] args)
{
int N = 10 , M = 5 ;
System.out.print(countWords(N, M));
}
}
|
Python3
def fact(n):
if (n < = 1 ):
return 1 ;
return n * fact(n - 1 );
def nPr(n, r):
return fact(n) / / fact(n - r);
def countWords(N, M):
return pow (N, M) - nPr(N, M);
N = 10 ; M = 5 ;
print (countWords(N, M));
|
C#
using System;
class GFG
{
static int fact( int n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
static int nPr( int n, int r)
{
return fact(n) / fact(n - r);
}
static int countWords( int N, int M)
{
return ( int )Math.Pow(N, M) - nPr(N, M);
}
static public void Main ()
{
int N = 10, M = 5;
Console.Write(countWords(N, M));
}
}
|
Javascript
function fact(n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
function nPr( n, r)
{
return fact(n) / fact(n - r);
}
function countWords( N, M)
{
return Math.pow(N, M) - nPr(N, M);
}
var N = 10 ;
var M = 5;
document.write(countWords(N, M));
|
Time Complexity: O(n)
Auxiliary Space: O(N), for recursive stack space.
Last Updated :
07 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...