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 st 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 partitionsint 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) { // 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) { // Increment the 'ans' ans++; } // Return the number of partitions return ans - 1;} // Driver codeint main(){ // Input string S = "7891634"; int K = 21; // Function call cout << minimumCommas(S, K); return 0;} |
5
Time Complexity: O(N)
Auxiliary Space: O(1)

