Ctrl K

Multibyte Stream Check

Medium
A stream of bytes octets arrived over the network: each element is a number from 0 to 255, that is, exactly one byte. Check whether the stream is well-formed UTF-8, meaning it splits completely into characters according to the rules below. A character takes 1 to 4 bytes: | Bytes per character | Binary layout | |---|---| | 1 | 0xxxxxxx | | 2 | 110xxxxx 10xxxxxx | | 3 | 1110xxxx 10xxxxxx 10xxxxxx | | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | Here x is any bit. In other words, the first byte of a k-byte character (k ≥ 2) starts with k ones followed by a zero, and each of the remaining k − 1 bytes starts with 10. A one-byte character starts with 0. Nothing else is allowed; you do not need to check what the characters mean. Return True if the stream is well formed and False otherwise.
Example 1
octets=[226, 130, 172, 65] → True

226 = 11100010 starts a three-byte character; 130 = 10000010 and 172 = 10101100 are valid continuations. 65 = 01000001 is a one-byte character. The stream is well formed.

Example 2
octets=[195, 65] → False

195 = 11000011 announces a two-byte character, but the next byte 65 = 01000001 does not start with 10.

Example 3
octets=[128] → False

128 = 10000000 is a continuation byte, and no character may start with one.

Constraints
  • 1 ≤ octets.length ≤ 2·10⁴
  • 0 ≤ octets[i] ≤ 255
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Topping Combo MediumAll Distinct Card Hands MediumThe Odd One Among Triples MediumTwo Values Without a Pair MediumSpot the Extra Copy Medium
loading Python…
Input
octets=[226, 130, 172, 65]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 137 tests on the server, hidden ones included.