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:
Minimum splits in a binary string such that every substring is a power of 4 or 6.
Next article icon

Minimum number of sub-strings of a string such that all are power of 5

Last Updated : 28 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 binary strings “101”, “101”, “101” 
each of which is a power of 5.
Input: str = “1111101” 
Output: 1 
The string “1111101” can be cut into one binary string “1111101” which is 
125 in decimal and a power of 5.
Input: str = “00000” 
Output: -1 
Strings of only zeroes is equivalent to 0 which is not a power of 5. 
 

 

Approach: This problem is a simple variation of the longest increasing sub-sequence. 
Iterate from i = 1 and for every str[j…i] where j = 0 & j < i, we check if the number formed from str[j..i] is a power of 5 then we update the dp[] array with the value of the lowest possible cut size value. After confirming that the number formed from str[j..i] in decimal is a power of 5 we calculate dp[i] = min(dp[i], dp[j] + 1). 
This technique is pretty similar to finding the longest increasing sub-sequence.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll unsigned long long
 
// Function that returns true
// if n is a power of 5
bool ispower(ll n)
{
    if (n < 125)
        return (n == 1 || n == 5 || n == 25);
    if (n % 125 != 0)
        return false;
    else
        return ispower(n / 125);
}
 
// Function to return the decimal
// value of binary equivalent
ll number(string s, int i, int j)
{
    ll ans = 0;
    for (int x = i; x < j; x++) {
        ans = ans * 2 + (s[x] - '0');
    }
    return ans;
}
 
// Function to return the minimum cuts required
int minCuts(string s, int n)
{
    int dp[n + 1];
 
    // Allocating memory for dp[] array
    memset(dp, n + 1, sizeof(dp));
    dp[0] = 0;
 
    // From length 1 to n
    for (int i = 1; i <= n; i++) {
 
        // If previous character is '0' then ignore
        // to avoid number with leading 0s.
        if (s[i - 1] == '0')
            continue;
        for (int j = 0; j < i; j++) {
 
            // Ignore s[j] = '0' starting numbers
            if (s[j] == '0')
                continue;
 
            // Number formed from s[j....i]
            ll num = number(s, j, i);
 
            // Check for power of 5
            if (!ispower(num))
                continue;
 
            // Assigning min value to get min cut possible
            dp[i] = min(dp[i], dp[j] + 1);
        }
    }
 
    // (n + 1) to check if all the strings are traversed
    // and no divisible by 5 is obtained like 000000
    return ((dp[n] < n + 1) ? dp[n] : -1);
}
 
