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 String Into Minimum Beautiful Substrings INPUT Binary String s = "1011" 1 idx 0 0 idx 1 1 idx 2 1 idx 3 Powers of 5 in Binary: 5^0 = 1 --> "1" 5^1 = 5 --> "101" 5^2 = 25 --> "11001" 5^3 = 125 --> "1111101" Beautiful: No leading 0s + Power of 5 ALGORITHM STEPS 1 Initialize DP dp[i] = min cuts for s[0..i] 2 Try Partitions Check all substring ends 3 Check Beautiful Is substring a power of 5? 4 Update Minimum dp[j] = min(dp[j], dp[i]+1) DP Table Progress: i=0 i=1 i=2 i=3 i=4 0 1 INF 2 2 "1" (5^0) + "011" invalid "101" (5^1) + "1" (5^0) OK FINAL RESULT Optimal Partition Found: "101" = 5 (5^1) + "1" = 1 (5^0) Original: "1011" 1 0 1 1 Output: 2 OK - Valid partition! Both substrings are beautiful (powers of 5) Key Insight: Dynamic Programming finds minimum partitions by trying all valid splits. At each position, we check if the substring forms a power of 5 (precomputed set: 1, 5, 25, 125, 625...). dp[i] stores minimum beautiful substrings needed for s[0..i-1]. Time: O(n^2), Space: O(n) TutorialsPoint - Partition String Into Minimum Beautiful Substrings | DP Approach
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