#2767
Partition String Into Minimum Beautiful Substrings
MediumHash TableStringDynamic ProgrammingBacktrackingDynamic ProgrammingBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal approach uses dynamic programming to store the minimum number of beautiful substrings that can be formed up to each index. This avoids redundant calculations and improves efficiency significantly.
⚙️
Algorithm
3 steps- 1Step 1: Precompute all powers of 5 that can be represented in binary up to the maximum length of the string.
- 2Step 2: Initialize a DP array where dp[i] represents the minimum number of beautiful substrings for the substring s[0:i].
- 3Step 3: For each index, check all possible substrings ending at that index and update the DP array accordingly.
solution.py18 lines
1# Full working Python code
2def minBeautifulSubstrings(s):
3 powers_of_5 = set()
4 for i in range(15):
5 powers_of_5.add(bin(5 ** i)[2:])
6 n = len(s)
7 dp = [float('inf')] * (n + 1)
8 dp[0] = 0
9 for i in range(1, n + 1):
10 for j in range(i):
11 substring = s[j:i]
12 if substring[0] != '0' and substring in powers_of_5:
13 dp[i] = min(dp[i], dp[j] + 1)
14 return dp[n] if dp[n] != float('inf') else -1
15
16# Example usage
17print(minBeautifulSubstrings('1011')) # Output: 2
18ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops for substring checks, but the space complexity is O(n) for the DP array.
- 1Understanding binary representations and their properties is crucial.
- 2Dynamic programming can significantly reduce the number of redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.