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
Partitioning "11001" into Beautiful Substrings1 1 0 0 101234Cut 1"1"1โ‚โ‚€ = 5โฐ"1001"9โ‚โ‚€ โ‰  power of 5โŒ Invalid partition: "1001" is not a power of 5Cut 2"11001"25โ‚โ‚€ = 5ยฒโœ… Optimal: Single partition, answer = 1
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.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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