Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Count Subsequence of 101 in binary form of a number
Next article icon

Count of unique subsequences from given number which are power of 2

Last Updated : 07 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S of size N and containing digits in the range [0-9], the task is to print the count of all the unique subsequences of a string that are the power of 2.

Examples:

Input: S = “1216389”
Output: 5
Explanation:
All the possible unique subsequences that are power of 2 are: {1, 2, 16, 128, 8}

Input: S = “12”
Output: 2
Explanation:
All the possible unique subsequences that are power of 2 are: {1, 2}.

Approach: The problem can be solved by generating all the subsequences of the string S and then checking if the number is the power of 2 or not. Follow the steps below to solve the problem:

  • Initialize a set say, allUniqueSubSeq to store the subsequence, which is a power of 2.
  • Define a recursive function, say uniqueSubSeq(S, ans, index), and perform the following steps:
    • Base Case: If the index is equal to N, then if, (int)ans, is the power of 2, then insert ans into the set allUniqueSubSeq.
    • Otherwise, there are two cases:
      • If S[index] is appended in the string ans, then recall the function uniqueSubSeq with parameters S, ans + S[index], and index+1.
      • If S[index] is not appended in the string ans, then recall the function uniqueSubSeq with parameters S, ans, and index + 1.
  • Finally, after performing the above steps, call the function, uniqueSubSeq(S, “”,  0) and then print the allUniqueSubSeq.size() as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Set to store subsequences that are
// power of 2
unordered_set<string> allUniqueSubSeq;
 
// Function to check whether the number
// is power of 2 or not
bool checkpower(int n)
{
    if ((n & (n - 1)) == 0)
    {
        return true;
    }
    return false;
}
 
// Auxiliary recursive Function to find
// all the unique subsequences of a string
// that are the power of 2
void uniqueSubSeq(string S, int N, string ans,
                            int index)
{
     
    // If index is equal to N
    if (index == N)
    {
        if (ans.length() != 0)
 
            // If the number is
            // power of 2
            if (checkpower(stoi(ans)))
            {
                 
                // Insert the String
                // in the set
                allUniqueSubSeq.insert(ans);
            }
        return;
    }
 
    // Recursion call, if the S[index]
    // is inserted in ans
    uniqueSubSeq(S, N, ans + S[index], index + 1);
 
    // Recursion call, if S[index] is
    // not inserted in ans
    uniqueSubSeq(S, N, ans, index + 1);
}
 
// Function to find count of all the unique
// subsequences of a string that are the
// power of 2
int Countsubsequneces(string S, int N)
{
     
    // Function Call
    uniqueSubSeq(S, N, "", 0);
 
    // Return the length of set
    // allUniqueSubSeq
    return allUniqueSubSeq.size();
}
 
// Driver Code
int main()
{
     
    // Given Input
    string S = "1216389";
    int N = S.length();
     
    // Function call
    cout << Countsubsequneces(S, N);
     
    return 0;
}
 
// This code is contributed by maddler
 
 

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
public class main {
 
    // Set to store subsequences that are
    // power of 2
    static HashSet<String> allUniqueSubSeq
        = new HashSet<>();
 
    // Function to check whether the number
    // is power of 2 or not
    static boolean checkpower(int n)
    {
        if ((n & (n - 1)) == 0) {
            return true;
        }
        return false;
    }
 
    // Auxiliary recursive Function to find
    // all the unique subsequences of a string
    // that are the power of 2
    static void uniqueSubSeq(String S, int N, String ans,
                             int index)
    {
 
        // If index is equal to N
        if (index == N) {
 
            if (ans.length() != 0)
 
                // If the number is
                // power of 2
                if (checkpower(
                        Integer.parseInt(ans.trim()))) {
 
                    // Insert the String
                    // in the set
                    allUniqueSubSeq.add(ans);
                }
            return;
        }
 
        // Recursion call, if the S[index]
        // is inserted in ans
        uniqueSubSeq(S, N, ans + S.charAt(index),
                     index + 1);
 
        // Recursion call, if S[index] is
        // not inserted in ans
        uniqueSubSeq(S, N, ans, index + 1);
    }
 
