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 String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimize deletions such that sum of position of characters is at most K
Next article icon

Minimum partitions of String such that each part is at most K

Last Updated : 26 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 45
Output: 2
Explanation: One possible way is to partition as 3, 45, 6. 
Another possibility is 3, 4, 5, 6, which uses 3 partition. 
No configuration needs less than 2 partitions. Hence, the answer is 2.

Input: S = "7891634", K = 21
Output: 5
Explanation: The minimum number of partitions is 
7, 8, 9, 16, 3, 4, which uses 5 partitions.

Input: S = "67142849", K = 39
Output: 5

 

Approach: The approach to this problem is based on the below idea:

Make each partition have a value as large as possible with an upper limit of K.
An edge case is if it’s impossible to partition the string. It will happen if the maximum digit in the string is larger than K..

Follow the below steps to solve this problem:

  • Iterate over the characters of the string from i = 0 to N-1:
    • If the number formed till now is at most K then keep on continuing with this partition. Otherwise, increase the number of partitions.
    • Otherwise, If the current digit is larger than K, return -1.
  • The last number may not have been accounted for after iterating the string, so check if the last partition is greater than 0. If yes, then increment number of partitions (say ans) by 1.
  • Finally, return ans - 1, as we need to find the minimum number of partitions, which is one less than the numbers formed.

Below is the implementation of the above approach:

C++
// C++ program for above implementation  #include <bits/stdc++.h> using namespace std;  // Function to count the minimum number // of partitions int minimumCommas(string& s, int k) {     // Length of the string 's'.     int n = s.size();      // Store the current number formed.     long long cur = 0;      // 'ans' stores the final answer.     int ans = 0;      // Iterate over the string.     for (int i = 0; i < n; ++i) {          // If we can include this digit in the         // current number         if (cur * 10 + (s[i] - '0') <= k) {              // Include this digit in             // the current number.             cur = cur * 10 + (s[i] - '0');         }         else {              // If 'cur' is '0',             // it's impossible to partition             if (cur == 0 or cur > k) {                  // Return the integer '-1'                 return -1;             }             else {                  // Increment the answer 'ans'                 ans++;                  // Set cur to the current digit                 cur = s[i] - '0';             }         }     }      // If cur > 0, means the last number is cur     if (cur > 0 and cur <= k) {          // Increment the 'ans'         ans++;     }      // Return the number of partitions     return ans - 1; }  // Driver code int main() {     // Input     string S = "7891634";     int K = 21;      // Function call     cout << minimumCommas(S, K);     return 0; } 
Java
// JAVA program for above implementation import java.util.*; class GFG {      // Function to count the minimum number     // of partitions     public static int minimumCommas(String s, int k)     {                // Length of the string 's'.         int n = s.length();          // Store the current number formed.         long cur = 0;          // 'ans' stores the final answer.         int ans = 0;          // Iterate over the string.         for (int i = 0; i < n; ++i) {             // If we can include this digit in the             // current number             if (cur * 10                     + Character.getNumericValue(s.charAt(i))                 <= k) {                  // Include this digit in                 // the current number.                 cur = cur * 10                       + Character.getNumericValue(                           s.charAt(i));             }             else {                  // If 'cur' is '0',                 // it's impossible to partition                 if (cur == 0 || cur > k) {                      // Return the integer '-1'                     return -1;                 }                 else {                      // Increment the answer 'ans'                     ans++;                      // Set cur to the current digit                     cur = Character.getNumericValue(                         s.charAt(i));                 }             }         }          // If cur > 0, means the last number is cur         if (cur > 0 && cur <= k) {              // Increment the 'ans'             ans++;         }          // Return the number of partitions         return ans - 1;     }      // Driver code     public static void main(String[] args)     {         // Input         String S = "7891634";         int K = 21;          // Function call         System.out.print(minimumCommas(S, K));     } }  // This code is contributed by Taranpreet 
Python3
# Python code for the above approach  # Function to count the minimum number # of partitions def minimumCommas(s, k) :          # Length of the string 's'.     n = len(s)      # Store the current number formed.     cur = 0      # 'ans' stores the final answer.     ans = 0      # Iterate over the string.     for i in range(n) :          # If we can include this digit in the         # current number         if (cur * 10 + (ord(s[i]) - ord('0')) <= k) :              # Include this digit in             # the current number.             cur = cur * 10 + (ord(s[i]) - ord('0'))                  else :              # If 'cur' is '0',             # it's impossible to partition             if (cur == 0 or cur > k) :                  # Return the integer '-1'                 return -1                          else :                  # Increment the answer 'ans'                 ans += 1                  # Set cur to the current digit                 cur = (ord(s[i]) - ord('0'))                                 # If cur > 0, means the last number is cur     if (cur > 0 and cur <= k) :          # Increment the 'ans'         ans += 1           # Return the number of partitions     return ans - 1  # Driver code if __name__ == "__main__":          # Input     S = "7891634"     K = 21      # Function call     print(minimumCommas(S, K))          # This code is contributed by code_hunt. 
C#
// C# program for above implementation using System; class GFG {    // Function to count the minimum number   // of partitions   static int minimumCommas(string s, int k)   {      // Length of the string 's'.     int n = s.Length;      // Store the current number formed.     long cur = 0;      // 'ans' stores the final answer.     int ans = 0;      // Iterate over the string.     for (int i = 0; i < n; ++i) {       // If we can include this digit in the       // current number       if (cur * 10 + (s[i] - '0') <= k) {          // Include this digit in         // the current number.         cur = cur * 10 + (s[i] - '0');       }       else {          // If 'cur' is '0',         // it's impossible to partition         if (cur == 0 || cur > k) {            // Return the integer '-1'           return -1;         }         else {            // Increment the answer 'ans'           ans++;            // Set cur to the current digit           cur = s[i] - '0';         }       }     }      // If cur > 0, means the last number is cur     if (cur > 0 && cur <= k) {        // Increment the 'ans'       ans++;     }      // Return the number of partitions     return ans - 1;   }    // Driver code   public static void Main()   {     // Input     string S = "7891634";     int K = 21;      // Function call     Console.WriteLine(minimumCommas(S, K));   } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script>  // JavaScript program for above implementation  // Function to count the minimum number // of partitions function minimumCommas(s, k) {      // Length of the string 's'.     let n = s.length;      // Store the current number formed.     let cur = 0;      // 'ans' stores the final answer.     let ans = 0;      // Iterate over the string.     for (let i = 0; i < n; ++i) {          // If we can include this digit in the         // current number         if (cur * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0)) <= k) {              // Include this digit in             // the current number.             cur = cur * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));         }         else {              // If 'cur' is '0',             // it's impossible to partition             if (cur == 0 || cur > k) {                  // Return the integer '-1'                 return -1;             }             else {                  // Increment the answer 'ans'                 ans++;                  // Set cur to the current digit                 cur = s.charCodeAt(i) - '0'.charCodeAt(0);             }         }     }      // If cur > 0, means the last number is cur     if (cur > 0 && cur <= k) {          // Increment the 'ans'         ans++;     }      // Return the number of partitions     return ans - 1; }  // Driver code  // Input let S = "7891634"; let K = 21;  // Function call document.write(minimumCommas(S, K));  // This code is contributed // by shinjanpatra  </script> 

