Fewest append-to-end moves to reverse a binary image
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests strings, greedy and two pointers.
An image is stored as a binary string s: '1' is a white pixel and '0' is a black pixel. To make a backup, you want to turn s into its reverse, s read from right to left.
You may use one operation any number of times: pick any character of the current string, remove it, and append it at the end.
Implement find_minimum_operations(s: str) -> int. It returns the fewest operations that turn s into its reverse.
Constraints
0 <= len(s) <= 2 * 10^5-
scontains only'0'and'1'
Example 1
s = "0010" reverse = "0100"
move index 1 ('0'): "010" + "0" = "0100"
output: 1
Example 2
s = "0001" reverse = "1000"
output: 3
Only the final '1' can stay where it is relative to the rest. All three '0's have to be moved behind it.
Example 3
s = "0110" output: 0 (s is already a palindrome)
Clarifying questions
- Is the empty string 0 moves?
- May a character be moved more than once? (It never needs to be: confirm.)
- Should I also return which characters to move?
What a strong answer covers
- Sees that the characters never moved keep their relative order and end up at the front, so they must spell a prefix of the reverse; every other character is moved once, in the right order, to the end.
- So the answer is
nminus the longest prefix ofreverse(s)that is a subsequence ofs, found with a greedy two-pointer scan in O(n). - Checks it on the examples:
"0010"keeps"010"(1 move),"0001"keeps only"1"(3 moves), a palindrome keeps everything. - Tests the empty string, all one character, alternating strings and a brute-force check (BFS over strings) for small lengths.
Follow-ups
- Turn
sinto any given target string with the same operation. - Allow moving a character to the front as well as the end.
- Return the sequence of indices to move.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
