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 Into Substrings With Values at Most K INPUT String s = "165312" 1 6 5 3 1 2 0 1 2 3 4 5 k = 60 (max substring value) Each substring value must be <= 60 Value Examples: "16" --> 16 (OK, <= 60) "165" --> 165 (BAD, > 60) "53" --> 53 (OK, <= 60) ALGORITHM STEPS 1 Start at index 0 Try "1" --> 1 <= 60 OK Try "16" --> 16 <= 60 OK Try "165" --> 165 > 60 STOP Take "16" 2 Continue at index 2 Try "5" --> 5 <= 60 OK Try "53" --> 53 <= 60 OK Try "531" --> 531 > 60 STOP Take "53" 3 Continue at index 4 Try "1" --> 1 <= 60 OK Try "12" --> 12 <= 60 OK End of string reached Take "12" 4 Wait - recalculate! "16" | "5" | "31" | "2" gives 4 partitions Count = 4 FINAL RESULT Optimal Partition: 16 <= 60 | 5 <= 60 | 31 <= 60 | 2 <= 60 Number of substrings: 4 Verification: "16" = 16 <= 60 OK "5" = 5 <= 60 OK "31" = 31 <= 60 OK "2" = 2 <= 60 OK Key Insight: Greedy approach: At each position, extend the current substring as far as possible while keeping its numeric value <= k. This minimizes the total number of partitions. If any single digit > k, return -1 since no valid partition exists. Time Complexity: O(n), Space Complexity: O(1). TutorialsPoint - Partition String Into Substrings With Values at Most K | Greedy Approach
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