Output
5

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Minimize deletions such that sum of position of characters is at most K

R

rohit768
Improve
Article Tags :
  • Strings
  • Greedy
  • DSA
  • partition
Practice Tags :
  • Greedy
  • Strings

Similar Reads

  • 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
  • Minimum value of K such that each substring of size K has the given character
    Given a string of lowercase letters S a character c. The task is to find minimum K such that every substring of length K contains the given character c. If there is no such K possible, return -1.Examples: Input: S = "abdegb", ch = 'b'Output: 4 Explanation:Consider the value of K as 4. Now, every sub
    12 min read
  • Minimize deletions such that sum of position of characters is at most K
    Given a string S consisting of lower case letters and an integer K, the task is to remove minimum number of letters from the string, such that the sum of alphabetic ordering of the letters present in the string is at most K. Examples : Input: S = "abca", K = 2Output: "aa"Explanation: Initial sum for
    8 min read
  • Minimum removal of characters required such that permutation of given string is a palindrome
    Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome. Examples: Input: str="aba"Output: 1Explanation: Removing 'b' generates a palindromic string "a
    7 min read
  • Convert to a string that is repetition of a substring of k length
    Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters. Examples: Input: str = "bdac", k
    7 min read
  • Remove k characters in a String such that ASCII sum is minimum
    Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2
    7 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
  • Minimum cost to partition the given binary string
    Given a binary string str and an integer K, the task is to find the minimum cost required to partition the string into exactly K segments when the cost of each segment is the product of the number of set bits with the number of unset bits and total cost is sum of cost of all the individual segments.
    10 min read
  • Minimum length of string having all permutation of given string.
    Given a string [Tex]S [/Tex]where [Tex]1\leq length\; of\; S\leq 26 [/Tex]. Assume that all the characters in [Tex]S [/Tex]are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present
    4 min read
  • Maximize partitions such that no two substrings have any common character
    Given string s of size n, the task is to print the number of substrings formed after maximum possible partitions such that no two substrings have a common character. Examples: Input : s = "ababcbacadefegdehijhklij" Output : 3 Explanation: Partitioning at the index 8 and at 15 produces three substrin
    1 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