You get an array data where each integer is one byte (0 to 255). Return true if the bytes form valid UTF-8 text, and false otherwise.
In UTF-8 a character takes 1 to 4 bytes. A one-byte character looks like 0xxxxxxx. A longer character starts with a leading byte made of as many 1s as the character has bytes, then a 0: 110xxxxx for 2 bytes, 1110xxxx for 3, 11110xxx for 4. Each of the bytes after the lead is a continuation byte of the form 10xxxxxx. Here x can be 0 or 1.
Example 1
Input: data = [226, 130, 172, 65] Output: true Why: 1110 lead plus two 10 bytes, then a 0xxxxxxx byte
2 more examples and the constraints
Example 2
Input: data = [240, 159, 152] Output: false Why: a 4-byte lead, but only two continuation bytes follow
Example 3
Input: data = [145] Output: false Why: 10010001 is a continuation byte with no lead before it
Constraints
- 1 ≤ length of data ≤ 20,000
- 0 ≤ data[i] ≤ 255
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Binary stringsO(n)
- Shifts and a counterO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 bytes | Verdict |
|---|---|---|---|
| Binary strings | O(n) | Readable; allocates per byte | |
| Shifts and a counter | O(n) | Best; no allocation |
n = length of data.
Edge cases to test
- Cut short. [240, 159, 152] ends while one byte is still owed: false.
- Stray continuation. [145] is
10xxxxxxwith nothing owed: false. - Too many 1s. 255 and 248 have five or more leading 1s; no character is that long.
- Wrong follower. [194, 65]: the lead owes a byte, but 65 starts with 0, not 10.
Common mistakes
- Forgetting to check
need == 0at the end, so a cut-off character passes. - Treating a
10xxxxxxbyte with nothing owed as a one-byte character. - Testing
b >> 5 == 0b110without first ruling out a pending continuation.
How to talk through it
- 1Clarify. Only the low 8 bits matter? Up to 4 bytes per character, and no overlong checks needed?
- 2State the rules. Leading 1s of a lead byte say the length; followers are
10xxxxxx. - 3Track what is owed. One counter: set by a lead, lowered by each follower.
- 4Use shifts.
b >> 6,b >> 5,b >> 4,b >> 3read the top bits without strings. - 5Test out loud. Try a cut-off character, a stray continuation and the byte 255.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?