Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Count of subsets not containing adjacent elements
Next article icon

Count of subsets not containing adjacent elements

Last Updated : 29 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers, the task is to find the count of all the subsets which do not contain adjacent elements from the given array.
Examples:  

Input: arr[] = {2, 7} 
Output: 3 
All possible subsets are {}, {2} and {7}.

Input: arr[] = {3, 5, 7} 
Output: 5  

Method 1: Using bit masking  

Idea: The idea is to use a bit-mask pattern to generate all the combinations as discussed in this article. While considering a subset, we need to check if it contains adjacent elements or not. A subset will contain adjacent elements if two or more consecutive bits are set in its bit mask. In order to check if the bit-mask has consecutive bits set or not, we can right shift the mask by one bit and take it AND with the mask. If the result of the AND operation is 0, then the mask does not have consecutive sets and therefore, the corresponding subset will not have adjacent elements from the array.
Below is the implementation of the above approach:  

C++
// C++ implementation of the approach #include <iostream> #include <math.h> using namespace std;  // Function to return the count // of possible subsets int cntSubsets(int* arr, int n) {      // Total possible subsets of n     // sized array is (2^n - 1)     unsigned int max = pow(2, n);      // To store the required     // count of subsets     int result = 0;      // Run from i 000..0 to 111..1     for (int i = 0; i < max; i++) {         int counter = i;          // If current subset has consecutive         // elements from the array         if (counter & (counter >> 1))             continue;         result++;     }     return result; }  // Driver code int main() {     int arr[] = { 3, 5, 7 };     int n = sizeof(arr) / sizeof(arr[0]);      cout << cntSubsets(arr, n);      return 0; } 
Java
// Java implementation of the approach import java.util.*;      class GFG {  // Function to return the count // of possible subsets static int cntSubsets(int[] arr, int n) {      // Total possible subsets of n     // sized array is (2^n - 1)     int max = (int) Math.pow(2, n);      // To store the required     // count of subsets     int result = 0;      // Run from i 000..0 to 111..1     for (int i = 0; i < max; i++)      {         int counter = i;          // If current subset has consecutive         if ((counter & (counter >> 1)) > 0)             continue;         result++;     }     return result; }  // Driver code static public void main (String []arg) {     int arr[] = { 3, 5, 7 };     int n = arr.length;      System.out.println(cntSubsets(arr, n)); } }  // This code is contributed by Rajput-Ji 
Python3
# Python3 implementation of the approach  # Function to return the count # of possible subsets def cntSubsets(arr, n):      # Total possible subsets of n     # sized array is (2^n - 1)     max = pow(2, n)      # To store the required     # count of subsets     result = 0      # Run from i 000..0 to 111..1     for i in range(max):         counter = i          # If current subset has consecutive         # elements from the array         if (counter & (counter >> 1)):             continue         result += 1      return result  # Driver code arr = [3, 5, 7] n = len(arr)  print(cntSubsets(arr, n))  # This code is contributed by Mohit Kumar 
C#
// C# implementation of the approach using System;  class GFG {      // Function to return the count // of possible subsets static int cntSubsets(int[] arr, int n) {      // Total possible subsets of n     // sized array is (2^n - 1)     int max = (int) Math.Pow(2, n);      // To store the required     // count of subsets     int result = 0;      // Run from i 000..0 to 111..1     for (int i = 0; i < max; i++)      {         int counter = i;          // If current subset has consecutive         if ((counter & (counter >> 1)) > 0)             continue;         result++;     }     return result; }  // Driver code static public void Main (String []arg) {     int []arr = { 3, 5, 7 };     int n = arr.Length;      Console.WriteLine(cntSubsets(arr, n)); } }      // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript implementation of the approach  // Function to return the count // of possible subsets function cntSubsets(arr, n) {      // Total possible subsets of n     // sized array is (2^n - 1)     var max = Math.pow(2, n);      // To store the required     // count of subsets     var result = 0;      // Run from i 000..0 to 111..1     for (var i = 0; i < max; i++) {         var counter = i;          // If current subset has consecutive         // elements from the array         if (counter & (counter >> 1))             continue;         result++;     }     return result; }  // Driver code var arr = [3, 5, 7]; var n = arr.length; document.write( cntSubsets(arr, n));   </script>  

Output
5

