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:
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
Next article icon

Minimum splits in a binary string such that every substring is a power of 4 or 6.

Last Updated : 19 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 100(power of 4), 110 (power of 6) and 110(power of 6).  Input : 00000 Output : -1 0 is not a power of  4 or 6.
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

A simple solution is to split the string recursively at different indices and check if each split is a power of 4 or 6. Start with index 0 and split str[0] from other string. If it is a power of 4 or 6 then call recursively for index 1 and perform the same operation. When an entire string is split check if a total number of partitions are minimum so far or not. Then split str[0..1], check if it is the power of 4 or 6 and then call recursively for rest string. Compare partitions with minimum so far at the end of string traversal. This approach will be exponential in time.

An efficient solution is to use Dynamic Programming. A 1-D dp table is created in which dp[i] stores minimum number of partitions required to split string str[i..n-1] into substrings that are power of 4 or 6. Suppose we are at index i and str[i..j] is power of 4 or 6, then minimum number of partitions will be minimum number of partitions to split str[j+1..n-1] plus one partition to split str[i..j] from string, that is dp[j+1] + 1. Hence the recurrence relation for (j!=(n-1)) and (dp[j + 1]!=-1) will be: 

dp[i] = min(dp[i], dp[j + 1] + 1)

Implementation:  

C++




// CPP program for Minimum splits in a
//string such that substring is a power of 4 or 6.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if given number
// is power of another number or not.
bool isPowerOf(long val, int base)
{
 
    // Divide given number repeatedly
    // by base value.
    while (val > 1) {
        if (val % base != 0)
            return false; // not a power
        val /= base;
    }
 
    return true;
}
 
// Function to find minimum number of
// partitions of given binary string
// so that each partition is power of 4 or 6.
int numberOfPartitions(string binaryNo)
{
    int i, j, n = binaryNo.length();
 
    // Variable to store integer value of
    // given binary string partition.
    long val;
 
    // DP table to store results of
    // partitioning done at differentindices.
    int dp[n];
 
    // If the last digit is 1, hence 4^0=1 and 6^0=1
    dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1;
 
    // Fix starting position for partition
    for (i = n - 2; i >= 0; i--) {
        val = 0;
 
        // Binary representation
        // with leading zeroes is not allowed.
        if ((binaryNo[i] - '0') == 0) {
            dp[i] = -1;
            continue;
        }
 
        dp[i] = INT_MAX;
 
        // Iterate for all different partitions starting from i
        for (j = i; j < n; j++) {
 
            // Find integer value of current
            // binary partition.
            val = (val * 2) + (long)(binaryNo[j] - '0');
 
            // Check if the value is a power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) || isPowerOf(val, 6)) {
                if (j == n - 1) {
                    dp[i] = 1;
                }
                else {
                    if (dp[j + 1] != -1)
                        dp[i] = min(dp[i], dp[j + 1] + 1);
                }
            }
        }
 
        // If no partitions are possible, then
        // make dp[i] = -1 to represent this.
        if (dp[i] == INT_MAX)
            dp[i] = -1;
    }
 
    return dp[0];
}
 
// Driver code
int main()
{
    string binaryNo = "100110110";
    cout << numberOfPartitions(binaryNo);
    return 0;
}
 
 

Java




// Java program for Minimum splits
// in a string such that substring
// is a power of 4 or 6.
import java.io.*;
 
class GFG
{
    static boolean isPowerOf(long val,
                             int base)
{
 
    // Divide given number
    // repeatedly by base value.
    while (val > 1)
    {
        if (val % base != 0)
            return false; // not a power
        val /= base;
    }
 
    return true;
}
 
// Function to find minimum
// number of partitions of
// given binary string so that
// each partition is power
// of 4 or 6.
static int numberOfPartitions(String binaryNo)
{
    int i, j, n = binaryNo.length();
 
    // Variable to store integer
    // value of given binary
    // string partition.
    long val;
 
    // DP table to store results
    // of partitioning done at
    // differentindices.
    int dp[] = new int[n];
 
    // If the last digit is 1,
    // hence 4^0=1 and 6^0=1
    dp[n - 1] = (((binaryNo.charAt(n - 1) -
                               '0') == 0) ?
                                   -1 : 1);
 
    // Fix starting position
    // for partition
    for (i = n - 2; i >= 0; i--)
    {
        val = 0;
 
        // Binary representation
        // with leading zeroes
        // is not allowed.
        if ((binaryNo.charAt(i) - '0') == 0)
        {
            dp[i] = -1;
            continue;
        }
 
        dp[i] = Integer.MAX_VALUE;
 
        // Iterate for all different
        // partitions starting from i
        for (j = i; j < n; j++)
        {
 
            // Find integer value of
            // current binary partition.
            val = (val * 2) +
                  (long)(binaryNo.charAt(j) - '0');
 
            // Check if the value is a
            // power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) ||
                isPowerOf(val, 6))
            {
                if (j == n - 1)
                {
                    dp[i] = 1;
                }
                else
                {
                    if (dp[j + 1] != -1)
                        dp[i] = Math.min(dp[i],
                                         dp[j + 1] + 1);
                }
            }
        }
 
        // If no partitions are possible,
        // then make dp[i] = -1 to
        // represent this.
        if (dp[i] == Integer.MAX_VALUE)
            dp[i] = -1;
    }
 
