Tuesday, November 19, 2024
Google search engine
HomeData Modelling & AIMinimum partitions of String such that each part is at most K

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 = 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)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments