Skip to content
Problem 717 · LeetCode 717(opens in a new tab)

1-bit and 2-bit Characters

EasyArrays

A simple code uses two kinds of characters. A one-bit character is written as a single 0. A two-bit character is written as 1 followed by any bit, so 10 or 11.

You are given bits, a list of 0s and 1s that always ends in 0 and can be decoded from the start into these characters. Return true if the last character in the decoding is a one-bit character, and false if the final 0 is the second half of a two-bit character.

Example 1

Input:  bits = [1, 1, 0, 0]
Output: true
Why:    it reads as 11, 0, 0, so the last character is a lone 0
2 more examples and the constraints

Example 2

Input:  bits = [0, 1, 0]
Output: false
Why:    it reads as 0, 10, so the final 0 belongs to 10

Example 3

Input:  bits = [0]
Output: true
Why:    a single 0 is a one-bit character

Constraints

  • 1 ≤ length of bits ≤ 1,000
  • Every bit is 0 or 1
  • The last bit is always 0

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Decode from the startO(n)
  2. Count the 1s before the endO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 bitsVerdict
Decode from the startO(n)
Simple and always passes
Count the 1s before the endO(n)
Best; reads only the tail

n = number of bits. The work for the second approach is typical, not worst case.

Edge cases to test

  • A single bit. [0] is one one-bit character: true.
  • A 0 right before the end. [1, 1, 0, 0] gives true: the run of 1s before the last bit is empty.
  • All 1s then the 0. [1, 1, 1, 0] gives false: three 1s, an odd run.
  • Even run of 1s. [1, 1, 1, 1, 0] gives true: 11, 11, then the lone 0.

Common mistakes

  • Looking only at the second-to-last bit: [1, 1, 0] has a 1 there yet the answer is true.
  • Letting the loop run to the last index, so the final 0 is consumed and i always ends past it.
  • Counting every 1 in the list instead of only the run touching the final 0.

How to talk through it

  1. 1Clarify. Is the last bit always 0? Is the input always a valid decoding?
  2. 2Give the direct walk. Decode from the left: a 1 jumps two bits, a 0 jumps one. Check where you land.
  3. 3Notice the cut. A 0 always closes a character, so only the run of 1s before the end matters.
  4. 4Code the parity check. Count 1s leftwards from the second-to-last bit; even means true.
  5. 5Test out loud. Run [0], [1, 1, 0] and [1, 1, 1, 0] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?