Skip to main content

Minimum Cost to Partition a Binary String - Solution & Explanation

HardStringDivide and ConquerPrefix Sum11 min readAsked at: Amazon
Practice this problem

Problem Statement

You are given a binary string s and two integers encCost and flatCost.

For each index i, s[i] = '1' indicates that the ith element is sensitive, and s[i] = '0' indicates that it is not.

The string must be partitioned into segments. Initially, the entire string forms a single segment.

For a segment of length L containing X sensitive elements:

  • If X = 0, the cost is flatCost.
  • If X > 0, the cost is L * X * encCost.

If a segment has even length, you may split it into two contiguous segments of equal length and the cost of this split is the sum of costs of the resulting segments.

Return an integer denoting the minimum possible total cost over all valid partitions.

 

Example 1:

Input: s = "1010", encCost = 2, flatCost = 1

Output: 6

Explanation:

  • The entire string s = "1010" has length 4 and contains 2 sensitive elements, giving a cost of 4 * 2 * 2 = 16.
  • Since the length is even, it can be split into "10" and "10". Each segment has length 2 and contains 1 sensitive element, so each costs 2 * 1 * 2 = 4, giving a total of 8.
  • Splitting both segments into four single-character segments yields the segments "1", "0", "1", and "0". A segment containing "1" has length 1 and exactly one sensitive element, giving a cost of 1 * 1 * 2 = 2, while a segment containing "0" has no sensitive elements and therefore costs flatCost = 1.
  • ​​​​​​​The total cost is thus 2 + 1 + 2 + 1 = 6, which is the minimum possible total cost.

Example 2:

Input: s = "1010", encCost = 3, flatCost = 10

Output: 12

Explanation:

  • The entire string s = "1010" has length 4 and contains 2 sensitive elements, giving a cost of 4 * 2 * 3 = 24.
  • Since the length is even, it can be split into two segments "10" and "10".
  • Each segment has length 2 and contains one sensitive element, so each costs 2 * 1 * 3 = 6, giving a total of 12, which is the minimum possible total cost.

Example 3:

Input: s = "00", encCost = 1, flatCost = 2

Output: 2

Explanation:

The string s = "00" has length 2 and contains no sensitive elements, so storing it as a single segment costs flatCost = 2, which is the minimum possible total cost.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists only of '0' and '1'.
  • 1 <= encCost, flatCost <= 105

Approach Overview

Problem Overview: You are given a binary string and must split it into one or more contiguous partitions such that the total cost of all partitions is minimized. The cost of a segment depends on the imbalance of characters inside it, so the goal is to choose split points that minimize the cumulative cost across the entire string.

Approach 1: Pure Recursion (Brute Force) (Time: O(n^3), Space: O(n))

The most direct way is to try every possible partition of the string. For a starting index i, iterate over every possible end index j, treat s[i..j] as one segment, compute its cost, and recursively solve the remaining substring starting from j + 1. The recursion explores the full decision tree of possible partitions. Because each segment cost may require scanning the substring, the total time grows to O(n^3). This approach clearly shows the structure of the problem but becomes impractical for large strings.

Approach 2: Recursion with Prefix Sum Optimization (Time: O(n^2), Space: O(n))

The expensive part of the brute force solution is repeatedly recomputing statistics for each substring. A prefix sum array solves this by storing the cumulative count of '1's up to each position. With prefix sums, the number of ones in any substring can be computed in O(1). Since the substring length is known, the number of zeros is derived immediately. This allows you to compute the cost of any segment instantly while still exploring partition choices recursively. The recursion still tries all split points, but substring evaluation becomes constant time, reducing complexity to about O(n^2).

Approach 3: Divide and Conquer with Memoization (Time: O(n^2), Space: O(n))

The recursive formulation naturally overlaps: the minimum cost from index i is recomputed many times. Memoizing results for each starting index removes this redundancy. Store the minimum cost for each suffix of the string and reuse it whenever the recursion revisits that state. Combined with prefix sums, each state processes possible split points in a single loop. This pattern blends divide and conquer with dynamic programming over a string. The result is a practical O(n^2) algorithm that works efficiently within typical constraints.

