Problem 717

Abstract / Summary

We must determine if a sequence of bits can be grouped into only 1-bit and 2-bit characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0717.py

lass Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        bits.pop()

        size = 0
        while size < len(bits):
            size += 1 + bits[size]

        return size == len(bits)
9 lines | 220 bytes | submitted August 15, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation defines a class with a method that determines whether the final character in a binary array is a one-bit character. The algorithm works by discarding the known terminating zero, then scanning the remaining bits while interpreting each 0 as a single-bit symbol and each 1 as the start of a two-bit symbol. The method finally checks whether the scan ends exactly at the end of the shortened array, which indicates that the removed zero was indeed a one-bit character.

Key Steps

Removing the trailing zero

bits.pop()

The last element of the input list is removed before processing. In the problem context the final bit is guaranteed to be 0, representing the character whose type we need to verify. By popping it, the algorithm can focus on parsing the preceding bits without special-casing the final element during the scan.

Scanning the bit sequence

size = 0
while size < len(bits):
    size += 1 + bits[size]

A pointer size starts at the beginning of the list. The loop continues while the pointer is within the bounds of the shortened array. For each iteration the pointer advances by 1 + bits[size]. When bits[size] is 0, the increment is 1, reflecting a one-bit character. When bits[size] is 1, the increment becomes 2, reflecting the two-bit character that starts with 1. This arithmetic eliminates the need for conditional branches or auxiliary state variables, keeping the scan tight and efficient.

Determining the result

return size == len(bits)

After the loop terminates, the method compares the final pointer position with the length of the processed list. If they are equal, the scan consumed the entire array exactly, meaning the removed trailing zero was not part of a two-bit character and therefore is a one-bit character. If the pointer overshoots, the removed zero would have been the second half of a two-bit character, and the method would return False.

Edge Cases Handled

When the input consists of a single 0, the pop operation empties the list. The while loop condition size < len(bits) fails immediately because len(bits) is 0, leaving size at 0. The final comparison size == len(bits) evaluates to True, correctly identifying the lone 0 as a one-bit character.

If the array contains a pattern like [1, 0, 0], after popping the last 0 the list becomes [1, 0]. The loop starts with size = 0, reads bits[0] as 1, and increments size by 2, moving directly to the end of the list. The final equality holds, indicating that the original trailing 0 was a one-bit character.

When the sequence ends with a two-bit character such as [1, 1, 0], popping the final 0 yields [1, 1]. The loop processes bits[0] (1) and jumps size to 2, which equals the length of the list, so the method still returns True. However, in the original problem constraints the final bit is always 0, and the algorithm’s logic correctly distinguishes whether that 0 belongs to a preceding two-bit symbol or stands alone.

Performance Optimizations

The code operates directly on the input list without allocating additional containers, which minimizes memory overhead. The use of pop() modifies the list in place, avoiding the need for a separate slice or copy of the data. The loop’s increment expression 1 + bits[size] combines the decision of one- versus two-bit advancement into a single arithmetic operation, eliminating branching and reducing instruction count. The overall traversal touches each element at most once, providing a linear-time execution path with a minimal constant factor.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train track made of blocks. Some blocks are small and take up only one space, but others are double-sized and need two spaces to fit. The computer looks at all these blocks lined up in a row.

First, the computer takes away the very last block to see what it is. Then, it starts walking from the beginning of the line to check the rest. Every time it finds a small block, it jumps forward one space. If it finds a double-sized block, it jumps forward two spaces to skip over it. The computer keeps jumping along until it reaches the end of the line. If it lands exactly at the spot where the last block used to be, it knows that the last block was just a tiny one-space piece.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4.5 | μ = 4.81 | σ = 2.25

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C#
lkwq007 Python
qiyuangong Java
shreymehul C#
suxrobGM C#
trung-hn Python
withaarzoo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C#
lkwq007 Python
qiyuangong Java
shreymehul C#
suxrobGM C#
trung-hn Python
withaarzoo C++
zfang399 C++
35 links | 20 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality