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?
  1. A. True True False
  2. B. False False True
  3. C. True False False
  4. 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

Exams that ask this topic