Partition String Into Substrings With Values at Most K - 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.
  • 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" is 123 and the value of "1" is 1.
  • A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "165312", k = 60
Output: 4
💡 Note: Optimal partition: ["16", "53", "1", "2"]. Values are [16, 53, 1, 2], all ≤ 60. Total: 4 substrings.
Example 2 — Impossible Case
$ Input: s = "238", k = 4
Output: -1
💡 Note: Single digits "2", "3" are ≤ 4, but "8" > 4. Since we can't partition "8", no good partition exists.
Example 3 — All Single Digits
$ Input: s = "123", k = 5
Output: 3
💡 Note: Each digit forms its own partition: ["1", "2", "3"]. Values [1, 2, 3] are all ≤ 5.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of digits from '1' to '9'
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Partition String: s="165312", k=60165312Original String165312≤ 60 ✓≤ 60 ✓≤ 60 ✓≤ 60 ✓Optimal Partition: 4 substringsOutput: 4
Understanding the Visualization
1
Input
String of digits and maximum value k
2
Process
Find optimal partition with minimum substrings
3
Output
Minimum number of valid substrings
Key Takeaway
🎯 Key Insight: Greedily take the longest valid substring at each step to minimize total partitions
Asked in
Google 45 Amazon 38 Microsoft 25
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen