#2522
Partition String Into Substrings With Values at Most K
MediumStringDynamic ProgrammingGreedyGreedyTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach to minimize the number of substrings. It builds substrings from the left and checks their values against k, ensuring that we only create valid partitions.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a counter for substrings and a variable to store the current substring value.
- 2Step 2: Iterate through each character in the string.
- 3Step 3: For each character, update the current substring value by multiplying the existing value by 10 and adding the integer value of the current character.
- 4Step 4: If the current substring value exceeds k, increment the substring counter, reset the current value to the current character's value.
- 5Step 5: If any character itself is greater than k, return -1.
- 6Step 6: After the loop, account for the last substring and return the counter.
solution.py18 lines
1# Full working Python code
2
3def minPartitions(s, k):
4 count = 0
5 current_value = 0
6 for char in s:
7 digit = int(char)
8 if digit > k:
9 return -1
10 current_value = current_value * 10 + digit
11 if current_value > k:
12 count += 1
13 current_value = digit
14 return count + (1 if current_value > 0 else 0)
15
16# Example usage
17print(minPartitions('165462', 60)) # Output: 4
18ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string, and the space complexity is O(1) since we are using a fixed amount of extra space.
- 1If any single digit is greater than k, a valid partition is impossible.
- 2The greedy approach ensures we minimize the number of substrings by always trying to extend the current substring until it exceeds k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.