Recommended for interviews: Start by explaining the brute force recursive partition idea because it demonstrates clear reasoning about how splits affect total cost. Then introduce prefix sums to eliminate repeated substring scans and add memoization to remove overlapping work. Interviewers typically expect the optimized recursive solution with prefix sums, since it shows both algorithmic insight and practical performance improvements.

Solution

We define a function dfs(l, r) that represents the minimum cost for the interval [l, r) of string s. We can use the prefix sum array pre to calculate the number of sensitive elements x in the interval [l, r), thereby computing the cost without splitting.

The calculation process of function dfs(l, r) is as follows:

  1. Calculate the number of sensitive elements x in the interval [l, r).
  2. Calculate the cost without splitting: if x > 0, the cost is (r - l) cdot x cdot encCost; if x = 0, the cost is flatCost.
  3. If the interval length is even, we can try to split it into two consecutive segments of equal length, and calculate the cost after splitting as dfs(l, m) + dfs(m, r), where m = \frac{l + r}{2}. Finally, return the smaller of the two values.

The answer is dfs(0, n), where n is the length of string s.

The time complexity is O(n) and the space complexity is O(n), where n is the length of string s.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor β†’

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Pure Recursive PartitioningO(n^3)O(n)Understanding the basic decision tree of partition problems
Recursion + Prefix SumO(n^2)O(n)When substring cost depends on counts of characters
Memoized Divide and ConquerO(n^2)O(n)Best general solution; avoids recomputation of subproblems

Video Solution

weekly contest 492 | leetcode 3861|leetcode 3862|leetcode 3863|leetcode 3864 | DSA | Easy solutions β€’ Code With Vick β€’ 507 views views

Watch 6 more video solutions β†’

Frequently Asked Questions

Is Minimum Cost to Partition a Binary String easy or hard?
Minimum Cost to Partition a Binary String is considered a hard problem because it combines recursion, prefix sums, and optimization of overlapping subproblems. Efficient solutions require recognizing the partition DP pattern and eliminating repeated substring calculations.
Minimum Cost to Partition a Binary String Python/Java solution
The solution is typically implemented using recursion with memoization. Python uses dictionaries or lists for caching results, while Java uses arrays or HashMap. Both versions rely on a prefix sum array to compute substring costs in constant time.
How to solve Minimum Cost to Partition a Binary String in O(n^2)?
Precompute a prefix sum array storing the cumulative number of '1's in the string. During recursion, use the prefix sums to compute the cost of any substring in constant time. Memoize the minimum cost starting from each index so each state is solved once, producing an overall O(n^2) algorithm.
What is the best approach for Minimum Cost to Partition a Binary String?
The most practical approach combines recursion with prefix sums and memoization. Prefix sums allow constant-time calculation of the number of ones or zeros in any substring, while memoization stores the minimum cost for each starting index. This reduces repeated work and leads to roughly O(n^2) time complexity with O(n) space.
Is Minimum Cost to Partition a Binary String asked at Google/Amazon/Meta?
Partitioning problems on binary strings frequently appear in interviews at companies like Google, Amazon, and Meta. Variants often test divide and conquer reasoning, dynamic programming, and prefix sum optimization for fast substring calculations.
What data structure is used in Minimum Cost to Partition a Binary String?
The main structure is a prefix sum array used to count characters efficiently in any substring. The recursive solution also uses a memoization cache or array to store previously computed results for starting indices.
What is the time complexity of Minimum Cost to Partition a Binary String?
A naive recursive partition approach can take O(n^3) time because every substring cost may require scanning characters. Using prefix sums to compute substring statistics in O(1) reduces the complexity to O(n^2). With memoization, each starting index is processed once while trying all split points.

Ready to solve this problem?

Practice Minimum Cost to Partition a Binary String with our built-in code editor and test cases.

Practice on FleetCode