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:
Longest sub-sequence of a binary string divisible by 3
Next article icon

Number of sub-sequences of non-zero length of a binary string divisible by 3

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = "1" 
Output: 0 


Naive approach: Generate all the possible sub-sequences and check if they are divisible by 3. Time complexity for this will be O((2N) * N).
Better approach: Dynamic programming can be used to solve this problem. Let's look at the states of the DP. 
DP[i][r] will store the number of sub-sequences of the substring S[i...N-1] such that they give a remainder of (3 - r) % 3 when divided by 3. 
Let's write the recurrence relation now. 
 

DP[i][r] = DP[i + 1][(r * 2 + s[i]) % 3] + DP[i + 1][r] 
 


The recurrence is derived because of the two choices below: 
 

  1. Include the current index i in the sub-sequence. Thus, the r will be updated as r = (r * 2 + s[i]) % 3.
  2. Don't include a current index in the sub-sequence.


Below is the implementation of the above approach: 
 

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; #define N 100  int dp[N][3]; bool v[N][3];  // Function to return the number of // sub-sequences divisible by 3 int findCnt(string& s, int i, int r) {     // Base-cases     if (i == s.size()) {         if (r == 0)             return 1;         else             return 0;     }      // If the state has been solved     // before then return its value     if (v[i][r])         return dp[i][r];      // Marking the state as solved     v[i][r] = 1;      // Recurrence relation     dp[i][r]         = findCnt(s, i + 1, (r * 2 + (s[i] - '0')) % 3)           + findCnt(s, i + 1, r);      return dp[i][r]; }  // Driver code int main() {     string s = "11";      cout << (findCnt(s, 0, 0) - 1);      return 0; } 
Java
// Java implementation of the approach  class GFG  {      static final int N = 100;           static int dp[][] = new int[N][3];      static int v[][] = new int[N][3];           // Function to return the number of      // sub-sequences divisible by 3      static int findCnt(String s, int i, int r)      {          // Base-cases          if (i == s.length())          {              if (r == 0)                  return 1;              else                 return 0;          }               // If the state has been solved          // before then return its value          if (v[i][r] == 1)              return dp[i][r];               // Marking the state as solved          v[i][r] = 1;               // Recurrence relation          dp[i][r] = findCnt(s, i + 1, (r * 2 + (s.charAt(i) - '0')) % 3)                      + findCnt(s, i + 1, r);               return dp[i][r];      }          // Driver code      public static void main (String[] args)      {         String s = "11";               System.out.print(findCnt(s, 0, 0) - 1);           }  }  // This code is contributed by AnkitRai01 
Python3
# Python3 implementation of the approach  import numpy as np N = 100  dp = np.zeros((N, 3));  v = np.zeros((N, 3));  # Function to return the number of  # sub-sequences divisible by 3  def findCnt(s, i, r) :      # Base-cases      if (i == len(s)) :                   if (r == 0) :             return 1;          else :             return 0;       # If the state has been solved      # before then return its value      if (v[i][r]) :         return dp[i][r];       # Marking the state as solved      v[i][r] = 1;       # Recurrence relation      dp[i][r] = findCnt(s, i + 1, (r * 2 +                        (ord(s[i]) - ord('0'))) % 3) + \                findCnt(s, i + 1, r);       return dp[i][r];   # Driver code  if __name__ == "__main__" :       s = "11";       print(findCnt(s, 0, 0) - 1);   # This code is contributed by AnkitRai01 
C#
// C# implementation of the approach  using System;  class GFG  {      static readonly int N = 100;           static int [,]dp = new int[N, 3];      static int [,]v = new int[N, 3];           // Function to return the number of      // sub-sequences divisible by 3      static int findCnt(String s, int i, int r)      {          // Base-cases          if (i == s.Length)          {              if (r == 0)                  return 1;              else                 return 0;          }               // If the state has been solved          // before then return its value          if (v[i, r] == 1)              return dp[i, r];               // Marking the state as solved          v[i, r] = 1;               // Recurrence relation          dp[i, r] = findCnt(s, i + 1, (r * 2 + (s[i] - '0')) % 3)                      + findCnt(s, i + 1, r);               return dp[i, r];      }          // Driver code      public static void Main(String[] args)      {         String s = "11";               Console.Write(findCnt(s, 0, 0) - 1);           }  }  // This code is contributed by 29AjayKumar 
JavaScript
<script>  // Javascript implementation of the approach var N = 100  var dp = Array.from(Array(N), ()=> Array(3)); var v = Array.from(Array(N), ()=> Array(3));  // Function to return the number of // sub-sequences divisible by 3 function findCnt(s, i, r) {     // Base-cases     if (i == s.length) {         if (r == 0)             return 1;         else             return 0;     }      // If the state has been solved     // before then return its value     if (v[i][r])         return dp[i][r];      // Marking the state as solved     v[i][r] = 1;      // Recurrence relation     dp[i][r]         = findCnt(s, i + 1, (r * 2 + (s[i] - '0')) % 3)           + findCnt(s, i + 1, r);      return dp[i][r]; }  // Driver code var s = "11"; document.write( (findCnt(s, 0, 0) - 1));  </script>    

