VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-partitions-of-string-such-that-each-part-is-at-most-k/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 26 Sep, 2022

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:


Output
5

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

Comment
Article Tags: