🔤 From UTF-8 to Grammar — Master the Art of Binary Strings
Welcome, binary explorer! 🚀 Binary strings are everywhere — from how your browser decodes characters to how grammar generates infinite sequences. This guide unlocks 5 essential patterns that'll make you see 0s and 1s in a whole new light.
Binary strings are deceptively simple — they're just sequences of 0s and 1s, right? But they show up in some of the most fascinating problems in computer science.
Think about it:
Every character you type is encoded as binary (UTF-8)
Networks send data as binary streams that must be validated
Grammar rules generate infinite binary sequences from simple rules
Parity checks detect errors in data transmission
This is NOT just theory — these exact problems appear in FAANG interviews regularly. UTF-8 validation? Amazon asks it. K-th symbol? Google loves it. Alternating strings? Meta asks variations constantly.
Let's dive into the patterns that make these problems click.
1. UTF-8 Validation — Check Those Continuation Bytes
Problem: Given an array of integers representing bytes, determine if it's a valid UTF-8 encoding. UTF-8 characters can be 1 to 4 bytes long, and each byte must follow specific rules.
Note
🚂 Real-World Analogy: Imagine a train where each car has a label. A single-car train starts with "0" (ASCII). A 2-car train: the first car says "110" and the second says "10". A 3-car train: first says "1110", next two say "10". A 4-car train: first says "11110", next three say "10". The train is valid if every car's label matches the pattern, and the train doesn't end mid-journey with missing cars!
🤔 The Backstory
Imagine you're building a browser from scratch (or writing a network protocol). You receive a stream of bytes. How do you know where one character ends and another begins? That's exactly what UTF-8 encoding rules define!
UTF-8 Byte Rules
UTF-8 has a beautiful, self-synchronizing design. Just look at the first byte and you know the character's total length:
First Byte Pattern
Byte Range
Total Bytes
Data Bits
0xxxxxxx
0x00 - 0x7F
1
7
110xxxxx
0xC0 - 0xDF
2
5 + 6 = 11
1110xxxx
0xE0 - 0xEF
3
4 + 6 + 6 = 16
11110xxx
0xF0 - 0xF7
4
3 + 6 + 6 + 6 = 21
Every continuation byte (bytes 2, 3, 4) MUST start with 10. This is how UTF-8 is self-synchronizing — even if you jump into the middle of a stream, you can find character boundaries!
UTF-8 Validation Encoding Rules
The Algorithm
Here's the plan:
Look at the first byte → count the number of leading 1s before the first 0
Leading 1s count = number of bytes in the character (0 = 1 byte, 2 = 2 bytes, 3 = 3 bytes, 4 = 4 bytes)
For each continuation byte, check: (byte & 0xC0) === 0x80 (i.e., starts with "10")
No overlong encodings allowed (e.g., using 2 bytes to encode a 1-byte character)
🔍 Real-Time Thinking — What Do I Know?
"I need to validate a UTF-8 byte sequence. UTF-8 has self-synchronizing properties: the first byte tells me the total character length. If the byte starts with 0, it's a 1-byte ASCII character. If it starts with 110, it's a 2-byte character. 1110 means 3-byte, 11110 means 4-byte. Every continuation byte MUST start with 10. I'll track 'remaining' — how many continuation bytes I still expect. For each byte: if remaining is 0, I'm starting a new character — count leading 1s to determine remaining. If remaining > 0, I verify it starts with 10 and decrement."
📋 Edge Cases to Consider
Overlong encoding: Using 2 bytes to encode an ASCII character (e.g., 0xC0 0x81 for 'A'). MUST be rejected per UTF-8 spec.
Unexpected continuation byte: A byte starting with "10" appears as a leader (remaining=0). Invalid.
Incomplete sequence at end of array: remaining > 0 when array ends. Invalid — missing continuation bytes.
Value > 0x10FFFF: 4-byte sequences encode code points. Maximum valid code point is U+10FFFF. Values exceeding this are invalid.
Byte 0xFF or 0xFE: These byte values (11111110, 11111111) are invalid in UTF-8 — they don't match any valid pattern.
example.js
function validUtf8(data) {
let remaining = 0; // How many continuation bytes we still expect
for (const byte of data) {
if (remaining === 0) {
// Count leading 1s to determine character length
if ((byte >> 5) === 0b110) remaining = 1; // 2-byte: 110xxxxx
else if ((byte >> 4) === 0b1110) remaining = 2; // 3-byte: 1110xxxx
else if ((byte >> 3) === 0b11110) remaining = 3; // 4-byte: 11110xxx
else if ((byte >> 7) !== 0) return false; // Invalid: 10xxxxxx without leader, or 11111xxx
// else: (byte >> 7) === 0 → valid 1-byte character (0xxxxxxx), do nothing
} else {
// Must be a continuation byte: must start with "10"
if ((byte >> 6) !== 0b10) return false;
remaining--;
}
}
return remaining === 0; // No unfinished sequences
}
📊 Dry Run — Example: [197, 130, 1]
Let's trace through a valid 3-byte UTF-8 sequence:
Byte
Binary
remaining BEFORE
Action
remaining AFTER
197
11000101
0
Starts with 110 → 2-byte char, expect 1 continuation
1
130
10000010
1
Starts with 10 ✅, continuation byte OK
0
1
00000001
0
Starts with 0 → single byte ASCII ✅
0
Key Insight
🔑 Key Insight: The magic is in the byte prefix pattern.0xxxxxxx = ASCII (single byte). 110xxxxx = leader of 2-byte.10xxxxxx = continuation. Since "10" never appears as a prefix of a leader byte (leaders start with "0", "110", "1110", or "11110"), the encoding is self-synchronizing. If you lose a byte mid-stream, you can always find the next character boundary!
Edge Cases
Overlong encoding: Using 2 bytes for a value that fits in 1 (e.g., encoding ASCII 'A' as 0xC0 0x81 instead of 0x41). MUST be rejected.
Unexpected continuation: A byte starting with "10" appears without a preceding leader → invalid.
Trailing bytes missing: A leader says "expect 2 more bytes" but the array ends → invalid.
Values > 0x10FFFF: Unicode code points max out at U+10FFFF (4-byte). Values exceeding that are invalid.
Tip
⚡ Interview Tip: The check (byte & 0xC0) === 0x80 is how you verify a continuation byte. 0xC0 = 11000000 (masks the top 2 bits). Continuation bytes have top 2 bits = "10" = 0x80. This is cleaner than comparing to specific byte ranges.
PROBLEMUTF-8 Validation
Given an array of integers, determine if it's a valid UTF-8 encoding — check leading byte patterns and continuation bytes.
Editable example loads when this section enters view.
2. Alternating Binary String — Minimum Changes
Problem: Given a binary string s, return the minimum number of bit flips (0→1 or 1→0) to make it alternating — meaning no two adjacent characters are the same.
Note
🎨 Real-World Analogy: Imagine you're painting a fence with alternating colors — red, blue, red, blue... There are only TWO valid patterns: starting with red or starting with blue. If your fence has some wrong colors, count how many posts need repainting for each pattern and pick the one with fewer changes. That's exactly the alternating string problem!
🤔 The Pattern Insight
An alternating binary string can only be ONE of two patterns:
Pattern 0: starts with '0': "010101..."
Pattern 1: starts with '1': "101010..."
That's it! There's no third option. Every valid alternating string is one of these two. So the problem reduces to: compare the input with both patterns and count differences. Take the minimum.
Alternating Binary String Two Patterns
The Algorithm
example.js
function minOperations(s) {
let diff0 = 0; // Differences when pattern starts with '0'
let diff1 = 0; // Differences when pattern starts with '1'
for (let i = 0; i < s.length; i++) {
// Pattern 0: char at position i should be '0' if i is even, '1' if i is odd
// Pattern 1: char at position i should be '1' if i is even, '0' if i is odd
const expectedFor0 = i % 2 === 0 ? '0' : '1';
const expectedFor1 = i % 2 === 0 ? '1' : '0';
if (s[i] !== expectedFor0) diff0++;
if (s[i] !== expectedFor1) diff1++;
}
return Math.min(diff0, diff1);
}
// Even more elegant — single pass, no need to count both!
function minOperationsOptimized(s) {
let changesStartsWith0 = 0;
let changesStartsWith1 = 0;
for (let i = 0; i < s.length; i++) {
// Compare with '0' at even positions, '1' at odd positions
const expected = i % 2 === 0 ? '0' : '1';
if (s[i] !== expected) changesStartsWith0++;
// Pattern starting with 1 is just the COMPLEMENT!
changesStartsWith1 = s.length - changesStartsWith0;
}
return Math.min(changesStartsWith0, changesStartsWith1);
}
📊 Dry Run — "0100"
Position
s[i]
Pattern 0 (0101...)
Pattern 1 (1010...)
diff0
diff1
0
0
0 ✓
1 ✗
0
1
1
1
1 ✓
0 ✗
0
2
2
0
0 ✓
1 ✗
0
3
3
0
1 ✗
0 ✓
1
3
Result: min(1, 3) = 1. Flip the last character (0→1) and we get "0101" 🎯
Key Insight
🔑 The Key Insight: You don't even need to generate the patterns! At position i, the alternating pattern is determined by parity: if i is even, character should be the same as position 0; if i is odd, it should flip. For pattern starting with '0', it's i % 2 === 0 ? '0' : '1'. The other pattern is just the complement!
PROBLEMMinimum Changes to Make Alternating Binary String
Find the minimum number of bit flips needed to make a binary string alternating. Compare with both possible patterns.
Editable example loads when this section enters view.
3. Generate Binary Strings Without Adjacent Zeros
Problem: Given an integer n, generate all binary strings of length n that have no adjacent zeros.
🤔 The Decision: Place 0 or 1?
At each position, I decide: "Do I place a 0 or a 1?" But there's a constraint — I can ONLY place a 0 if the previous character was NOT 0 (no adjacent zeros). This is like building a wall where I can always lay a red brick (1), but I can only lay a blue brick (0) if the last brick wasn't blue. The choice is always available for 1, but conditional for 0. This naturally prunes the search tree!
🤔 Backtracking Intuition
Think of it like building a wall with bricks. You have two types of bricks: '0' and '1'. The rule: you can NEVER place two '0' bricks next to each other.
This is a classic backtracking with pruning problem:
If the last character was '0', the next character MUST be '1' (because two zeros can't be adjacent)
If the last character was '1', the next character can be either '0' or '1'
The Algorithm
example.js
function generateWithoutAdjacentZeros(n) {
const result = [];
function backtrack(current, lastWasZero) {
if (current.length === n) {
result.push(current.join(''));
return;
}
// We can ALWAYS place a '1'
current.push('1');
backtrack(current, false);
current.pop();
// We can place '0' ONLY if last wasn't zero
if (!lastWasZero) {
current.push('0');
backtrack(current, true);
current.pop();
}
}
backtrack([], false);
return result;
}
// Result for n = 3:
// ["111", "110", "101", "011", "010"]
// Notice: "100", "001", "000" are missing — they have adjacent zeros!
📊 Dry Run — n = 3
Let's trace the recursion tree. At each step, we decide what to place next:
Step
Current String
Last Was 0?
Options
1
""
No
'0' or '1'
2
"1"
No
'0' or '1'
3
"10"
Yes
MUST be '1' (can't place '0' after '0')
4
"101"
No
✓ Complete! Push "101"
5
"11"
No
'0' or '1'
6
"110"
Yes
MUST be '1'
7
"110" → "1101"
—
Length exceeded n=3, stopping
Warning
⚠️ Common Mistake: Don't confuse this with "no consecutive 1's" — that's a different (but similar) problem. The constraint here is specifically no adjacent zeros, which means zeros are the restricted character. Ones are always free!
Complexity
Time: O(2ⁿ) in the worst case (all strings of 0s and 1s), but the constraint prunes branches significantly. For length n, the count follows the Fibonacci sequence! F(n+2) where F(1)=1, F(2)=1. For n=10, that's 144 strings instead of 1024 — 86% savings.
Tip
⚡ Fibonacci Connection: Let f(n) = number of valid strings of length n. If the string starts with '1', the rest can be any valid string of length n-1 → f(n-1). If it starts with '0', the next MUST be '1', then the rest can be any valid string of length n-2 → f(n-2). So f(n) = f(n-1) + f(n-2). That's Fibonacci! 🎯
PROBLEMGenerate Binary Strings Without Adjacent Zeros
Given n, generate all binary strings of length n with no adjacent zeros using backtracking with pruning.
Editable example loads when this section enters view.
4. Concatenation of Consecutive Binary Numbers
Problem: Given an integer n, return the decimal value of the binary string formed by concatenating numbers from 1 to n in order. Return modulo 10⁹ + 7.
🔍 Real-Time Thinking — What Do I Know?
"I need to concatenate binary representations of 1..n and interpret the result as a decimal. n can be up to 10⁵ — I can't build the actual string! But what if I think about it differently? Each time I append a number, I shift the existing result LEFT by the bit-length of the new number, then OR them together. result = (result << bitLength(i)) | i. And bitLength only increases at powers of 2. I can detect powers of 2 with (i & (i-1)) === 0!"
🤔 The Intuition
For n = 3, we concatenate the binary representations of 1, 2, and 3:
The challenge? n can be up to 10⁵ — we can't just build the string! We need to compute the value mathematically.
The Bit-Shift Trick
Think about what happens when we append a number to our result. If we have resultval so far, and we want to append num:
We need to shift val left by the bit length of num
Then OR (or add) num to the result
example.js
val = (val << bitLength(num)) | num
// Example: val = "1" (1), num = 2 (binary "10", length 2)
// Step: 1 << 2 = 4 (binary "100")
// Then: 4 | 2 = 6 (binary "110")
// But wait — "110" = 6, but "1" + "10" = "110" = 6 ✅
The Algorithm
example.js
function concatenatedBinary(n) {
const MOD = 1_000_000_007;
let result = 0;
let bitLen = 0; // Current bit length of the number being appended
for (let i = 1; i <= n; i++) {
// If i is a power of 2, its bit length increases by 1
// (e.g., 2→3, 4→7, 8→15: the bit length grows at powers of 2)
if ((i & (i - 1)) === 0) {
bitLen++; // i is a power of 2, bit length just increased
}
// Shift result left by bitLen and add current number
result = ((result << bitLen) | i) % MOD;
}
return result;
}
// Why check (i & (i-1)) === 0?
// This is the "is power of 2" check. Numbers and their bit lengths:
// 1 (1) → bitLen=1 ← power of 2
// 2 (10) → bitLen=2 ← power of 2
// 3 (11) → bitLen=2
// 4 (100) → bitLen=3 ← power of 2
// 5 (101) → bitLen=3
// ...
📊 Dry Run — n = 4
i
Binary
Power of 2?
bitLen
Operation
Result
1
1
✅
1
(0 << 1) | 1
1 (1)
2
10
✅
2
(1 << 2) | 2
6 (110)
3
11
❌
2
(6 << 2) | 3
27 (11011)
4
100
✅
3
(27 << 3) | 4
220 (11011100)
Concatenated: "1" + "10" + "11" + "100" = "11011100" = 220 decimal. Check: 1→1, 1→110 (6), 110→11011 (27), 11011→11011100 (220). Each step: left shift by bitLen, OR new number. ✅
Key Insight
🔑 The Key Insight: The bit length of numbers increases only at powers of 2. Instead of computing bit length via Math.floor(Math.log2(i)) + 1every iteration (which costs O(log n)), we just check (i & (i-1)) === 0— a single O(1) bit operation. This is the same trick used to check if a number is a power of 2!
PROBLEMConcatenation of Consecutive Binary Numbers
Given n, return the decimal value of concatenating binary representations of 1 to n modulo 10^9+7. Use bit-length tracking for O(n) solution.
Editable example loads when this section enters view.
5. K-th Symbol in Grammar — Recursive Tree Traversal
Problem: We build a table of n rows (1-indexed). We start with0 in row 1. For each subsequent row, we replace every0 with 01 and every1 with 10. Given n and k, return the k-th symbol in row n.
Note
🌳 Real-World Analogy: Imagine a family tree where every parent has exactly two children. 0-parents have children 0 and 1. 1-parents have children 1 and 0. Starting from the root (0), each generation doubles. To find the k-th person in generation n, I trace back to the root: at each step, I ask "am I the first child (odd k) or second child (even k)?" First child = same as parent. Second child = flipped. This is the "Odd = same, Even = flip" rule!
🤔 The Grammar Tree
This is one of the most mind-bending problems — until you see the pattern. Here's how the grammar grows:
Here's the trick: every row is built from the previous row. Each element in row n-1spawns two children in row n. If we know the parent, we know the children:
Parent = 0 → children are 0 (first) and 1 (second)
Parent = 1 → children are 1 (first) and 0 (second)
So if we want the k-th symbol in row n, we need to:
Find its parent: parentIndex = Math.ceil(k / 2) → this is which element in row n-1 spawned our element
Find the parent value: recursively kthGrammar(n-1, parentIndex)
Determine if k is the first or second child: isOdd = k % 2 === 1
If k is odd → it's the first child (same as parent). If even → it's the second child (flipped: parent ^ 1)
example.js
function kthGrammar(n, k) {
if (n === 1) return 0; // Base case: row 1 is always "0"
const parentIndex = Math.ceil(k / 2);
const parentValue = kthGrammar(n - 1, parentIndex);
if (k % 2 === 1) {
// Odd position → first child → same as parent
return parentValue;
} else {
// Even position → second child → flipped
return parentValue ^ 1; // XOR with 1 flips: 0→1, 1→0
}
}
// Iterative version (equally intuitive):
function kthGrammarIterative(n, k) {
let result = 0; // Start with row 1's only value
let left = 1, right = Math.pow(2, n - 1); // Search range in row n
for (let row = 1; row < n; row++) {
const mid = Math.floor((left + right) / 2);
if (k <= mid) {
right = mid; // Go left → first child → same
} else {
left = mid + 1; // Go right → second child → flip
result ^= 1;
}
}
return result;
}
📊 Dry Run — kthGrammar(4, 5)
Find the 5th symbol in row 4. Let's trace:
Call
n
k
parentIdx
k odd?
parentVal
Return
kthGrammar(4,5)
4
5
ceil(5/2)=3
odd
?
= parentVal
→ kthGrammar(3,3)
3
3
ceil(3/2)=2
odd
?
1
→→ kthGrammar(2,2)
2
2
ceil(2/2)=1
even
0
0^1=1
→→→ kthGrammar(1,1)
1
1
—
—
—
0 🎯 base
Answer: kthGrammar(4, 5) = 1
Tip
💡 The Parent-Child Rule Visualized: Every element 0 spawns "01", and every element 1 spawns "10". Position k in row n is at position ceil(k/2) in row n-1. If k is odd → first child → parent's value. If k is even → second child → complement (flip) of parent's value. Memorize: "Odd = same, Even = flip"
PROBLEMK-th Symbol in Grammar
Find the k-th symbol in row n of the grammar where 0→01 and 1→10. Use recursive parent lookup with the 'odd=same, even=flip' rule.
Editable example loads when this section enters view.
6. Parity & Basic Bit Operations — Complete Reference
Before we wrap up, here's your cheat sheet for the fundamental bit operations. These are the building blocks of EVERY bit manipulation solution.
Parity and Basic Bit Operations Cheat Sheet
Quick Reference Table
Operation
Expression
Example (n=5, 0101)
Get bit i
(n >> i) & 1
(5>>2)&1 = 1
Set bit i
n | (1 << i)
5 | (1<<1) = 7
Clear bit i
n & ~(1 << i)
5 & ~(1<<0) = 4
Toggle bit i
n ^ (1 << i)
5 ^ (1<<2) = 1
Lowest set bit
n & (-n)
5 & -5 = 1
Clear lowest set bit
n & (n-1)
5 & 4 = 4
Is power of 2
n > 0 && (n & (n-1)) === 0
4 & 3 = 0 → true
Count set bits
while(n) { count++; n &= n-1 }
5 has 2 set bits (101)
Parity (odd # of 1s)
while(n) { p ^= 1; n &= n-1 }
5(101) → 2 ones → even → 0
Note
📝 Two's Complement Magic:n & (-n) isolates the lowest set bit. Why? In two's complement, -n = ~n + 1. The ~n flips all bits, and +1 causes carries that stop at the rightmost 1. The AND of n and -n clears all bits except that rightmost 1. This is HANDS DOWN the most useful bit trick to memorize! It's used in Fenwick Trees, set bit isolation, and Single Number III.
🎯 Interview Cheat Sheet
Key Insight
Q1: How do I check if a byte is a valid UTF-8 continuation byte? (byte & 0xC0) === 0x80. The mask 0xC0 = 11000000 keeps only the top 2 bits. Continuation bytes have top 2 bits = "10" = 0x80. This is faster and cleaner than range checks.
Key Insight
Q2: What are the two alternating patterns for a binary string? Only two: starting with '0' → "010101..." or starting with '1' → "101010...". Compare input with both, count differences, take min. The second pattern is always the complement of the first: changes1 = n - changes0.
Key Insight
Q3: How do I track bit length without calling log2? Use (i & (i-1)) === 0 to detect powers of 2. Bit length increments only at powers of 2 (1→2, 2→3, 4→3, 8→4). Maintain a running counter.
Key Insight
Q4: What's the parent-child rule for K-th Symbol in Grammar? "Odd = same, even = flip." Parent index = ceil(k/2). If k is odd → first child → same as parent. If even → second child → flipped (parent ^ 1).
Key Insight
Q5: How to generate strings without adjacent zeros? Backtracking with state: track if last was 0. If yes, next MUST be 1. The count of valid strings follows Fibonacci: f(n) = f(n-1) + f(n-2).
Key Insight
Q6: What does n & (n-1) do? Clears the lowest set bit. Used for: power-of-2 check (if result = 0), counting set bits (repeated until n = 0), and parity calculation (XOR a counter each time).
📝 Key Takeaways
UTF-8 validation — count leading 1s to determine byte length, verify each continuation byte with (byte & 0xC0) === 0x80
Alternating strings — only 2 possible patterns (starting with 0 or 1), compare both and take minimum differences. Pattern at position i = i % 2 === 0 ? startChar : flipChar
No adjacent zeros — backtrack with state pruning: if last was 0, next must be 1. Count follows Fibonacci sequence
Consecutive binary concatenation — track bit length via power-of-2 detection (i & (i-1)) === 0, shift and OR each number
K-th symbol in grammar — recursive tree traversal: parent at ceil(k/2). "Odd = same, even = flip"
Bit ops arsenal — get, set, clear, toggle, isolate lowest set bit (n & -n), clear lowest set bit (n & (n-1)). These 6 operations unlock 90% of bit problems
Time & Space — UTF-8: O(n), O(1). Alternating: O(n), O(1). No adjacent zeros: O(Fib(n)), O(n) for recursion. Concat: O(n), O(1). K-th symbol: O(n), O(n) or O(1) iterative
Memorize:n & -n (isolate lowest set bit) and n & (n-1) (clear lowest set bit) — these are the two most powerful bit tricks!
Practice! — The only way binary strings become intuitive is repetition. Use the Playground below to test yourself 🥋
Note
🔮 What's Next? Now that you've mastered binary string validation and generation, check out Bit Masking & Complementsfor more bit manipulation patterns!