Four boys are playing a game with a ball. In each turn, the player (who has the ball currently) passes it to a different player randomly. Bob always starts the game. The task is to find in how many ways the ball will come back to Bob after N passes.
Examples:
Input: N = 3
Output: 6
Here are all the possible ways:
Bob -> Boy1 -> Boy2 -> Bob
Bob -> Boy1 -> Boy3 -> Bob
Bob -> Boy2 -> Boy1 -> Bob
Bob -> Boy2 -> Boy3 -> Bob
Bob -> Boy3 -> Boy1 -> Bob
Bob -> Boy3 -> Boy2 -> Bob
Input: N = 10
Output: 14763
Approach: Let the number of sequences that get back to Bob after N passes are P(N). There are two cases, either pass N – 2 is to Bob or it is not. Note that Bob can’t have the ball at (N – 1)th pass because then he won’t have the ball at the Nth pass.
- Case 1: If pass N – 2 is to Bob then the pass N – 1 can be to any of the other 3 boys. Thus, the number of such sequences is 3 * P(N – 2).
- Case 2: If pass N – 2 is not to Bob then pass N – 1 is to one of the 2 boys other than Bob and the one who got the ball in hand. So, substitute Bob for the receiver of pass N – 1, and get a unique N – 1 sequence. So, the number of such sequences are 2 * P(N – 1).
Hence the recurrence relation will be P(N) = 2 * P(N – 1) + 3 * P(N – 2) where P(0) = 1 and P(1) = 0.
After solving the recurrence relation, P(N) = (3N + 3 * (-1N)) / 4
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int numSeq( int n)
{
return ( pow (3, n) + 3 * pow (-1, n)) / 4;
}
int main()
{
int N = 10;
printf ( "%d" , numSeq(N));
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int numSeq( int n)
{
return ( int ) ((Math.pow( 3 , n) + 3 *
Math.pow(- 1 , n)) / 4 );
}
public static void main(String[] args)
{
int N = 10 ;
System.out.printf( "%d" , numSeq(N));
}
}
|
Python3
def numSeq(n):
return ( pow ( 3 , n) + 3 * pow ( - 1 , n)) / / 4
N = 10
print (numSeq(N))
|
C#
using System;
class GFG
{
static int numSeq( int n)
{
return ( int ) ((Math.Pow(3, n) + 3 *
Math.Pow(-1, n)) / 4);
}
public static void Main()
{
int N = 10;
Console.WriteLine(numSeq(N));
}
}
|
Javascript
<script>
function numSeq(n)
{
return Math.floor((Math.pow(3, n) + 3 * Math.pow(-1, n)) / 4);
}
let N = 10;
document.write(numSeq(N));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Aug, 2022
Like Article
Save Article