Time Complexity: O(2n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Method 2: The above approach takes exponential time. In the above code, the number of bit-masks without consecutive 1s was required. This count can be obtained in linear time using dynamic programming as discussed in this article.
Below is the implementation of the above approach:  

C++
// C++ implementation of the approach #include <iostream> using namespace std;  // Function to return the count // of possible subsets int cntSubsets(int* arr, int n) {     int a[n], b[n];      a[0] = b[0] = 1;      for (int i = 1; i < n; i++) {          // If previous element was 0 then 0         // as well as 1 can be appended         a[i] = a[i - 1] + b[i - 1];          // If previous element was 1 then         // only 0 can be appended         b[i] = a[i - 1];     }      // Store the count of all possible subsets     int result = a[n - 1] + b[n - 1];      return result; }  // Driver code int main() {     int arr[] = { 3, 5, 7 };     int n = sizeof(arr) / sizeof(arr[0]);      cout << cntSubsets(arr, n);      return 0; } 
Java
// Java implementation of the approach import java.util.*;  class GFG  {  // Function to return the count // of possible subsets static int cntSubsets(int []arr, int n) {     int []a = new int[n];     int []b = new int[n];      a[0] = b[0] = 1;      for (int i = 1; i < n; i++)      {          // If previous element was 0 then 0         // as well as 1 can be appended         a[i] = a[i - 1] + b[i - 1];          // If previous element was 1 then         // only 0 can be appended         b[i] = a[i - 1];     }      // Store the count of all possible subsets     int result = a[n - 1] + b[n - 1];      return result; }  // Driver code public static void main(String[] args) {     int arr[] = { 3, 5, 7 };     int n = arr.length;      System.out.println(cntSubsets(arr, n)); } }  // This code is contributed by Princi Singh 
Python3
# Python3 implementation of the approach   # Function to return the count  # of possible subsets  def cntSubsets(arr, n) :       a = [0] * n     b = [0] * n;       a[0] = b[0] = 1;       for i in range(1, n) :                  # If previous element was 0 then 0          # as well as 1 can be appended          a[i] = a[i - 1] + b[i - 1];           # If previous element was 1 then          # only 0 can be appended          b[i] = a[i - 1];       # Store the count of all possible subsets      result = a[n - 1] + b[n - 1];       return result;   # Driver code  if __name__ == "__main__" :       arr = [ 3, 5, 7 ];      n = len(arr);       print(cntSubsets(arr, n));   # This code is contributed by AnkitRai01 
C#
// C# implementation of the approach using System;      class GFG  {  // Function to return the count // of possible subsets static int cntSubsets(int []arr, int n) {     int []a = new int[n];     int []b = new int[n];      a[0] = b[0] = 1;      for (int i = 1; i < n; i++)      {          // If previous element was 0 then 0         // as well as 1 can be appended         a[i] = a[i - 1] + b[i - 1];          // If previous element was 1 then         // only 0 can be appended         b[i] = a[i - 1];     }      // Store the count of all possible subsets     int result = a[n - 1] + b[n - 1];      return result; }  // Driver code public static void Main(String[] args) {     int []arr = { 3, 5, 7 };     int n = arr.Length;      Console.WriteLine(cntSubsets(arr, n)); } }  // This code is contributed by 29AjayKumar 
JavaScript
<script>  // Javascript implementation of the approach  // Function to return the count // of possible subsets function cntSubsets(arr, n) {     var a = Array(n);     var b = Array(n);      a[0] = b[0] = 1;      for (var i = 1; i < n; i++) {          // If previous element was 0 then 0         // as well as 1 can be appended         a[i] = a[i - 1] + b[i - 1];          // If previous element was 1 then         // only 0 can be appended         b[i] = a[i - 1];     }      // Store the count of all possible subsets     var result = a[n - 1] + b[n - 1];      return result; }  // Driver code var arr = [3, 5, 7 ]; var n = arr.length; document.write( cntSubsets(arr, n));  </script>  

Output
5

Time Complexity: O(n)
Auxiliary Space: O(n), where n is the size of the given array

Another approach : Space optimized

 we can space optimize previous approach by using only two variables to store the previous values instead of two arrays. 

Implementation Steps:

  • Initialize two variables a and b to 1.
  • Use a loop to iterate over the array elements from index 1 to n-1.
  • For each element at index i, update a and b using the following formulas:
    a = a + b
    b = previous value of a
  • After the loop, compute the total number of possible subsets as the sum of a and b.
  • Return the total number of possible subsets.

Implementation:

C++
// C++ implementation of the approach #include <iostream> using namespace std;  // Function to return the count // of possible subsets int cntSubsets(int* arr, int n) {     int a = 1, b = 1;      for (int i = 1; i < n; i++) {          // If previous element was 0 then 0         // as well as 1 can be appended         int temp = a;         a = a + b;          // If previous element was 1 then         // only 0 can be appended         b = temp;     }      // Store the count of all possible subsets     int result = a + b;      return result; }  // Driver code int main() {     int arr[] = { 3, 5, 7 };     int n = sizeof(arr) / sizeof(arr[0]);      cout << cntSubsets(arr, n);      return 0; } 
Java
// Java implementation of the approach import java.io.*;  class Main {   // Function to return the count // of possible subsets static int cntSubsets(int[] arr, int n) {     int a = 1, b = 1;      for (int i = 1; i < n; i++) {          // If previous element was 0 then 0         // as well as 1 can be appended         int temp = a;         a = a + b;          // If previous element was 1 then         // only 0 can be appended         b = temp;     }      // Store the count of all possible subsets     int result = a + b;      return result; }  // Driver code public static void main(String[] args) {     int[] arr = { 3, 5, 7 };     int n = arr.length;      System.out.println(cntSubsets(arr, n)); } } 
Python3
# Function to return the count # of possible subsets   def cntSubsets(arr, n):     a = 1     b = 1      for i in range(1, n):         # If previous element was 0 then 0         # as well as 1 can be appended         temp = a         a = a + b          # If previous element was 1 then         # only 0 can be appended         b = temp      # Store the count of all possible subsets     result = a + b      return result   # Driver code arr = [3, 5, 7] n = len(arr)  print(cntSubsets(arr, n)) 
C#
using System;  public class Program {     public static int CountSubsets(int[] arr, int n)     {         int a = 1, b = 1;         for (int i = 1; i < n; i++) {              // If previous element was 0 then 0             // as well as 1 can be appended             int temp = a;             a = a + b;              // If previous element was 1 then             // only 0 can be appended             b = temp;         }          // Store the count of all possible subsets         int result = a + b;          return result;     }      public static void Main()     {         int[] arr = { 3, 5, 7 };         int n = arr.Length;          Console.WriteLine(CountSubsets(arr, n));     } } 
JavaScript
// Function to return the count of possible subsets function cntSubsets(arr) {     let a = 1, b = 1;      for (let i = 1; i < arr.length; i++) {          // If previous element was 0 then 0         // as well as 1 can be appended         let temp = a;         a = a + b;          // If previous element was 1 then         // only 0 can be appended         b = temp;     }      // Store the count of all possible subsets     let result = a + b;      return result; }  // Driver code     const arr = [3, 5, 7];      console.log(cntSubsets(arr)); 

Output
5

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 3; If we take a closer look at the pattern, we can observe that the count is actually (N + 2)th Fibonacci number for N ? 1.  

n = 1, count = 2 = fib(3) 
n = 2, count = 3 = fib(4) 
n = 3, count = 5 = fib(5) 
n = 4, count = 8 = fib(6) 
n = 5, count = 13 = fib(7) 
................ 

Therefore, the subsets can be counted in O(log n) time using method 5 of this article.


Next Article
Count of subsets not containing adjacent elements

A

aganjali10
Improve
Article Tags :
  • Misc
  • Dynamic Programming
  • DSA
  • Arrays
  • subset
  • Bit Algorithms
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Misc
  • subset

Similar Reads

    Bit Manipulation for Competitive Programming
    Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag
    15+ min read
    Count set bits in an integer
    Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits[Naive Approach] - One by One CountingTh
    15+ min read
    Count total set bits in first N Natural Numbers (all numbers from 1 to N)
    Given a positive integer n, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to n. Examples: Input: n= 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -> Set bits = 1Binary Representation of 2: 10 -> Se
    9 min read
    Check whether the number has only first and last bits set
    Given a positive integer n. The problem is to check whether only the first and last bits are set in the binary representation of n.Examples: Input : 9 Output : Yes (9)10 = (1001)2, only the first and last bits are set. Input : 15 Output : No (15)10 = (1111)2, except first and last there are other bi
    4 min read
    Shortest path length between two given nodes such that adjacent nodes are at bit difference 2
    Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and
    7 min read
    Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
    Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers.Examples:Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, the
    7 min read
    Unset least significant K bits of a given number
    Given an integer N, the task is to print the number obtained by unsetting the least significant K bits from N. Examples: Input: N = 200, K=5Output: 192Explanation: (200)10 = (11001000)2 Unsetting least significant K(= 5) bits from the above binary representation, the new number obtained is (11000000
    4 min read
    Find all powers of 2 less than or equal to a given number
    Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N. Examples: Input: N = 63 Output: 32 16 8 4 2 1 Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N. Input: N = 193 Output:
    6 min read
    Powers of 2 to required sum
    Given an integer N, task is to find the numbers which when raised to the power of 2 and added finally, gives the integer N. Example : Input : 71307 Output : 0, 1, 3, 7, 9, 10, 12, 16 Explanation : 71307 = 2^0 + 2^1 + 2^3 + 2^7 + 2^9 + 2^10 + 2^12 + 2^16 Input : 1213 Output : 0, 2, 3, 4, 5, 7, 10 Exp
    10 min read
    Print bitwise AND set of a number N
    Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. Examples : Input : N = 5Output : 0, 1, 4, 5 Explanation: 0 &
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences