Count of distinct permutations of length N having no similar adjacent characters
Given an integer N, the task is to calculate the total number of distinct permutations of length N, consisting only of letters ‘a’, ‘b’, and ‘c’, with repetitions allowed, such that no two adjacent characters are the same.
Input: N = 3
Output: 12
Explanation:
Possible permutations satisfying the required conditions are {aba, abc, aca, acb, bac, bab, bca, bcb, cac, cab, cba, cbc}
Input: N = 5
Output: 48
Approach:
Following observations need to be made to solve the given problem:
- Let us fix the first letter as ‘a’.
- Now, the 2nd letter can either be ‘b’ or ‘c’, which leaves 2 ways to fill the second letter.
- Similarly, the third letter can also be filled in two ways. If the character in 2nd position is ‘b’, the third character can either be ‘a’ or ‘c’. If the character in 2nd position is ‘c’, the third character can either be ‘a’ or ‘b’.
- Similarly, for all the remaining positions, there will always be two possibilities depending on the character in the previous position. Therefore, the total number of possible permutation if ‘a’ occupies the first position is 1*2*2*2…*2 = 1 * 2N – 1.
- Therefore, the total number of permutations, considering the first character can also be ‘b’ or ‘c’ as well, is 3 * 2N – 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countofPermutations( int N)
{
return int (3 * pow (2, N - 1));
}
int main()
{
int N = 5;
cout << countofPermutations(N);
return 0;
}
|
Java
class GFG{
static int countofPermutations( int N)
{
return ( int )( 3 * Math.pow( 2 , N - 1 ));
}
public static void main(String[] args)
{
int N = 5 ;
System.out.print(countofPermutations(N));
}
}
|
Python3
def countofPermutations(N):
return int (( 3 * pow ( 2 , N - 1 )));
if __name__ = = '__main__' :
N = 5 ;
print (countofPermutations(N));
|
C#
using System;
class GFG{
static int countofPermutations( int N)
{
return ( int )(3 * Math.Pow(2, N - 1));
}
public static void Main(String[] args)
{
int N = 5;
Console.Write(countofPermutations(N));
}
}
|
Javascript
<script>
function countofPermutations(N)
{
return parseInt(3 * Math.pow(2, N - 1));
}
var N = 5;
document.write( countofPermutations(N));
</script>
|
Time Complexity: O(logN)
Auxiliary Space: O(1)
Last Updated :
29 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...