All problems
1133MediumArrayBit Manipulation

Checking a Packed Octet Stream

Tracked in this browser only
Write code

Trains the technique from

LeetCode 393UTF-8 Validation

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A stream stream holds whole numbers, and only the lowest eight bits of each one count: those bits make up one octet of data.

Characters are packed into one to four octets by this scheme:

  • A one-octet character has a top bit of 0, so the octet reads 0xxxxxxx.
  • A character of n octets, with n between 2 and 4, opens with an octet whose top n bits are all 1 followed by a 0, and every octet after that reads 10xxxxxx.

So two octets read 110xxxxx 10xxxxxx, three read 1110xxxx 10xxxxxx 10xxxxxx, and four read 11110xxx followed by three octets of 10xxxxxx.

Return true when the whole stream is packed correctly under that scheme.

Examples

Example 1

Input
stream = [224, 160, 128]
Output
true

The first octet opens with 1110, promising three octets, and the two after it both open with 10.

Example 2

Input
stream = [197]
Output
false

The octet opens with 110 and so promises a second octet, but the stream ends there.

Example 3

Input
stream = [128]
Output
false

The octet opens with 10, which can only follow a leading octet, so it cannot start a character at all.

Constraints

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

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def valid_utf8(stream: list[int]) -> bool:
Java
public boolean validUtf8(int[] stream)
September 7
Apply