    return dp[0];
}
 
// Driver code
public static void main (String[] args)
{
    String binaryNo = "100110110";
    System.out.println(numberOfPartitions(binaryNo));
}
}
 
// This code is contributed
// by shiv_bhakt.
 
 

Python 3




# Python 3 program for Minimum
# splits in a string such that
# substring is a power of 4 or 6.
 
import sys
 
# Function to find if given number
# is power of another number or not.
def isPowerOf(val, base):
 
    # Divide given number repeatedly
    # by base value.
    while (val > 1):
        if (val % base != 0):
            return False # not a power
        val //= base
 
    return True
 
# Function to find minimum number of
# partitions of given binary string
# so that each partition is power of 4 or 6.
def numberOfPartitions(binaryNo):
 
    n = len(binaryNo)
 
    # DP table to store results of
    # partitioning done at differentindices.
    dp = [0] * n
 
    # If the last digit is 1, hence 4^0=1 and 6^0=1
    if ((ord(binaryNo[n - 1]) - ord('0')) == 0) :
        dp[n - 1] = -1
    else:
        dp[n - 1] = 1
 
    # Fix starting position for partition
    for i in range( n - 2, -1, -1):
        val = 0
 
        # Binary representation
        # with leading zeroes is not allowed.
        if ((ord(binaryNo[i]) - ord('0')) == 0):
            dp[i] = -1
            continue
 
        dp[i] = sys.maxsize
 
        # Iterate for all different partitions starting from i
        for j in range(i, n):
 
            # Find integer value of current
            # binary partition.
            val = (val * 2) + (ord(binaryNo[j]) - ord('0'))
 
            # Check if the value is a power of 4 or 6 or not
            # apply recurrence relation
            if (isPowerOf(val, 4) or isPowerOf(val, 6)):
                if (j == n - 1):
                    dp[i] = 1
                 
                else :
                    if (dp[j + 1] != -1):
                        dp[i] = min(dp[i], dp[j + 1] + 1)
 
        # If no partitions are possible, then
        # make dp[i] = -1 to represent this.
        if (dp[i] == sys.maxsize):
            dp[i] = -1
 
    return dp[0]
 
# Driver code
if __name__ == "__main__":
     
    binaryNo = "100110110"
    print(numberOfPartitions(binaryNo))
     
# This code is contributed by Ita_c.   
 
 

C#




// C# program for Minimum splits
// in a string such that substring
// is a power of 4 or 6.
 
using System;
  
class GFG
{
    static bool isPowerOf(long val, int b)
{
  
    // Divide given number
    // repeatedly by base value.
    while (val > 1)
    {
        if (val % b != 0)
            return false; // not a power
        val /= b;
    }
  
    return true;
}
  
// Function to find minimum
// number of partitions of
// given binary string so that
// each partition is power
// of 4 or 6.
static int numberOfPartitions(string binaryNo)
{
    int i, j, n = binaryNo.Length;
  
    // Variable to store integer
    // value of given binary
    // string partition.
    long val;
  
    // DP table to store results
    // of partitioning done at
    // differentindices.
    int[] dp = new int[n];
  
    // If the last digit is 1,
    // hence 4^0=1 and 6^0=1
    dp[n - 1] = (((binaryNo[n - 1] -
                               '0') == 0) ?
                                   -1 : 1);
  
    // Fix starting position
    // for partition
    for (i = n - 2; i >= 0; i--)
    {
        val = 0;
  
        // Binary representation
        // with leading zeroes
        // is not allowed.
        if ((binaryNo[i] - '0') == 0)
        {
            dp[i] = -1;
            continue;
        }
  
        dp[i] = int.MaxValue;
  
        // Iterate for all different
        // partitions starting from i
        for (j = i; j < n; j++)
        {
  
            // Find integer value of
            // current binary partition.
            val = (val * 2) +
                  (long)(binaryNo[j] - '0');
  
            // Check if the value is a
            // power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) ||
                isPowerOf(val, 6))
            {
                if (j == n - 1)
                {
                    dp[i] = 1;
                }
                else
                {
                    if (dp[j + 1] != -1)
                        dp[i] = Math.Min(dp[i],
                                         dp[j + 1] + 1);
                }
            }
        }
  
        // If no partitions are possible,
        // then make dp[i] = -1 to
        // represent this.
        if (dp[i] == int.MaxValue)
            dp[i] = -1;
    }
  
    return dp[0];
}
  
// Driver code
public static void Main ()
{
    string binaryNo = "100110110";
    Console.Write(numberOfPartitions(binaryNo));
}
}
 
 

Javascript




<script>
 
// Javascript program for Minimum splits in a
//string such that substring is a power of 4 or 6.
 
// Function to find if given number
// is power of another number or not.
function isPowerOf(val, base)
{
 
    // Divide given number repeatedly
    // by base value.
    while (val > 1) {
        if (val % base != 0)
            return false; // not a power
        val /= base;
    }
 
    return true;
}
 
