Leetcode #2522: Partition String Into Substrings With Values at Most K
In this guide, we solve Leetcode #2522 Partition String Into Substrings With Values at Most K in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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.
It can be shown that we cannot partition the string into less than 4 substrings.
Python Solution
class Solution:
def minimumPartition(self, s: str, k: int) -> int:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.