← Questions

Fewest append-to-end moves to reverse a binary image

0
AmazonCoding

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
  • s contains 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 n minus the longest prefix of reverse(s) that is a subsequence of s, 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 s into 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

strings · greedy · two pointers · subsequence

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding