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 (
10
or11
).
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 <= 1000
bits[i]
is either0
or1
.
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
i
at the start of the array. - While
i
is less than the last index:
- If
bits[i]
is1
, incrementi
by 2 (since10
or11
forms a 2-bit character). - If
bits[i]
is0
, incrementi
by 1 (since0
is a 1-bit character).
- After the loop, check if
i
is 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)
, whereN
is the length ofbits
. - 🧺 Space complexity:
O(1)
, as only a constant amount of extra space is used.