Output: 
1

 

Time Complexity: O(n)
Auxiliary Space: O(n * 3) ⇒ O(n), where n is the length of the given string.


Next Article
Longest sub-sequence of a binary string divisible by 3

D

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

Similar Reads

  • Longest sub-sequence of a binary string divisible by 3
    Given a binary string S of length N, the task is to find the length of the longest sub-sequence in it which is divisible by 3. Leading zeros in the sub-sequences are allowed.Examples:   Input: S = "1001" Output: 4 The longest sub-sequence divisible by 3 is "1001". 1001 = 9 which is divisible by 3.In
    9 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
  • Number of binary strings such that there is no substring of length ≥ 3
    Given an integer N, the task is to count the number of binary strings possible such that there is no substring of length ? 3 of all 1's. This count can become very large so print the answer modulo 109 + 7.Examples: Input: N = 4 Output: 13 All possible valid strings are 0000, 0001, 0010, 0100, 1000,
    10 min read
  • Number of subsequences in a given binary string divisible by 2
    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 Naiv
    4 min read
  • Count number of binary strings of length N having only 0's and 1's
    Given an integer N, the task is to count the number of binary strings of length N having only 0's and 1's. Note: Since the count can be very large, return the answer modulo 10^9+7. Examples: Input: 2 Output: 4 Explanation: The numbers are 00, 01, 11, 10. Hence the count is 4. Input: 3 Output: 8 Expl
    6 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
  • Number of Binary Strings of length N with K adjacent Set Bits
    Given [Tex]n [/Tex]and [Tex]k [/Tex]. The task is to find the number of binary strings of length n out of 2n such that they satisfy f(bit string) = k. Where, f(x) = Number of times a set bit is adjacent to another set bit in a binary string x.For Example:f(011101101) = 3f(010100000) = 0f(111111111)
    15+ min read
  • Number of substrings with length divisible by the number of 1's in it
    Given a binary string S consisting of only 0's and 1's. Count the number of substrings of this string such that the length of the substring is divisible by the number of 1's in the substring. Examples: Input: S = "01010" Output: 10 Input: S = "1111100000" Output: 25 Naive Approach: Iterate through a
    15+ min read
  • Number of substrings divisible by 8 but not by 3
    Given a string of digits "0-9". The task is to find the number of substrings which are divisible by 8 but not by 3. Examples : Input : str = "888" Output : 5 Substring indexes : (1, 1), (1, 2), (2, 2), (2, 3), (3, 3). Input : str = "6564525600" Output : 15Recommended: Please solve it on “PRACTICE ”
    11 min read
  • Count the number of Special Strings of a given length N
    Given the length N of the string, we have to find the number of special strings of length N. A string is called a special string if it consists only of lowercase letters a and b and there is at least one b between two a’s in the string. Since the number of strings may be very large, therefore print
    9 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