UTF-8 Validation - 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 0, followed by its Unicode code.
  • For an n-bytes character, the first n bits are all 1s, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.

UTF-8 Encoding Rules:

Number of BytesUTF-8 Octet Sequence (binary)
10xxxxxxx
2110xxxxx 10xxxxxx
31110xxxx 10xxxxxx 10xxxxxx
411110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data.

Input & Output

Example 1 — Valid UTF-8 Sequence
$ Input: data = [197,130,1]
Output: true
💡 Note: 197 (11000101) is a 2-byte start, 130 (10000010) is valid continuation, 1 (00000001) is valid 1-byte character
Example 2 — Invalid Continuation
$ Input: data = [235,140,4]
Output: false
💡 Note: 235 (11101011) starts a 3-byte character but only has one continuation byte 140, missing second continuation
Example 3 — Single Bytes Only
$ Input: data = [1,2,3,4]
Output: true
💡 Note: All bytes have pattern 0xxxxxxx, which are valid 1-byte UTF-8 characters

Constraints

  • 1 ≤ data.length ≤ 2 × 104
  • 0 ≤ data[i] ≤ 255

Visualization

Tap to expand
UTF-8 Validation OverviewInput: [197, 130, 1] → Output: trueUTF-8 Byte Patterns1-byte: 0xxxxxxx2-byte: 110xxxxx 10xxxxxx3-byte: 1110xxxx 10xxxxxx 10xxxxxxInput Analysis197: 11000101 (2-byte start)130: 10000010 (continuation)1: 00000001 (1-byte char)State Tracking197 → count = 1130 → count = 0 ✓1 → count = 0 ✓Validation Result✓ Valid UTF-8: Complete 2-byte character + 1-byte characterOutput: trueAll multi-byte sequences properly closed (count = 0 at end)
Understanding the Visualization
1
Input Data
Array of integers representing bytes
2
UTF-8 Patterns
Identify start bytes and continuation bytes
3
Validation
Check if sequence forms valid UTF-8 characters
Key Takeaway
🎯 Key Insight: UTF-8 validation requires state tracking to ensure continuation bytes follow start bytes in correct sequences
Asked in
Google 25 Microsoft 18 Amazon 15 Facebook 12
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen