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?- A. 1 3
- B. 2 3
- C. 3 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
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…
- Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, ……
- Problem: Compute a^b mod 1337 where the exponent b is given as a digit array (too large for an integer), using a^(10x + d) = (a^x)^10 ·…
- A stack supports push, pop and multipop(k) (pop up to k elements). Starting from empty, what is the worst-case total cost of any sequence…
- A binary counter starts at 0 and is incremented n times; each increment flips trailing 1s to 0 and one 0 to 1. What is the total number of…