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
  • 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:
Number of substrings divisible by 4 in a string of integers
Next article icon

Number of subsequences in a given binary string divisible by 2

Last Updated : 10 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given binary string str of length N, the task is to find the count of subsequences of str which are divisible by 2. Leading zeros in a sub-sequence are allowed.

Examples:  

Input: str = “101” 
Output: 2 
“0” and “10” are the only subsequences 
which are divisible by 2.
Input: str = “10010” 
Output: 22  

Naive approach: A naive approach will be to generate all possible sub-sequences and check if they are divisible by 2. The time complexity for this will be O(2N * N).

Efficient approach: It can be observed that any binary number is divisible by 2 only if it ends with a 0. Now, the task is to just count the number of subsequences ending with 0. So, for every index i such that str[i] = ‘0’, find the number of subsequences ending at i. This value is equal to 2i (0-based indexing). Thus, the final answer will be equal to the summation of 2i for all i such that str[i] = ‘0’.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count
// of the required subsequences
int countSubSeq(string str, int len)
{
    // To store the final answer
    int ans = 0;
 
    // Multiplier
    int mul = 1;
 
    // Loop to find the answer
    for (int i = 0; i < len; i++) {
 
        // Condition to update the answer
        if (str[i] == '0')
            ans += mul;
        // updating multiplier
        mul *= 2;
    }
 
    return ans;
}
 
// Driver code
int main()
{
    string str = "10010";
    int len = str.length();
 
    cout << countSubSeq(str, len);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
class GFG
{
 
// Function to return the count
// of the required subsequences
static int countSubSeq(String str, int len)
{
    // To store the final answer
    int ans = 0;
 
    // Multiplier
    int mul = 1;
 
    // Loop to find the answer
    for (int i = 0; i < len; i++)
    {
 
        // Condition to update the answer
        if (str.charAt(i) == '0')
            ans += mul;
             
        // updating multiplier
        mul *= 2;
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String str = "10010";
    int len = str.length();
 
    System.out.print(countSubSeq(str, len));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 implementation of the approach
 
# Function to return the count
# of the required subsequences
def countSubSeq(strr, lenn):
     
    # To store the final answer
    ans = 0
 
    # Multiplier
    mul = 1
 
    # Loop to find the answer
    for i in range(lenn):
 
        # Condition to update the answer
        if (strr[i] == '0'):
            ans += mul
             
        # updating multiplier
        mul *= 2
 
    return ans
 
# Driver code
strr = "10010"
lenn = len(strr)
 
print(countSubSeq(strr, lenn))
 
# This code is contributed by Mohit Kumar
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the count
    // of the required subsequences
    static int countSubSeq(string str, int len)
    {
        // To store the final answer
        int ans = 0;
     
        // Multiplier
        int mul = 1;
     
        // Loop to find the answer
        for (int i = 0; i < len; i++)
        {
     
            // Condition to update the answer
            if (str[i] == '0')
                ans += mul;
                 
            // updating multiplier
            mul *= 2;
        }
        return ans;
    }
     
    // Driver code
    static public void Main ()
    {
        string str = "10010";
        int len = str.Length;
     
        Console.WriteLine(countSubSeq(str, len));
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the count
// of the required subsequences
function countSubSeq(str, len)
{
    // To store the final answer
    var ans = 0;
 
    // Multiplier
    var mul = 1;
 
    // Loop to find the answer
    for (var i = 0; i < len; i++) {
 
        // Condition to update the answer
        if (str[i] == '0')
            ans += mul;
        // updating multiplier
        mul *= 2;
    }
 
    return ans;
}
 
// Driver code
var str = "10010";
var len = str.length;
document.write( countSubSeq(str, len));
 
</script>
 
 

Output: 

22

Time Complexity: O(len), where len is the size of the given string
Auxiliary Space: O(1)
 



Next Article
Number of substrings divisible by 4 in a string of integers

D

DivyanshuShekhar1
Improve
Article Tags :
  • Algorithms
  • DSA
  • Dynamic Programming
  • Strings
  • binary-string
  • subsequence
Practice Tags :
  • Algorithms
  • Dynamic Programming
  • Strings

Similar Reads

  • Number of subsequences in a string divisible by n
    Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: Input : str = "1234", n = 4Output : 4The subsequences 4, 12, 24 and 124 are divisible by 4. Input : str = "330", n = 6Output : 4The subsequences 30, 30, 330 and 0 are divisible by n.Input : str =
    11 min read
  • Number of sub-strings in a given binary string divisible by 2
    Given binary string str of length N, the task is to find the count of substrings of str which are divisible by 2. Leading zeros in a substring are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only substrings which are divisible by 2. Input: str = "10010" Output: 10 Naive appr
    4 min read
  • Minimum number whose binary form is not a subsequence of given binary string
    Given a binary string S of size N, the task is to find the minimum non-negative integer which is not a subsequence of the given string S in its binary form. Examples: Input: S = "0000"Output:1Explanation: 1 whose binary representation is "1" is the smallest non-negative integer which is not a subseq
    8 min read
  • Number of substrings divisible by 4 in a string of integers
    Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when converted into integer are divisible by 4. Substring may contain leading zeroes. Examples: Input : "124" Output : 4 Substrings divisible by 4 are "12", "4", "24", "124" . Input : "04" Output : 3 Su
    11 min read
  • Number of substrings divisible by 6 in a string of integers
    Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
    9 min read
  • Number of sub-sequences of non-zero length of a binary string divisible by 3
    Given a binary string S of length N, the task is to find the number of sub-sequences of non-zero length which are divisible by 3. Leading zeros in the sub-sequences are allowed.Examples: Input: S = "1001" Output: 5 "11", "1001", "0", "0" and "00" are the only subsequences divisible by 3.Input: S = "
    5 min read
  • Longest Subsequence from a numeric String divisible by K
    Given an integer K and a numeric string str, the task is to find the longest subsequence from the given string which is divisible by K. Examples: Input: str = "121400", K = 8Output: 121400Explanation:Since the whole string is divisible by 8, the entire string is the answer. Input: str: "7675437", K
    8 min read
  • Given a large number, check if a subsequence of digits is divisible by 8
    Given a number of at most 100 digits. We have to check if it is possible, after removing certain digits, to obtain a number of at least one digit which is divisible by 8. We are forbidden to rearrange the digits. Examples : Input : 1787075866 Output : Yes There exist more one or more subsequences di
    15+ min read
  • Largest sub-string of a binary string divisible by 2
    Given binary string str of length N, the task is to find the longest sub-string divisible by 2. If no such sub-string exists then print -1. Examples: Input: str = "11100011" Output: 111000 Largest sub-string divisible by 2 is "111000".Input: str = "1111" Output: -1 There is no sub-string of the give
    3 min read
  • Generate Binary String with equal number of 01 and 10 Subsequence
    Given an integer N (N > 2), the task is to generate a binary string of size N that consists of equal numbers of "10" & "01" subsequences and also the string should contain at least one '0' and one '1' Note: If multiple such strings exist, print any. Examples: Input: 4Output: 0110Explanation :
    7 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