Fewest flips to split a binary string into even uniform blocks
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Jul 2025. It tests strings, greedy and dynamic programming.
You are given a string s of 0s and 1s whose length is even. You may flip any characters. After flipping, s must split into consecutive blocks where every block has even length and holds only 0s or only 1s. First make the number of flips as small as possible. Among the ways that use that fewest number of flips, make the number of blocks as small as possible. Return both numbers.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_flips_and_blocks(s: str) -> list[int]— returns[min_flips, min_blocks];[0, 0]for an empty string.
Example
"1001" -> [2, 1] # flip to "0000" (or "1111")
"110011" -> [0, 3] # already valid: "11" "00" "11"
"1110011000" -> [3, 2] # e.g. "1111111100": "11111111" "00"
"0110" -> [2, 1]
Constraints
-
0 <= len(s) <= 10^5, andlen(s)is even. -
sholds only0and1.
Clarifying questions
- Is the length always even? What should an odd length return?
- Which goal comes first: fewer flips or fewer blocks?
- Is a block of length 2 allowed?
What a strong answer covers
- The reduction: a string splits into even uniform blocks exactly when every aligned pair
s[2i], s[2i+1]is equal. So the minimum flips is the number of mismatched pairs, one flip each. - Matched pairs keep their value; a mismatched pair can become
00or11at the same cost, so it takes the value of a neighbouring pair. - Blocks = 1 + the number of value changes between consecutive matched pairs, skipping the free ones (all pairs free: 1 block). O(n) time, O(1) space.
- Why minimizing blocks first would be trivial (one block, flip the minority value), so the order of the goals matters.
- Tests: all one value, alternating
0101…, empty.
Follow-ups
- Minimize blocks first and flips second. What is the answer now?
- Every block must have length at least
Las well as even. How does the solution change? - Return one valid final string, not only the two counts.
Where it's asked
- Amazon · Online assessment · Last asked Jul 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
