#717
1-bit and 2-bit Characters
EasyArrayArrayGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass through the array to determine if the last character is a one-bit character. By keeping track of the last valid character position, we can efficiently decide the outcome without unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a pointer at the start of the bits array.
- 2Step 2: Iterate through the bits array until the second last element.
- 3Step 3: If the current bit is 1, skip the next bit (move the pointer by 2). If it's 0, move the pointer by 1.
- 4Step 4: At the end of the iteration, check if the pointer is at the last bit (0). If yes, return true; otherwise, return false.
solution.py5 lines
1def isOneBitCharacter(bits):
2 i = 0
3 while i < len(bits) - 1:
4 i += 2 if bits[i] == 1 else 1
5 return i == len(bits) - 1ℹ
Complexity note: The complexity is O(n) because we only pass through the bits array once, making it efficient.
- 1The last character must always be a one-bit character if the pointer ends at the last index.
- 2The decoding is straightforward as we only need to check the current bit and decide how many bits to skip.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.