Search topics...
All Problems

UTF-8 Validation

Solution Approach
Was this helpful?
MediumbitsExpected: O(n) where n = length of data array time, O(1) space
bit-manipulation

Problem

Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.

A character in UTF-8 can be from 1 to 4 bytes long, subjected to the following rules:

  • For a 1-byte character, the first bit is a 0, followed by its Unicode code.
  • For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.
Number of Bytes   |        UTF-8 Octet Sequence (binary)
------------------+-----------------------------------------
        1         |   0xxxxxxx
        2         |   110xxxxx 10xxxxxx
        3         |   1110xxxx 10xxxxxx 10xxxxxx
        4         |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Only the least significant 8 bits of each integer is used to store the data.

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

Example 1:

Input: data = [197,130,1]
Output: true
Explanation: 11000101 10000010 00000001 — a valid 2-byte character followed by a 1-byte character.

Example 2:

Input: data = [235,140,4]
Output: false
Explanation: 11101011 10001100 00000100 — 3-byte character but second continuation byte doesn't start with 10.
Reference solution unlocks after your first submission
Loading...