// Driver code
int main()
{
    string s = "101101101";
    int n = s.length();
    cout << minCuts(s, n);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function that returns true
    // if n is a power of 5
    static boolean ispower(long n)
    {
        if (n < 125)
        {
            return (n == 1 || n == 5 || n == 25);
        }
        if (n % 125 != 0)
        {
            return false;
        }
        else
        {
            return ispower(n / 125);
        }
    }
 
    // Function to return the decimal
    // value of binary equivalent
    static long number(String s, int i, int j)
    {
        long ans = 0;
        for (int x = i; x < j; x++)
        {
            ans = ans * 2 + (s.charAt(x) - '0');
        }
        return ans;
    }
 
    // Function to return the minimum cuts required
    static int minCuts(String s, int n)
    {
        int[] dp = new int[n + 1];
 
        // Alongocating memory for dp[] array
        Arrays.fill(dp, n+1);
        dp[0] = 0;
 
        // From length 1 to n
        for (int i = 1; i <= n; i++)
        {
 
            // If previous character is '0' then ignore
            // to avoid number with leading 0s.
            if (s.charAt(i - 1) == '0')
            {
                continue;
            }
            for (int j = 0; j < i; j++)
            {
 
                // Ignore s[j] = '0' starting numbers
                if (s.charAt(j) == '0')
                {
                    continue;
                }
 
                // Number formed from s[j....i]
                long num = number(s, j, i);
 
                // Check for power of 5
                if (!ispower(num))
                {
                    continue;
                }
 
                // Assigning min value to get min cut possible
                dp[i] = Math.min(dp[i], dp[j] + 1);
            }
        }
 
        // (n + 1) to check if all the Strings are traversed
        // and no divisible by 5 is obtained like 000000
        return ((dp[n] < n + 1) ? dp[n] : -1);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String s = "101101101";
        int n = s.length();
        System.out.println(minCuts(s, n));
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Python 3




# Python 3 implementation of the approach
  
# Function that returns true
# if n is a power of 5
def ispower( n):
    if (n < 125):
        return (n == 1 or n == 5 or n == 25)
    if (n % 125 != 0):
        return 0
    else:
        return ispower(n // 125)
 
  
# Function to return the decimal
# value of binary equivalent
def number(s, i, j):
    ans = 0
    for x in range( i, j) :
        ans = ans * 2 + (ord(s[x]) - ord('0'))
    return ans
 
# Function to return the minimum cuts required
def minCuts(s, n):
  
    # Allocating memory for dp[] array
    dp=[n+1 for i in range(n+1)]
    dp[0] = 0;
  
    # From length 1 to n
    for i in range(1, n+1) :
  
        # If previous character is '0' then ignore
        # to avoid number with leading 0s.
        if (s[i - 1] == '0'):
            continue
        for j in range(i) :
  
            # Ignore s[j] = '0' starting numbers
            if (s[j] == '0'):
                continue
  
            # Number formed from s[j....i]
            num = number(s, j, i)
  
            # Check for power of 5
            if (not ispower(num)):
                continue
  
            # Assigning min value to get min cut possible
            dp[i] = min(dp[i], dp[j] + 1)
  
    # (n + 1) to check if all the strings are traversed
    # and no divisible by 5 is obtained like 000000
    if dp[n] < n + 1:
        return dp[n]
    else:
        return  -1
  
# Driver code
if __name__== "__main__":
    s = "101101101"
    n = len(s)
    print(minCuts(s, n))
 
# This code is contributed by ChitraNayal
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function that returns true
    // if n is a power of 5
    static Boolean ispower(long n)
    {
        if (n < 125)
        {
            return (n == 1 || n == 5 || n == 25);
        }
        if (n % 125 != 0)
        {
            return false;
        }
        else
        {
            return ispower(n / 125);
        }
    }
 
    // Function to return the decimal
    // value of binary equivalent
    static long number(String s, int i, int j)
    {
        long ans = 0;
        for (int x = i; x < j; x++)
        {
            ans = ans * 2 + (s[x] - '0');
        }
        return ans;
    }
 
    // Function to return the minimum cuts required
    static int minCuts(String s, int n)
    {
        int[] dp = new int[n + 1];
 
        // Alongocating memory for dp[] array
        for (int i = 0; i <= n; i++)
            dp[i]=n+1;
        dp[0] = 0;
 
        // From length 1 to n
        for (int i = 1; i <= n; i++)
        {
 
            // If previous character is '0' then ignore
            // to avoid number with leading 0s.
            if (s[i - 1] == '0')
            {
                continue;
            }
            for (int j = 0; j < i; j++)
            {
 
                // Ignore s[j] = '0' starting numbers
                if (s[j] == '0')
                {
                    continue;
                }
 
                // Number formed from s[j....i]
                long num = number(s, j, i);
 
                // Check for power of 5
                if (!ispower(num))
                {
                    continue;
                }
 
                // Assigning min value to get min cut possible
                dp[i] = Math.Min(dp[i], dp[j] + 1);
            }
        }
 
        // (n + 1) to check if all the Strings are traversed
        // and no divisible by 5 is obtained like 000000
        return ((dp[n] < n + 1) ? dp[n] : -1);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String s = "101101101";
        int n = s.Length;
        Console.WriteLine(minCuts(s, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */
 
 

PHP




<?php
// PHP implementation of the approach
 
// Function that returns true
// if n is a power of 5
function ispower($n)
{
    if ($n < 125)
        return ($n == 1 || $n == 5 || $n == 25);
    if ($n % 125 != 0)
        return false;
    else
        return ispower($n / 125);
}
 
// Function to return the decimal
// value of binary equivalent
function number($s, $i, $j)
{
    $ans = 0;
    for ($x = $i; $x < $j; $x++)
    {
        $ans = $ans * 2 + (ord($s[$x]) - ord('0'));
    }
    return $ans;
}
 
// Function to return the minimum cuts required
function minCuts($s, $n)
{
    // Allocating memory for dp[] array
    $dp = array_fill(0,$n + 1,$n + 1);
     
    $dp[0] = 0;
 
    // From length 1 to n
    for ($i = 1; $i <= $n; $i++)
    {
 
        // If previous character is '0' then ignore
        // to avoid number with leading 0s.
        if ($s[$i - 1] == '0')
            continue;
        for ($j = 0; $j < $i; $j++)
        {
 
            // Ignore s[j] = '0' starting numbers
            if ($s[$j] == '0')
                continue;
 
            // Number formed from s[j....i]
            $num = number($s, $j, $i);
 
            // Check for power of 5
            if (!ispower($num))
                continue;
 
            // Assigning min value to get min cut possible
            $dp[$i] = min($dp[$i], $dp[$j] + 1);
        }
    }
 
    // (n + 1) to check if all the strings are traversed
    // and no divisible by 5 is obtained like 000000
    return (($dp[$n] < $n + 1) ? $dp[$n] : -1);
}
 
    // Driver code
    $s = "101101101";
    $n = strlen($s);
    echo minCuts($s, $n);
 
    // This code is contributed by AnkitRai01
 
?>
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
// Function that returns true
// if n is a power of 5
function ispower(n)
{
    if (n < 125)
        return (n == 1 || n == 5 || n == 25);
    if (n % 125 != 0)
        return false;
    else
        return ispower(parseInt(n / 125));
}
 
// Function to return the decimal
// value of binary equivalent
function number(s, i, j)
{
    var ans = 0;
    for (var x = i; x < j; x++) {
        ans = ans * 2 + (s[x] - '0');
    }
    return ans;
}
 
// Function to return the minimum cuts required
function minCuts(s, n)
{
    var dp = Array(n+1).fill(n+1);
    dp[0] = 0;
 
    // From length 1 to n
    for (var i = 1; i <= n; i++) {
 
        // If previous character is '0' then ignore
        // to avoid number with leading 0s.
        if (s[i - 1] == '0')
            continue;
        for (var j = 0; j < i; j++) {
 
            // Ignore s[j] = '0' starting numbers
            if (s[j] == '0')
                continue;
 
            // Number formed from s[j....i]
            var num = number(s, j, i);
 
            // Check for power of 5
            if (!ispower(num))
                continue;
 
            // Assigning min value to get min cut possible
            dp[i] = Math.min(dp[i], dp[j] + 1);
        }
    }
 
    // (n + 1) to check if all the strings are traversed
    // and no divisible by 5 is obtained like 000000
    return ((dp[n] < n + 1) ? dp[n] : -1);
}
 
// Driver code
var s = "101101101";
var n = s.length;
document.write( minCuts(s, n));
 
</script>
 
 
Output: 
3

 

Time complexity: O(n2) 
Space complexity: O(n)
 



Next Article
Minimum splits in a binary string such that every substring is a power of 4 or 6.
author
md1844
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Strings
  • substring
Practice Tags :
  • Dynamic Programming
  • Strings

Similar Reads

  • 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
  • Minimum partitions of String such that each part is at most K
    Given a string S of size N consisting of numerical digits 1-9 and a positive integer K, the task is to minimize the partitions of the string such that each part is at most K. If it’s impossible to partition the string print -1. Examples: Input: S = "3456", K = 45Output: 2Explanation: One possible wa
    8 min read
  • Minimum deletions to make String S the Subsequence of any String in the Set D
    Given a string S and a set of strings D, the task is to find the minimum number of deletions required to make the string S a subsequence of any string in the set D, such that the deletion can only be performed on the substring of S. Examples: Input: string S = "abcdefg", vector<string> D = {"a
    13 min read
  • Sum of all substrings of a string representing a number | Set 1
    Given an integer represented as a string, we need to get the sum of all possible substrings of this string Examples: Input: num = “1234”Output: 1670Explanation: Sum = 1 + 2 + 3 + 4 + 12 + 23 +34 + 123 + 234 + 1234 = 1670 Input: num = “421”Output: 491Explanation: Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
    11 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
  • Lengths of maximized partitions of a string such that each character of the string appears in one substring
    Given string str of lowercase alphabets, split the given string into as many substrings as possible such that each character from the given string appears in a single substring. The task is to print the length of all such partitions. Examples: Input: str = "acbbcc"Output: 1 5Explanation:Possible par
    8 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
  • Form minimum number of Palindromic Strings from a given string
    Given a string S, the task is to divide the characters of S to form minimum number of palindromic strings. Note: There can be multiple correct answers. Examples: Input: S = "geeksforgeeks"Output: {eegksrskgee, o, f} Explanation: There should be at least 3 strings "eegksrskgee", "o", "f". All 3 forme
    12 min read
  • Minimum number of subsequences required to convert one string to another
    Given two strings A and B consisting of only lowercase letters, the task is to find the minimum number of subsequences required from A to form B. Examples: Input: A = "abbace" B = "acebbaae" Output: 3 Explanation: Sub-sequences "ace", "bba", "ae" from string A used to form string B Input: A = "abc"
    8 min read
  • Minimum number of palindromic subsequences to be removed to empty a binary string
    Given a binary string, count minimum number of subsequences to be removed to make it an empty string. Examples : Input: str[] = "10001" Output: 1 Since the whole string is palindrome, we need only one removal. Input: str[] = "10001001" Output: 2 We can remove the middle 1 as first removal, after fir
    6 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