Leetcode 2522: Partition String Into Substrings With Values at Most K

grid47
grid47
Exploring patterns and algorithms
Feb 28, 2024 7 min read

Given a string s consisting of digits between 1 and 9, and an integer k, you need to partition the string into the fewest possible substrings such that the value of each substring is less than or equal to k. Each substring must consist of contiguous digits and must be interpreted as an integer. If it’s not possible to partition the string in such a way, return -1.
Problem
Approach
Steps
Complexity
Input: You are given a string `s` containing digits from '1' to '9' and an integer `k`. The task is to partition the string into the fewest number of substrings where each substring has a value less than or equal to `k`.
Example: s = "123456", k = 50
Constraints:
• 1 <= s.length <= 10^5
• 1 <= k <= 10^9
Output: Return the minimum number of substrings required to partition the string `s` where the value of each substring is less than or equal to `k`. If it's not possible to partition the string, return `-1`.
Example: Output: 4
Constraints:
• The output should be an integer representing the minimum number of substrings or -1 if no valid partition exists.
Goal: The goal is to find the minimum number of substrings where each substring has a value less than or equal to `k`. If such a partition isn't possible, return -1.
Steps:
• Iterate through the string and attempt to form the largest valid substrings starting from the current position.
• For each substring, check if its value is less than or equal to `k`.
• If a valid substring is found, continue to form the next substring from the remaining characters.
• If a substring exceeds `k`, try partitioning earlier and minimize the number of substrings.
Goal: The input string `s` has a length of at most 10^5, and each character in `s` is a digit between 1 and 9. The value of `k` is at most 10^9.
Steps:
• 1 <= s.length <= 10^5
• 1 <= k <= 10^9
Assumptions:
• Each digit in the string `s` is between '1' and '9', so the string contains no zero digits.
Input: s = "123456", k = 50
Explanation: The string can be partitioned into substrings '12', '34', '5', and '6'. Each substring is less than or equal to 50, so the minimum number of substrings is 4.

Input: s = "987654", k = 100
Explanation: The string can be partitioned into substrings '9', '8', '7', '6', and '54'. Each substring is less than or equal to 100, so the minimum number of substrings is 5.

Input: s = "238182", k = 5
Explanation: It's not possible to partition the string such that all substrings are less than or equal to 5, so the answer is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus