Problem Description
Given a binary array bits that always ends with 0, determine if the last character is a one-bit character. In the encoding scheme, a 0 represents a one-bit character, whereas a 1 along with the bit that follows represents a two-bit character. You must decide if the array is decoded in such a way that the final character is a one-bit character.
Key Insights
- Traverse the array from the beginning.
- If a 1 is encountered, skip the next bit since it forms a two-bit character.
- If a 0 is encountered, move one step.
- The final character must be interpreted correctly: if the pointer lands on the last index, it implies that the last character is one-bit; if not, it's part of a two-bit character.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the bits array.
Space Complexity: O(1), using only constant extra space.
Solution
The approach uses a simple pointer to iterate through the given bits array. We start from the beginning and move the pointer as follows:
- If the current bit is 1, it indicates a two-bit character, so we increment the pointer by 2.
- If the current bit is 0, it is a one-bit character, so we increment by 1.
The key is to check whether the pointer exactly lands on the last index when the loop finishes. If so, the last character is one-bit; otherwise, it is not. This solution is straightforward and uses constant space.