1-bit and 2-bit Characters
EasyUpdated: Aug 2, 2025
Practice on:
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:
Input: bits = [1,0,0]
Output: true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
Example 2:
Input: bits = [1,1,1,0]
Output: false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
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
Java
class Solution {
public boolean isOneBitCharacter(int[] bits) {
int i = 0, n = bits.length;
while (i < n - 1) {
i += bits[i] == 1 ? 2 : 1;
}
return i == n - 1;
}
}
Python
class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i, n = 0, len(bits)
while i < n - 1:
i += 2 if bits[i] == 1 else 1
return i == n - 1
Complexity
- ⏰ Time complexity:
O(N), whereNis the length ofbits. - 🧺 Space complexity:
O(1), as only a constant amount of extra space is used.