Partition String Into Substrings With Values at Most K — LeetCode 2522 Python Solution

MediumGreedyStringDynamic Programming
Problem
#2522
Pattern
Greedy
Reading time
3 min

The problem

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 s is part of exactly one substring.

Example

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.

Python solution

Python
class Solution:
    def minimumPartition(self, s: str, k: int) -> int:
        @cache
        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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2522. Partition String Into Substrings With Values at Most K is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2522. Partition String Into Substrings With Values at Most K?
LeetCode 2522. Partition String Into Substrings With Values at Most K is rated Medium on LeetCode.
What is the time complexity of LeetCode 2522. Partition String Into Substrings With Values at Most K?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2522. Partition String Into Substrings With Values at Most K?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2522. Partition String Into Substrings With Values at Most K cover?
LeetCode 2522. Partition String Into Substrings With Values at Most K is tagged Greedy, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview