Given N positions, the task is to count the total number of ways to place X and Y such that no two X are together.
Examples:
Input: 3
Output: 5
XYX, YYX, YXY, XYY and YYY
Input: 4
Output: 8
XYXY, XYYX, YXYX, YYYX, YYXY, YXYY, XYYY and YYYY
Approach:
For N = 1, X and Y are 2 possible ways.
For N = 2, XY, YX and YY are the 3 possible ways.
For N = 3, XYX, YYX, YXY, XYY and YYY are 5 possible ways.
For N = 4, XYXY, XYYX, YXYX, YYYX, YYXY, YXYY, XYYY and YYYY are 8 possible ways.
On solving for values of N, a Fibonacci pattern series is observed.
Below is the iterative implementation of the above approach:
C++
#include <iostream>
using namespace std;
int ways( int n)
{
int first = 2;
int second = 3;
int res = 0;
for ( int i = 3; i <= n; i++) {
res = first + second;
first = second;
second = res;
}
return res;
}
int main()
{
int n = 7;
cout << "Total ways are : " ;
cout << ways(n);
return 0;
}
|
Java
public class GFG {
static int ways( int n)
{
int first = 2 ;
int second = 3 ;
int res = 0 ;
for ( int i = 3 ; i <= n; i++) {
res = first + second;
first = second;
second = res;
}
return res;
}
public static void main(String[] args)
{
int n = 7 ;
System.out.print( "Total ways are: " + ways(n));
}
}
|
Python3
def ways(n):
first = 2 ;
second = 3 ;
res = 0 ;
for i in range ( 3 , n + 1 ):
res = first + second;
first = second;
second = res;
return res;
n = 7 ;
print ( "Total ways are: " ,
ways(n));
|
C#
using System;
class GFG
{
static int ways( int n)
{
int first = 2;
int second = 3;
int res = 0;
for ( int i = 3; i <= n; i++)
{
res = first + second;
first = second;
second = res;
}
return res;
}
static public void Main ()
{
int n = 7;
Console.WriteLine( "Total ways are: " +
ways(n));
}
}
|
PHP
<?php
function ways( $n )
{
$first = 2;
$second = 3;
$res = 0;
for ( $i = 3; $i <= $n ; $i ++)
{
$res = $first + $second ;
$first = $second ;
$second = $res ;
}
return $res ;
}
$n = 7;
echo "Total ways are: " , ways( $n );
?>
|
Javascript
<script>
function ways(n)
{
var first = 2;
var second = 3;
var res = 0;
for (i = 3; i <= n; i++)
{
res = first + second;
first = second;
second = res;
}
return res;
}
var n = 7;
document.write( "Total ways are: " + ways(n));
</script>
|
Output:
Total ways are: 34
Time Complexity: O(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 :
30 Sep, 2022
Like Article
Save Article