    // Function to find count of all the unique
    // subsequences of a string that are the
    // power of 2
    static int Countsubsequneces(String S, int N)
    {
        // Function Call
        uniqueSubSeq(S, N, "", 0);
 
        // Return the length of set
        // allUniqueSubSeq
        return allUniqueSubSeq.size();
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given Input
        String S = "1216389";
        int N = S.length();
 
        // Function call
        System.out.println(Countsubsequneces(S, N));
    }
}
 
 

Python3




# Python program for the above approach
 
# Set to store subsequences that are
# power of 2
allUniqueSubSeq = set()
 
# Function to check whether the number
# is power of 2 or not
def checkpower(n):
    if(n & (n-1) == 0):
        return True
    return False
 
# Auxiliary recursive Function to find
# all the unique subsequences of a string
# that are the power of 2
def uniqueSubSeq(S, N, ans, index):
   
    # If index is equal to N
    if (index == N):
        if (len(ans) != 0):
           
            # If the number is
            # power of 2
            if(checkpower(int(ans))):
                allUniqueSubSeq.add(ans)
        return
       
    # Recursion call, if the S[index]
    # is inserted in ans
    uniqueSubSeq(S, N, ans+S[index], index+1)
     
    # Recursion call, if the S[index]
    # is not inserted in ans
    uniqueSubSeq(S, N, ans, index+1)
 
# Function to find count of all the unique
# subsequences of a string that are
# the power of 2
def countSubsequences(S, N):
   
    # Function call
    uniqueSubSeq(S, N, "", 0)
     
    # Return the length of set
    # allUniqueSubSeq
    return len(allUniqueSubSeq)
 
# Driver code
if __name__ == '__main__':
   
    # Given Input
    S = "1216389"
    N = len(S)
 
    # Function call
    print(countSubsequences(S, N))
     
# This code is contributed by MuskanKalra1
 
 

C#




using System;
using System.Collections.Generic;
public class GFG {
 
    // Set to store subsequences that are
    // power of 2
    static HashSet<String> allUniqueSubSeq
        = new HashSet<String>();
 
    // Function to check whether the number
    // is power of 2 or not
    static bool checkpower(int n)
    {
        if ((n & (n - 1)) == 0) {
            return true;
        }
        return false;
    }
 
    // Auxiliary recursive Function to find
    // all the unique subsequences of a string
    // that are the power of 2
    static void uniqueSubSeq(String S, int N, String ans,
                             int index)
    {
 
        // If index is equal to N
        if (index == N) {
 
            if (ans.Length != 0)
 
                // If the number is
                // power of 2
                if (checkpower(
                        int.Parse(ans))) {
 
                    // Insert the String
                    // in the set
                    allUniqueSubSeq.Add(ans);
                }
            return;
        }
 
        // Recursion call, if the S[index]
        // is inserted in ans
        uniqueSubSeq(S, N, ans + S[index],
                     index + 1);
 
        // Recursion call, if S[index] is
        // not inserted in ans
        uniqueSubSeq(S, N, ans, index + 1);
    }
 
    // Function to find count of all the unique
    // subsequences of a string that are the
    // power of 2
    static int Countsubsequeneces(String S, int N)
    {
        // Function Call
        uniqueSubSeq(S, N, "", 0);
 
        // Return the length of set
        // allUniqueSubSeq
        return allUniqueSubSeq.Count;
    }
 
    // Driver Code
 
    static public void Main()
    {
        String S = "1216389";
        int N = S.Length;
 
        // Function call
        Console.WriteLine(Countsubsequeneces(S, N));
    }
}
 
// This code is contributed by maddler.
 
 

Javascript




<script>
       // Javascript program for above approach
 
       // Set to store subsequences that are
       // power of 2
       const allUniqueSubSeq
           = new Set();
 
       // Function to check whether the number
       // is power of 2 or not
       function checkpower(n) {
           if ((n & (n - 1)) == 0) {
               return true;
           }
           return false;
       }
 
       // Auxiliary recursive Function to find
       // all the unique subsequences of a string
       // that are the power of 2
       function uniqueSubSeq(S, N, ans, index) {
 
           // If index is equal to N
           if (index == N) {
 
               if (ans.length != 0)
 
                   // If the number is
                   // power of 2
                   if (checkpower(parseInt(ans.trim()))) {
 
                       // Insert the String
                       // in the set
                       allUniqueSubSeq.add(ans);
                   }
               return;
           }
 
           // Recursion call, if the S[index]
           // is inserted in ans
           uniqueSubSeq(S, N, ans + S.charAt(index),
               index + 1);
 
           // Recursion call, if S[index] is
           // not inserted in ans
           uniqueSubSeq(S, N, ans, index + 1);
       }
 
       // Function to find count of all the unique
       // subsequences of a string that are the
       // power of 2
       function Countsubsequneces(S, N) {
           // Function Call
           uniqueSubSeq(S, N, "", 0);
 
           // Return the length of set
           // allUniqueSubSeq
           return allUniqueSubSeq.size;
       }
 
       // Driver Code
 
       // Given Input
       let S = "1216389";
       let N = S.length;
 
       // Function call
       document.write(Countsubsequneces(S, N));
 
       // This code is contributed by Hritik
   </script>
 
 
