Partition String Into Minimum Beautiful Substrings - Problem

Given a binary string s, partition the string into one or more substrings such that each substring is beautiful.

A string is beautiful if:

  • It doesn't contain leading zeros.
  • It's the binary representation of a number that is a power of 5.

Return the minimum number of substrings in such partition. If it is impossible to partition the string s into beautiful substrings, return -1.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Valid Partition
$ Input: s = "1011"
Output: 2
💡 Note: The string "1011" can be partitioned as "101" + "1". Both "101" (binary for 5¹=5) and "1" (binary for 5⁰=1) are powers of 5, so minimum partitions = 2.
Example 2 — No Valid Partition
$ Input: s = "111"
Output: -1
💡 Note: No way to partition "111" into beautiful substrings. "1" is valid but "11" is not a power of 5 (binary 11 = decimal 3). "111" (decimal 7) is also not a power of 5.
Example 3 — Single Character
$ Input: s = "1"
Output: 1
💡 Note: The string "1" itself is beautiful (binary representation of 5⁰=1), so only 1 partition needed.

Constraints

  • 1 ≤ s.length ≤ 15
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Partition "1011" Into Minimum Beautiful Substrings1011Input String"101" (5¹ = 5)"1" (5⁰ = 1)Powers of 5: 1="1", 5="101", 25="11001", 125="1111101", ...Valid Partition: "101" + "1" = 2 substringsOutput: 2
Understanding the Visualization
1
Input
Binary string that needs to be partitioned
2
Identify
Find valid power-of-5 substrings without leading zeros
3
Partition
Return minimum number of beautiful substrings
Key Takeaway
🎯 Key Insight: Precompute power-of-5 binary patterns and use DP to find minimum partitions
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.0K Views
Medium Frequency
~25 min Avg. Time
890 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