Problem
We have two special characters:
- The first character can be represented by one bit
0. - The second character can be represented by two bits (
10or11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= bits.length <= 1000bits[i]is either0or1.
Solution
Method 1 – Greedy Linear Scan
Intuition
The key idea is to simulate reading the bits from left to right, always taking the largest valid character (either a 2-bit character if we see a 1, or a 1-bit character if we see a 0). If we land exactly on the last bit and it’s a single 0, then the last character is a one-bit character.
Approach
- Initialize a pointer
iat the start of the array. - While
iis less than the last index:
- If
bits[i]is1, incrementiby 2 (since10or11forms a 2-bit character). - If
bits[i]is0, incrementiby 1 (since0is a 1-bit character).
- After the loop, check if
iis exactly at the last index (len(bits) - 1).
- If yes, the last character is a one-bit character, return
true. - Otherwise, return
false.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(N), whereNis the length ofbits. - 🧺 Space complexity:
O(1), as only a constant amount of extra space is used.