Count non-adjacent subsets from numbers arranged in Circular fashion
Last Updated :
07 Mar, 2022
Given that N people are sitting in a circular queue numbered from 1 to N, the task is to count the number of ways to select a subset of them such that no two consecutive are sitting together. The answer could be large, so compute the answer modulo 109 + 7. Note that an empty subset is also a valid subset.
Examples:
Input: N = 2
Output: 3
All possible subsets are {}, {1} and {2}.
Input: N = 3
Output: 4
Approach: Let’s find the answer to small values of N.
N = 1 -> All possible subsets are {}, {1}.
N = 2 -> All possible subsets are {}, {1}, {2}.
N = 3 -> All possible subsets are {}, {1}, {2}, {3}.
N = 4 -> All possible subsets are {}, {1}, {2}, {3}, {4}, {1, 3}, {2, 4}.
So the sequence will be 2, 3, 4, 7, …
When N = 5 the count will be 11 and if N = 6 then the count will be 18.
It can now be observed that the sequence is similar to a Fibonacci series starting from the second term with the first two terms, 3 and 4.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll N = 10000;
const ll MOD = 1000000007;
ll F[N];
void precompute()
{
F[1] = 2;
F[2] = 3;
F[3] = 4;
for ( int i = 4; i < N; i++)
F[i] = (F[i - 1] + F[i - 2]) % MOD;
}
int main()
{
int n = 8;
precompute();
cout << F[n];
return 0;
}
|
Java
class GFG
{
static int N = 10000 ;
static int MOD = 1000000007 ;
static int []F = new int [N];
static void precompute()
{
F[ 1 ] = 2 ;
F[ 2 ] = 3 ;
F[ 3 ] = 4 ;
for ( int i = 4 ; i < N; i++)
F[i] = (F[i - 1 ] + F[i - 2 ]) % MOD;
}
public static void main(String []args)
{
int n = 8 ;
precompute();
System.out.println(F[n]);
}
}
|
Python3
N = 10000 ;
MOD = 1000000007 ;
F = [ 0 ] * N;
def precompute():
F[ 1 ] = 2 ;
F[ 2 ] = 3 ;
F[ 3 ] = 4 ;
for i in range ( 4 ,N):
F[i] = (F[i - 1 ] + F[i - 2 ]) % MOD;
n = 8 ;
precompute();
print (F[n]);
|
C#
using System;
class GFG
{
static int N = 10000;
static int MOD = 1000000007;
static int []F = new int [N];
static void precompute()
{
F[1] = 2;
F[2] = 3;
F[3] = 4;
for ( int i = 4; i < N; i++)
F[i] = (F[i - 1] + F[i - 2]) % MOD;
}
public static void Main(String []args)
{
int n = 8;
precompute();
Console.WriteLine(F[n]);
}
}
|
Javascript
<script>
var N = 10000;
var MOD = 1000000007;
var F = Array(N);
function precompute()
{
F[1] = 2;
F[2] = 3;
F[3] = 4;
for ( var i = 4; i < N; i++)
F[i] = (F[i - 1] + F[i - 2]) % MOD;
}
var n = 8;
precompute();
document.write( F[n]);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...