1-bit and 2-bit Characters - 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 or 11)

Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.

Note: The array is guaranteed to end with 0.

Input & Output

Example 1 — Two-bit then One-bit
$ Input: bits = [1,0,0]
Output: true
💡 Note: The first character is a two-bit character "10", and the second character is a one-bit character "0". So the last character is a one-bit character.
Example 2 — Two consecutive 1's
$ Input: bits = [1,1,0]
Output: true
💡 Note: The array decodes as one two-bit character "11" followed by one one-bit character "0". So the last character is a one-bit character.
Example 3 — Single character
$ Input: bits = [0]
Output: true
💡 Note: The array contains only one bit "0", which is a one-bit character.

Constraints

  • 1 ≤ bits.length ≤ 1000
  • bits[i] is either 0 or 1
  • bits[bits.length - 1] == 0

Visualization

Tap to expand
1-bit and 2-bit Characters INPUT Binary Array: bits[] 1 idx 0 0 idx 1 0 idx 2 Character Types: 1-bit char: [0] 2-bit char: [1,0] or [1,1] Question: Is the last 0 a 1-bit character? Input Values: bits = [1, 0, 0] ALGORITHM STEPS 1 Initialize i = 0, n = 3 2 Traverse Array While i < n-1 3 Count Characters bits[i]==1? i+=2 : i+=1 4 Check Final Position Return i == n-1 Execution Trace: i bits[i] action 0 1 i += 2 2 - i == n-1 Final: i=2, n-1=2 FINAL RESULT Decoding Process: [1, 0] 2-bit char [0] 1-bit char First char --> Second char [1,0] consumes indices 0-1 Last [0] at index 2 is alone It MUST be 1-bit char! Output: true Key Insight: When bits[i]=1, it always starts a 2-bit character (10 or 11), so skip 2 positions. If we land exactly at n-1 (the last bit), the last 0 must be a standalone 1-bit character. TutorialsPoint - 1-bit and 2-bit Characters | Count Two-Bit Characters Approach
Asked in
Google 15 Facebook 12
28.7K Views
Medium Frequency
~15 min Avg. Time
894 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen