Partition String Into Minimum Beautiful Substrings - Problem
Given a binary string s, your task is to partition it into the minimum number of beautiful substrings.
A substring is considered beautiful if it satisfies two conditions:
- No leading zeros: The substring cannot start with '0' (unless it's just "0" itself, but "0" is not a power of 5)
- Power of 5: When converted from binary to decimal, the number must be a power of 5 (1, 5, 25, 125, ...)
Goal: Find the minimum number of partitions needed, or return -1 if impossible.
Example: The binary string "101" represents decimal 5, which is 51, so it's beautiful. The string "11001" can be split into "1" (decimal 1 = 50) and "1001" (decimal 9, not a power of 5), so we need to try different partitions.
Input & Output
example_1.py โ Simple Valid Case
$
Input:
s = "1011"
โบ
Output:
2
๐ก Note:
We can partition "1011" into "101" (decimal 5 = 5ยน) and "1" (decimal 1 = 5โฐ). Both are powers of 5, so minimum partitions = 2.
example_2.py โ Single Beautiful String
$
Input:
s = "111"
โบ
Output:
3
๐ก Note:
"111" (decimal 7) is not a power of 5. We must partition it as "1" + "1" + "1", where each "1" represents 5โฐ = 1. Minimum partitions = 3.
example_3.py โ Impossible Case
$
Input:
s = "0"
โบ
Output:
-1
๐ก Note:
"0" has a leading zero and 0 is not a power of 5. It cannot form any beautiful substring, so return -1.
Constraints
- 1 โค s.length โค 15
- s[i] is either '0' or '1'
- Powers of 5 in binary: 1โ=1โโ, 101โ=5โโ, 11001โ=25โโ, 1111101โ=125โโ
Visualization
Tap to expand
Understanding the Visualization
1
Identify Powers of 5
Pre-compute: 1โ=1, 101โ=5, 11001โ=25, 1111101โ=125...
2
Try All Cuts
At each position, attempt to cut and create valid beautiful substrings
3
Validate Substrings
Check if each piece has no leading zeros and represents a power of 5
4
Minimize Partitions
Use DP to find the minimum number of cuts needed
5
Handle Impossible Cases
Return -1 if no valid partitioning exists
Key Takeaway
๐ฏ Key Insight: Pre-compute all powers of 5 in binary and use memoized DP to find minimum cuts. The binary representations of powers of 5 follow a pattern that we can leverage for efficient checking.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code