Output
5

Time Complexity: O(2N)
Auxiliary Space: O(2N)

 



Next Article
Count Subsequence of 101 in binary form of a number
author
zack_aayush
Improve
Article Tags :
  • DSA
  • Mathematical
  • Pattern Searching
  • Recursion
  • maths-power
  • subsequence
Practice Tags :
  • Mathematical
  • Pattern Searching
  • Recursion

Similar Reads

  • Count of unique Subsequences of given String with lengths in range [0, N]
    Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N. Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007. Examples: Input: S = "ababd"Output: Num
    15 min read
  • Number of Subsequences with Even and Odd Sum | Set 2
    Given an array arr[] of size N. The task is to find the number of subsequences whose sum is even and the number of subsequences whose sum is odd.Examples: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are 2N-1 possible subsequences. The subsequences with even sum are 1) {1, 3} Su
    7 min read
  • Count Subsequence of 101 in binary form of a number
    Given a number N, the task is to count the occurrences of 101 subsequences in the binary representation of that number. Examples: Input: N = 10Output: 1Explanation: The binary representation of the number 10 is 1010 and there is only one subsequence 101 which is starting from the left end of binary
    5 min read
  • Number of Subsequences with Even and Odd Sum
    Given an array, find the number of subsequences whose sum is even and the number of subsequences whose sum is odd. Example: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are [Tex]2^{N}-1 [/Tex]possible subsequences. The subsequences with even sum is 1) {1, 3} Sum = 4 2) {1, 2, 2,
    15 min read
  • Number of subsequences of the form a^i b^j c^k
    Given a string, count number of subsequences of the form aibjck, i.e., it consists of i ’a’ characters, followed by j ’b’ characters, followed by k ’c’ characters where i >= 1, j >=1 and k >= 1. Note: Two subsequences are considered different if the set of array indexes picked for the 2 sub
    15+ min read
  • Find number of subarrays with XOR value a power of 2
    Given an integer array, arr[] of size N. The XOR value of any subarray of arr[] is defined as the xor of all the integers in that subarray. The task is to find the number of sub-arrays with XOR value a power of 2. (1, 2, 4, 8, 16, ....)Examples: Input : arr[] = {2, 6, 7, 5, 8} Output : 6 Subarrays :
    6 min read
  • Count number of sub-sequences with GCD 1
    Given an array of N numbers, the task is to count the number of subsequences that have gcd equal to 1. Examples: Input: a[] = {3, 4, 8, 16} Output: 7 The subsequences are: {3, 4}, {3, 8}, {3, 16}, {3, 4, 8}, {3, 4, 16}, {3, 8, 16}, {3, 4, 8, 16} Input: a[] = {1, 2, 4} Output: 4 A simple solution is
    15+ min read
  • Count of subsequence of an Array having all unique digits
    Given an array A containing N positive integers, the task is to find the number of subsequences of this array such that in each subsequence , no digit is repeated twice, i.e. all the digits of the subsequences must be unique.Examples: Input: A = [1, 12, 23, 34] Output: 7 The subsequences are: {1}, {
    15+ min read
  • Count of numbers which can be made power of 2 by given operation
    Given a array arr[], the task is to count the numbers which can be made power of 2 with the following operation: 1 can be added to any element atmost once if its not already a power of 2. Examples: Input: arr[] = {2, 3, 7, 9, 15} Output: 4 3, 7 and 15 can be made a power of 2 by adding 1, and 2 is a
    6 min read
  • Count of possible subarrays and subsequences using given length of Array
    Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.Examples: Input: N = 5 Output: Count of subarray = 15 Count of subsequence = 32Input: N = 3 Output: Count of subarray = 6 Count of subseque
    3 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