MediumNo. 0393

UTF-8 Validation — LeetCode 393 Python Solution

Topics
Bit Manipulation, Array
Reading time
3 min

The problem

Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).

Example

Example
Number of Bytes   |        UTF-8 Octet Sequence
                       |              (binary)
   --------------------+-----------------------------------------
            1          |   0xxxxxxx
            2          |   110xxxxx 10xxxxxx
            3          |   1110xxxx 10xxxxxx 10xxxxxx
            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Python solution

PythonSolution
class Solution:
    def validUtf8(self, data: List[int]) -> bool:
        cnt = 0
        for v in data:
            if cnt > 0:
                if v >> 6 != 0b10:
                    return False
                cnt -= 1
            elif v >> 7 == 0:
                cnt = 0
            elif v >> 5 == 0b110:
                cnt = 1
            elif v >> 4 == 0b1110:
                cnt = 2
            elif v >> 3 == 0b11110:
                cnt = 3
            else:
                return False
        return cnt == 0

Complexity

Time
O(n)where n is the length of the array `data`
Space · auxiliary
O(1)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 393. UTF-8 Validation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0136Single NumberEasy
0137Single Number IIMedium
0260Single Number IIIMedium
0287Find the Duplicate NumberMedium
0318Maximum Product of Word LengthsMedium
0477Total Hamming DistanceMedium

Frequently asked questions

How hard is LeetCode 393. UTF-8 Validation?

LeetCode 393. UTF-8 Validation is rated Medium on LeetCode.

What is the time complexity of LeetCode 393. UTF-8 Validation?

The Python solution on this page runs in O(n), where n is the length of the array `data`.

What is the space complexity of LeetCode 393. UTF-8 Validation?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 393. UTF-8 Validation cover?

LeetCode 393. UTF-8 Validation is tagged Bit Manipulation and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.