Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'.

Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'.
def min_del(s):
    b_seen = dels = 0
    for c in s:
        if c == 'b': b_seen += 1
        else: dels = min(dels + 1, b_seen)
    return dels
print(min_del("aababbab"), min_del("bbbaaaab"))
What is printed?
  1. A. 1 3
  2. B. 2 3
  3. C. 3 4
  4. D. 2 4

Correct answer: B. 2 3

For each 'a' either delete it (dels + 1) or delete every 'b' before it (b_seen). 'aababbab' → 2 (e.g. delete the b at index 2 and the a at index 6). 'bbbaaaab' → min(delete 3 b's, delete 4 a's) = 3.

More Coding Interview Problems questions

Exams that ask this topic