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 Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Number of sub-strings in a given binary string divisible by 2
Next article icon

Maximum splits in binary string such that each substring is divisible by given odd number

Last Updated : 05 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given binary string str, the task is to calculate the maximum possible splits possible to make each substring divisible by a given odd number K.
Examples: 
 

Input: str = "110111001", K = 9 
Output: 2 
Explanation: 
The two possible substrings are "11011" and "1001". The equivalent decimal values are 27 and 9 respectively which are divisible by 9.
Input: str = "10111001", K = 5 
Output: 2 
Explanation: 
The two possible substrings are "101" and "11001". The equivalent decimal values are 5 and 25 respectively which are divisible by 5. 
 


 


Approach: In order to solve this problem, we traverse from the end of the string and generate the sum of the length traversed. As soon as the sum is divisible by K, we increase the count by 1 and reset sum to 0 and traverse forward and repeat the same process. On full traversal of the string, if sum has been reset to 0, then the value of the count gives the required maximum possible splits. Otherwise, print "Not Possible" as all segments are not divisible by K.
Below code is the implementation of the above approach:
 

C++
// C++ Program to split // a given binary string // into maximum possible // segments divisible by // given odd number K  #include <bits/stdc++.h> using namespace std; // Function to calculate // maximum splits possible void max_segments(string str, int K) {     int n = str.length();     int s = 0, sum = 0, count = 0;     for (int i = n - 1; i >= 0; i--) {         int a = str[i] - '0';         sum += a * pow(2, s);          s++;         if (sum != 0 && sum % K == 0) {             count++;             sum = 0;             s = 0;         }     }     if (sum != 0)         cout << "-1" << endl;     else         cout << count << endl; }  // Driver code int main() {     string str = "10111001";     int K = 5;     max_segments(str, K);     return 0; } 
Java
// Java code to split a given // binary string into maximum // possible segments divisible // by given odd number K  import java.io.*;  import java.util.*;  class GFG{      // Function to calculate  // maximum splits possible  static void rearrange(String str, int K)  {      int n = str.length();      int s = 0, sum = 0, count = 0;          for(int i = n - 1; i >= 0; i--)     {         int a = str.charAt(i) - '0';         sum += a * Math.pow(2, s);         s++;                 if (sum != 0 && sum % K == 0)         {             count++;             sum = 0;               s = 0;         }      }       if (sum != 0)          System.out.println("-1");         else         System.out.println(count); }  // Driver code  public static void main(String[] args)  {      String str = "10111001";      int K = 5;          rearrange(str, K);  }  }   // This code is contributed by coder001 
Python3
# Python3 program to split # a given binary string # into maximum possible # segments divisible by # given odd number K  # Function to calculate # maximum splits possible def max_segments(st, K):      n = len(st)     s, sum, count = 0, 0, 0          for i in range(n - 1, -1, -1):         a = ord(st[i]) - 48         sum += a * pow(2, s)         s += 1                  if (sum != 0 and sum % K == 0):             count += 1             sum = 0             s = 0                  if (sum != 0):         print("-1")     else:         print(count)  # Driver code if __name__ == "__main__":          st = "10111001"     K = 5     max_segments(st, K)  # This code is contributed by chitranayal 
C#
// C# program to split a given  // binary string into maximum  // possible segments divisible by  // given odd number K  using System;  class GFG{      // Function to calculate  // maximum splits possible  static void max_segments(string str, int K) {     int n = str.Length;     int s = 0;     int sum = 0;     int count = 0;          for(int i = n - 1; i >= 0; i--)     {        int a = str[i] - '0';        sum += a * (int)Math.Pow(2, s);        s++;                if (sum != 0 && sum % K == 0)        {            count++;            sum = 0;              s = 0;        }     }     if (sum != 0)     {         Console.Write("-1");     }     else     {         Console.Write(count);     } }  // Driver code  public static void Main()  {     string str = "10111001";     int K = 5;          max_segments(str, K); } }  // This code is contributed by sayesha     
JavaScript
<script>  // Javascript code to split a given // binary string into maximum // possible segments divisible // by given odd number K        // Function to calculate  // maximum splits possible  function rearrange(str , K)  {      var n = str.length;      var s = 0, sum = 0, count = 0;          for(var i = n - 1; i >= 0; i--)     {         var a = str.charAt(i) - '0';         sum += a * Math.pow(2, s);         s++;                 if (sum != 0 && sum % K == 0)         {             count++;             sum = 0;               s = 0;         }      }       if (sum != 0)          document.write("-1");         else         document.write(count); }  // Driver code  var str = "10111001";  var K = 5;  rearrange(str, K);   // This code contributed by shikhasingrajput   </script> 

Output: 
2

 

Time Complexity: O(n)

Auxiliary Space: O(1)


Next Article
Number of sub-strings in a given binary string divisible by 2
author
siddhanthapliyal
Improve
Article Tags :
  • Strings
  • Mathematical
  • Competitive Programming
  • Programming Language
  • DSA
  • divisibility
  • binary-string
Practice Tags :
  • Mathematical
  • Strings

Similar Reads

  • 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 splits in a binary string such that every substring is a power of 4 or 6.
    Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: Input: 100110110 Output: 3 The string can be split into a minimum of three substrings
    11 min read
  • Find the minimum number of distinct Substrings formed by 0s in Binary String
    Given two integers N and M, the task is to output the minimum number of different substrings that can be formed using the Binary String of length N having M number of set bits. Note: Two substrings let say S[x, y] and S[a, b] are different. If either x != a or y != b. Examples: Input: N = 3, M = 1Ou
    6 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
  • Maximum number of set bits count in a K-size substring of a Binary String
    Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
    10 min read
  • Number of ways to split a binary number such that every part is divisible by 2
    Given a binary string S, the task is to find the number of ways to split it into parts such that every part is divisible by 2. Examples: Input: S = "100" Output: 2 There are two ways to split the string: {"10", "0"} and {"100"}Input: S = "110" Output: 1 Approach: One observation is that the string c
    7 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 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
  • Maximum bitwise OR one of any two Substrings of given Binary String
    Given a binary string str, the task is to find the maximum possible OR value of any two substrings of the binary string str. Examples: Input: str = "1110010"Output: "1111110"Explanation: On choosing the substring "1110010" and "11100" we get the OR value as "1111110" which is the maximum value. Inpu
    8 min read
  • Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
    Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the bina
    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