UTF-8 Validation

MediumBit Manipulationbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array data where each element is one byte (a value in [0, 255]). Decide whether the bytes form a valid sequence of UTF-8 encoded characters under these structural rules: - A 1-byte character is 0xxxxxxx. - A character of k bytes (k = 2, 3 or 4) starts with k ones followed by a zero (110xxxxx, 1110xxxx, 11110xxx) and is followed by exactly k - 1 continuation bytes of the form 10xxxxxx. Every byte must belong to exactly one character. Return true if the whole array is valid and false otherwise. Only these bit patterns matter: do not reject overlong encodings or specific code point ranges.

Examples

Input: data = [197,130,1]
Output: true
11000101 10000010 is a 2-byte character, then 00000001 is a 1-byte character.
Input: data = [235,140,4]
Output: false
11101011 starts a 3-byte character, 10001100 is a valid continuation, but 00000100 is not.

Constraints

  • 1 <= data.length <= 2 * 10^4
  • 0 <= data[i] <= 255

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems