Data Structures & AlgorithmsHardAmazon · Microsoft OA
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 bytes of the form 10xxxxxx).
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 bytes of the form 10xxxxxx).
def valid(data):
need = 0
for b in data:
if need:
if b >> 6 != 0b10: return False
need -= 1
elif b >> 7 == 0: continue
elif b >> 5 == 0b110: need = 1
elif b >> 4 == 0b1110: need = 2
elif b >> 3 == 0b11110: need = 3
else: return False
return need == 0
print(valid([197, 130, 1]), valid([235, 140, 4]), valid([240, 162, 138]))What is printed?- A. True True False
- B. False False True
- C. True False False
- D. True False True
Correct answer: C. True False False
197 = 110 00101 starts a 2-byte char and 130 = 10 000010 continues it; 1 is ASCII → True. 235 = 1110 1011 needs two continuation bytes, but 4 = 00000100 is not 10xxxxxx → False. 240 = 11110 000 needs THREE continuation bytes but only two follow → False.
More Coding Interview Problems questions
- 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…
- A service must detect whether a dependency graph with 10⁵ modules and 10⁶ edges has a cycle. Which approach is both correct and efficient?
- Shortest paths in a large grid where each move costs either 0 or 1. Which algorithm is the most efficient correct choice?