Partition String Into Substrings With Values at Most K - Problem
You're tasked with breaking down a string of digits into the minimum number of valid pieces. Given a string
s containing only digits from 1 to 9 and an integer k, you need to partition the string such that:
- Every digit belongs to exactly one substring
- When each substring is interpreted as an integer, its value must be โค
k - You want the fewest possible substrings
s = "165334" and k = 60, you could partition it as ["1", "6", "53", "3", "4"] (5 parts) or ["16", "53", "34"] (3 parts). The second partition is better!
Return the minimum number of substrings needed, or -1 if no valid partition exists. Input & Output
example_1.py โ Basic partition
$
Input:
s = "165334", k = 60
โบ
Output:
3
๐ก Note:
We can partition as ["16", "53", "34"]. All values (16, 53, 34) are โค 60, giving us 3 partitions total.
example_2.py โ Impossible case
$
Input:
s = "238", k = 4
โบ
Output:
-1
๐ก Note:
No valid partition exists because even single digits like 8 exceed k=4, making it impossible to satisfy the constraint.
example_3.py โ Single character partitions
$
Input:
s = "123", k = 1
โบ
Output:
3
๐ก Note:
Each digit must be its own partition: ["1", "2", "3"], since combining any two would exceed k=1.
Constraints
- 1 โค s.length โค 105
- s consists only of digits from '1' to '9'
- 1 โค k โค 109
- No leading zeros in any partition
Visualization
Tap to expand
Understanding the Visualization
1
Greedy Path
Takes longest valid substring at each step
2
Exhaustive Search
Explores all possible partitions
3
Efficiency Gain
Greedy is O(n) vs O(2^n) for brute force
Key Takeaway
๐ฏ Key Insight: Greedy algorithm achieves optimal results in linear time by always choosing the longest valid substring, proving that being locally optimal leads to global optimality in this problem.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code