Partition String Into Substrings With Values at Most K Problem
Description
LeetCode Problem 2522.
You are given a string s consisting of digits from 1 to 9 and an integer k.
A partition of a string s is called good if:
- Each digit of
sis part of exactly one substring. - The value of each substring is less than or equal to
k.
Return the minimum number of substrings in a good partition of s. If no good partition of s exists, return -1.
Note that:
- The value of a string is its result when interpreted as an integer. For example, the value of
"123"is123and the value of"1"is1. - A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "165462", k = 60
Output: 4
Explanation: We can partition the string into substrings "16", "54", "6", and "2". Each substring has a value less than or equal to k = 60.
It can be shown that we cannot partition the string into less than 4 substrings.
Example 2:
Input: s = "238182", k = 5
Output: -1
Explanation: There is no good partition for this string.
Constraints:
1 <= s.length <= 10^5s[i]is a digit from'1'to'9'.1 <= k <= 10^9
Solution
Approach: Memoized Search
Let dfs(i) be the minimum number of substrings needed to partition s[i:]. Then dfs(n) = 0, and for i < n we extend a substring from i one digit at a time, keeping its numeric value v; as soon as v > k we stop (more digits only make it bigger). For every end j with v <= k we try dfs(j + 1), take the minimum and add 1 for the current piece.
If dfs(0) is still infinite, no partition exists and the answer is -1. Memoizing on i keeps each state computed once, and since k < 10^9 a substring never has more than 9 digits, so each state tries at most 9 ends.
Complexity: O(n) time and O(n) space, where n is the length of s.
from functools import lru_cache
from math import inf
class Solution:
def minimumPartition(self, s: str, k: int) -> int:
@lru_cache(None)
def dfs(i):
if i >= n:
return 0
res, v = inf, 0
for j in range(i, n):
v = v * 10 + int(s[j])
if v > k:
break
res = min(res, dfs(j + 1))
return res + 1
n = len(s)
ans = dfs(0)
return ans if ans < inf else -1