// Function to find minimum number of
// partitions of given binary string
// so that each partition is power of 4 or 6.
function numberOfPartitions(binaryNo)
{
    var i, j, n = binaryNo.length;
 
    // Variable to store integer value of
    // given binary string partition.
    var val;
 
    // DP table to store results of
    // partitioning done at differentindices.
    var dp = Array(n);
 
    // If the last digit is 1, hence 4^0=1 and 6^0=1
    dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1;
 
    // Fix starting position for partition
    for (i = n - 2; i >= 0; i--) {
        val = 0;
 
        // Binary representation
        // with leading zeroes is not allowed.
        if ((binaryNo[i] - '0') == 0) {
            dp[i] = -1;
            continue;
        }
 
        dp[i] = 1000000000;
 
        // Iterate for all different partitions starting from i
        for (j = i; j < n; j++) {
 
            // Find integer value of current
            // binary partition.
            val = (val * 2) + (binaryNo[j] - '0');
 
            // Check if the value is a power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) || isPowerOf(val, 6)) {
                if (j == n - 1) {
                    dp[i] = 1;
                }
                else {
                    if (dp[j + 1] != -1)
                        dp[i] = Math.min(dp[i], dp[j + 1] + 1);
                }
            }
        }
 
        // If no partitions are possible, then
        // make dp[i] = -1 to represent this.
        if (dp[i] == 1000000000)
            dp[i] = -1;
    }
 
    return dp[0];
}
 
// Driver code
var binaryNo = "100110110";
document.write( numberOfPartitions(binaryNo));
 
// This code is contributed by itsok.
</script>
 
 
Output
3

 Complexity Analysis:

  • Time Complexity: O(n^2*log(x)), x = largest power of 4 or 6 obtainable from input string. 
  • Auxiliary Space: O(n)


Next Article
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
author
nik1996
Improve
Article Tags :
  • Algorithms
  • DSA
  • Dynamic Programming
  • Strings
Practice Tags :
  • Algorithms
  • Dynamic Programming
  • Strings

Similar Reads

  • 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
  • Minimum flips required in a binary string such that all K-size substring contains 1
    Given a binary string str of size N and a positive integer K, the task is to find the minimum number of flips required to make all substring of size K contain at least one '1'.Examples: Input: str = "0001", K = 2 Output: 1 Explanation: Flipping the bit at index 1 modifies str to "0101". All substrin
    11 min read
  • Minimum shifts of substrings of 1s required to group all 1s together in a given Binary string
    Given a binary string S of length N, the task is to print the minimum number of indices, substrings consisting only of 1s are required to be shifted such that all 1s present in the string are grouped together. Examples: Input: S = "00110111011"Output: 2Explanation: Operation 1: Shift substring {S[2]
    6 min read
  • Minimum number of sub-strings of a string such that all are power of 5
    Given a binary string str. The task is to find the smallest positive integer C such that the binary string can be cut into C pieces (sub-strings) and each sub-string should be a power of 5 with no leading zeros.Examples: Input: str = "101101101" Output: 3 The string "101101101" can be cut into three
    10 min read
  • Split the binary string into substrings with equal number of 0s and 1s
    Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
    8 min read
  • Minimum steps to remove substring 010 from a binary string
    Given a binary string, the task is to count the minimum steps to remove substring "010" from this binary string. Examples: Input: binary_string = "0101010" Output: 2 Switching 0 to 1 at index 2 and index 4 will remove the substring 010. Hence the number of steps needed is 2. Input: binary_string = "
    4 min read
  • Check if substring "10" occurs in the given binary string in all possible replacements of '?' with 1 or 0
    Given a string S consisting of only '0', '1' and '?', the task is to check if there exists a substring "10" in every possible replacement of the character '?' with either 1 or 0. Examples: Input: S = "1?0"Output: YesExplanation:Following are all the possible replacements of '?': Replacing the '?' wi
    7 min read
  • Minimum size binary string required such that probability of deleting two 1's at random is 1/X
    Given a value X, the task is to find a minimum size binary string, such that if any 2 characters are deleted at random, the probability that both the characters will be '1' is 1/X. Print the size of such binary string. Example: Input: X = 2 Output: 4 Explanation: Let the binary string be "0111". Pro
    6 min read
  • Minimum Repetitions of s1 such that s2 is a substring of it
    Given two strings s1 and s2, the task is to find the minimum number of times s1 has to be repeated such that s2 is a substring of it. If no such solution exists, print -1. Examples: Input: s1 = "abcd", s2 = "cdabcdab"Output: 3 Explanation: After repeating s1 three times, s1 will become “abcdabcdabcd
    15+ min read
  • Periodic Binary String With Minimum Period and a Given Binary String as Subsequence.
    Periodic Binary String: A Binary string is called periodic if it can be written as a repetition of a binary string of smaller or same length. For example, 101010 is a periodic binary string with period 10 as we can get the string by repeatedly appending 10 to itself. In general, the string S with pe
    5 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