UTF-8 Validation

Medium · Bit Manipulation · about 20 minutes

Asked at Google, Meta, Apple, Amazon.

Given an array data where each integer is one byte (only the lowest 8 bits are used), return true if it is a valid UTF-8 encoding:

  • a 1-byte character is 0xxxxxxx;
  • an n-byte character (n = 2..4) starts with n ones and a zero (110xxxxx, 1110xxxx, 11110xxx), followed

by n − 1 continuation bytes 10xxxxxx.