๐ช Every string is secretly an integer โ learn to see the bits
Welcome, future bit wizard! ๐ Did you know that every string can be encoded as a single integer using bits? That's right โ a 26-letter word fits in one 32-bit machine word. Compare thousands of strings with a single & operation. This is the SUPERPOWER we unlock today. By the end of this guide, you'll be able to spot bit-string problems instantly and solve them in your sleep. We cover 6 essential LeetCode patterns, from character-set bitmasks to rolling hashes for DNA sequences.
๐ค Why Bit String Patterns Matter: The Party Problem
Imagine you're at a party checking invitations. Every guest has a list of allowed items they can bring. You need to check 10,000 bags, each with 50 items, against a permission list. Checking each item individually would take forever.
What if you could encode the permission list as a single number?
That's EXACTLY what bit strings do. Each bit position represents one character. Bit 0 = 'a', bit 1 = 'b', ..., bit 25 = 'z'. A set bit means "this character is present". Suddenly, checking if 'c' is allowed becomes checking if bit 2 is set โ a single (mask & (1 << 2)) !== 0. That's O(1), not O(26).
This trick appears constantly in Amazon, Google, and Meta interviews. The "I've seen this before" factor is REAL. Let's master it.
Bitmask Flag Encode abc into an Integer
Key Insight
๐ก The Core Insight: A 26-bit integer can represent the entire lowercase alphabet. Operations that would take O(alphabet size) become O(1) bitwise operations. Comparison, containment, intersection โ all in a single machine instruction.
1. Count Consistent Strings โ Bitmask per Word
Problem: You are given a string allowed consisting of distinct characters and an array of words. A string is consistent if all its characters appear in allowed. Return the number of consistent strings.
Note
๐ซ Real-World Analogy: Imagine you're a bouncer at an exclusive club. The club only allows guests with specific attributes (like "wearing red" or "has a VIP pass"). Each guest arrives with a list of their attributes. Instead of checking each attribute one by one, you encode the club's policy as a bitmask and the guest's attributes as another bitmask. If (policyMask & guestMask) === guestMask, the guest only has allowed attributes โ they're in! One AND operation decides their fate.
๐ค Let's Think About It
Take a moment. If you'd never seen bitmasks before, how would you solve this?
Brute Force Approach
example.js
function countConsistentBrute(allowed, words) {
const allowedSet = new Set(allowed);
let count = 0;
for (const word of words) {
let consistent = true;
for (const ch of word) {
if (!allowedSet.has(ch)) {
consistent = false;
break;
}
}
if (consistent) count++;
}
return count;
}
โ This works! But each Set.has() is O(1) on average, so it'sO(n ยท k). Not bad, but we can do better with bitmasks โ and the bitmask version scales better when we need more complex operations (intersection, subset, exact match).
โจ The Bitmask Solution
Build a 26-bit mask for allowed, then build a mask for each word. A word is consistent when (allowedMask & wordMask) === wordMask. Every set bit in the word must also be set in the allowed mask.
๐ Real-Time Thinking โ What Do I Know?
"I need to check if each word uses ONLY characters from the allowed set. If I encode the allowed set as a 26-bit mask, and each word as another mask, then a word is consistent if EVERY set bit in the word mask is ALSO set in the allowed mask. That's exactly: (allowedMask & wordMask) === wordMask. If word has a character not in allowed, its bit will be 1 in wordMask but 0 in allowedMask โ the AND clears it, and the equality fails!"
example.js
function countConsistentStrings(allowed, words) {
// Build allowed bitmask
let allowedMask = 0;
for (const ch of allowed) {
const bit = 1 << (ch.charCodeAt(0) - 97);
allowedMask |= bit;
}
let count = 0;
for (const word of words) {
let wordMask = 0;
for (const ch of word) {
const bit = 1 << (ch.charCodeAt(0) - 97);
wordMask |= bit;
}
// All chars in word must be in allowed set
// This single & operation replaces a loop of Set.has() checks!
if ((allowedMask & wordMask) === wordMask) {
count++;
}
}
return count;
}
๐ Dry Run โ Watch It In Action
Let's trace through countConsistentStrings("ab", ["a", "b", "ab", "c"]). This is where the intuition CLICKS:
โก Interview Tip: When you hear "check if string uses only characters from a set", think bitmask. The check (allowedMask & wordMask) === wordMask is the core operation โ it's a subset check in O(1). Say it out loud in interviews: "I can encode the character set as a bitmask and check containment with a single AND operation."
2. Count Pairs of Similar Strings โ Bitmask Equality
Problem: Two strings are similar if they consist of the same set of characters. Order and frequency don't matter. Given an array of words, count the number of pairs (i, j) where the two words are similar.
Note
๐ฏ Real-World Analogy: Two strings are "similar" if they use the same SET of characters, ignoring duplicates. "ab" and "aab" and "ba" all have the same character set {a, b}. A bitmask naturally encodes just the set โ OR is idempotent, so 'a' appearing once or ten times still just sets bit 0 to 1. Two words are similar exactly when their bitmasks are EQUAL. So group by mask and count pairs!
The Bitmask Set Trick
This is where bitmasks REALLY shine. A word's bitmask naturally encodes its set of characters โ duplicates don't matter because OR is idempotent. mask("aba") equals mask("ab") equals mask("ba").
Two words are similar precisely when their masks are EQUAL. So we group by mask and count pairs using the combination formula: k * (k - 1) / 2 for each group of size k.
example.js
function similarPairs(words) {
const map = new Map();
for (const word of words) {
let mask = 0;
for (const ch of word) {
const bit = 1 << (ch.charCodeAt(0) - 97);
mask |= bit; // OR is idempotent โ duplicates don't change the mask
}
map.set(mask, (map.get(mask) ?? 0) + 1);
}
// For each group of size k, there are k*(k-1)/2 similar pairs
let pairs = 0;
for (const count of map.values()) {
pairs += (count * (count - 1)) / 2;
}
return pairs;
}
// Example:
// words = ["aba", "aab", "bab", "xyz"]
// masks: 0b011 0b011 0b011 0b111000
// Group sizes: 0b011 โ 3, 0b111000 โ 1
// Pairs = C(3,2) + C(1,2) = 3 + 0 = 3
Let's trace through this visually:
Count Pairs of Similar Strings Mask Equality
Key Insight
๐ The Genius Trick: OR is idempotent โ whether a character appears once or a thousand times, its bit is set exactly once. This means the bitmask IS the character set. Comparing two sets becomes comparing two integers: mask1 === mask2. This is O(1) instead of O(min(k1, k2)) for set comparison.
Complexity Analysis
Time: O(n ยท k) to build masks, O(n) to group and count. Space: O(n) for the hash map. Brute-forcing all pairs would be O(nยฒ ยท k) โ the bitmask transforms this into a linear scan.
3. Max Length Concat Unique Chars โ Backtrack + Bitmask
Problem: Given an array of strings arr, find the maximum possible length of a concatenated string you can form by choosing a subsequence of arr such that the resulting string has all unique characters.
๐ค The Decision: Include or Skip?
For each string, I have a binary choice: "Do I include this string or skip it?" If I include it, I gain its length but risk character overlap. The overlap check is O(1) with bitmasks: (currentMask & stringMask) === 0. If no overlap, I can safely OR the masks and add the length. This is classic subset enumeration with pruning โ backtrack over strings, and at each step, choose to include (if no overlap) or skip.
๐ค Think About It
We need to pick a subset of strings where no character repeats across the entire concatenation. This is a classic set-packing problem. With 16 strings, brute-forcing all 2^16 subsets is expensive โ but bitmasks make each overlap check O(1).
Bitmask + Backtracking Solution
Each string gets a 26-bit mask. A string is valid only if it has no internal duplicates (popcount of mask equals string length). Two strings can be concatenated if their masks don't overlap: (mask1 & mask2) === 0.
example.js
function maxLength(arr) {
// Filter: only keep strings with all unique characters
const masks = [];
const lens = [];
for (const s of arr) {
let mask = 0;
let valid = true;
for (const ch of s) {
const bit = 1 << (ch.charCodeAt(0) - 97);
if (mask & bit) { valid = false; break; }
mask |= bit;
}
if (valid) {
masks.push(mask);
lens.push(s.length);
}
}
let best = 0;
function backtrack(i, currentMask, currentLen) {
best = Math.max(best, currentLen);
for (let j = i; j < masks.length; j++) {
if ((currentMask & masks[j]) === 0) {
// No character overlap โ safe to concatenate!
backtrack(
j + 1,
currentMask | masks[j],
currentLen + lens[j]
);
}
}
}
backtrack(0, 0, 0);
return best;
}
// Helper: count set bits (popcount)
function bitCount(x) {
let count = 0;
while (x) { count += x & 1; x >>>= 1; }
return count;
}
Dry Run
Let's trace maxLength(["ab", "cd", "ac"]):
Step
String
Mask
Valid?
currentMask
Can add?
Best
1
"ab"
00011
โ
00000
โ (no overlap)
2
2
"cd"
01100
โ
00011
โ (no overlap)
4
3
"ac"
00101
โ
01111
โ (overlaps 'a' and 'c')
4
Best concatenation: "ab" + "cd" = "abcd" (length 4).
Warning
โ ๏ธ NP-Hard Alert: This problem is a variant of Maximum Set Packing, which is NP-hard. The bitmask doesn't change the worst-case complexity (O(2โฟ)), but it makes each operation O(1) instead of O(26). For n โค 16, this runs instantly โ without bitmasks, even n = 12 would struggle.
4. All Binary Codes of Size K โ Sliding Window Bitmask
Problem: Given a binary string s and an integer k, return true if every binary code of length k occurs as a substring of s.
๐ Real-Time Thinking โ What Do I Know?
"There are 2แต possible binary codes of length k. I need to check if ALL of them appear as substrings in s. If I slide a window across s and collect each k-bit value, I need exactly 2แต distinct values. The trick is computing each window's value in O(1): shift left by 1, add the new bit, mask to keep k bits. This is the Rabin-Karp rolling hash with base 2 โ no collisions because each k-bit value maps uniquely to an integer 0..2แต-1."
The Sweet Spot
There are exactly 2แต possible binary codes of length k. If we slide a window across s and collect each k-bit window as an integer, we need all 2แต values to appear. The trick: update the window value in O(1) using bit shifts instead of extracting substrings.
example.js
function hasAllCodes(s, k) {
const need = 1 << k; // 2^k possible codes
const seen = new Set();
let mask = 0;
// Build initial mask from first k characters
for (let i = 0; i < k && i < s.length; i++) {
mask = (mask << 1) | (s[i] === '1' ? 1 : 0);
}
if (s.length >= k) {
seen.add(mask);
}
// Slide the window โ O(1) per position
for (let i = k; i < s.length; i++) {
// Drop leftmost bit, shift left, add new rightmost bit
mask = ((mask << 1) | (s[i] === '1' ? 1 : 0))
& ((1 << k) - 1); // Keep only lowest k bits
seen.add(mask);
if (seen.size === need) return true; // Early exit!
}
return seen.size === need;
}
๐ Dry Run โ s = "00110110", k = 2
Window
Substring
Integer
Seen so far
Found all?
0-1
"00"
0
0
โ
1-2
"01"
1
0, 1
โ
2-3
"11"
3
0, 1, 3
โ
3-4
"10"
2
0, 1, 3, 2
โ YES (all 4 codes!)
Tip
โก The Key Trick:mask = ((mask << 1) | bit) & ((1 << k) - 1). Shift left by 1, add the new bit, then mask to keep only k bits. This converts each window to an integer in O(1) instead of O(k) for substring extraction.
Rolling Hash Connection
This is essentially a Rabin-Karp rolling hash with base 2. The sliding mask computes the integer value of each k-bit window incrementally. For binary strings, base 2 is natural and there's zero collision risk โ perfect hashing!
5. Longest Vowel Even Substring โ Prefix XOR State
Problem: Given a string s, find the length of the longest substring where each vowel ('a', 'e', 'i', 'o', 'u') appears an even number of times.
Note
๐ฆ Real-World Analogy: Imagine 5 light switches labeled a, e, i, o, u. Every time you encounter a vowel in the string, you flip its switch (XOR). A substring has all vowels even when ALL switches are OFF at both the start and end of the substring. That means the state (bitmask) is the same at both positions. If you see the same state twice, the substring between those positions has all vowels an even number of times!
The XOR State Machine
This is one of the most elegant bit-string problems. Represent the parity (odd/even) of each vowel as a 5-bit mask: bit 0 = 'a', bit 1 = 'e', bit 2 = 'i', bit 3 = 'o', bit 4 = 'u'.
When we see a vowel, we XOR its bit โ this toggles its parity. A substring has all vowels even when the prefix state at the start equals the prefix state at the end. Why? Because XOR is its own inverse: the segment between two identical prefix states cancels out.
example.js
function findTheLongestSubstring(s) {
// Map vowel โ bit position (0-4)
const vowelBit = { a: 0, e: 1, i: 2, o: 3, u: 4 };
// Map from state (0..31) to first occurrence index
// State 0 (all vowels even) starts at index -1
const firstSeen = { 0: -1 };
let state = 0; // 5-bit mask: bit0=a, bit1=e, bit2=i, bit3=o, bit4=u
let maxLen = 0;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch in vowelBit) {
const bit = 1 << vowelBit[ch];
state ^= bit; // Toggle parity of this vowel
}
if (state in firstSeen) {
// Same state seen before โ substring between is all-even!
maxLen = Math.max(maxLen, i - firstSeen[state]);
} else {
firstSeen[state] = i;
}
}
return maxLen;
}
๐ Dry Run โ "leetcode"
Watch the 5-bit state [a,e,i,o,u] change as we scan:
Longest Vowel Even Substring Prefix XOR State
Prefix
Char
Action
State [a e i o u]
First seen at
Substring length
""
โ
โ
0 0 0 0 0
-1
โ
"l"
l
consonant โ skip
0 0 0 0 0
-1 (already seen)
1
"le"
e
XOR bit 1
0 1 0 0 0
1
โ
"lee"
e
XOR bit 1
0 0 0 0 0
-1 (seen!)
3
"leet"
t
consonant โ skip
0 0 0 0 0
-1 (seen!)
4
"leetc"
c
consonant โ skip
0 0 0 0 0
-1 (seen!)
5
"leetco"
o
XOR bit 3
0 0 0 1 0
5
โ
"leetcod"
d
consonant โ skip
0 0 0 1 0
5 (seen!)
2
"leetcode"
e
XOR bit 1
0 1 0 1 0
? (new)
โ
Longest all-even substring: "leet" (indices 0-3, length 4). The state is 00000 at both index -1 and index 3.
Key Insight
๐ Why XOR works here: XOR is its OWN inverse. state ^ bit ^ bit = state. Each vowel toggles its parity bit. If a vowel appears an even number of times in a substring, its bit toggles an even number of times โ returning to its original value. The state before and after the substring is identical. Only 32 possible states (2โต), making this O(n) and O(1) space!
6. Repeated DNA Sequences โ Rolling Hash with Bits
Problem: Given a string s that represents a DNA sequence, return all 10-letter-long substrings that occur more than once. DNA sequences consist of only A, C, G, T.
๐ Real-Time Thinking โ What Do I Know?
"I need to find 10-letter substrings that appear more than once. With 4 nucleotides (A, C, G, T), I can encode each in 2 bits. A 10-character window = 20 bits โ fits in a 32-bit integer! I can slide a window in O(1) per position: shift left by 2, OR in the new base\'s code, mask to 20 bits. This is a perfect rolling hash โ no collisions needed since 2ยฒโฐ >> string length. Use a set to detect duplicates."
Encoding DNA in 2 Bits Per Base
Since there are only 4 nucleotide bases, we can encode each one in 2 bits:
Base
2-bit code
Binary
A
0
00
C
1
01
G
2
10
T
3
11
A 10-character window fits in 20 bits (10 ร 2 = 20), which fits comfortably in a 32-bit integer. We shift in 2 bits per character to compute a rolling hash, and use a set to detect duplicates.
example.js
function findRepeatedDnaSequences(s) {
if (s.length < 10) return [];
// Map each base to a 2-bit encoding
const code = { A: 0, C: 1, G: 2, T: 3 };
const seen = new Set();
const repeated = new Set();
let hash = 0;
const mask = (1 << 20) - 1; // Keep only lowest 20 bits
// Build initial hash for first 10 characters
for (let i = 0; i < 10; i++) {
hash = ((hash << 2) | code[s[i]]) & mask;
}
seen.add(hash);
// Slide the window โ O(1) per position
for (let i = 10; i < s.length; i++) {
hash = ((hash << 2) | code[s[i]]) & mask;
if (seen.has(hash)) {
repeated.add(s.slice(i - 9, i + 1));
} else {
seen.add(hash);
}
}
return [...repeated];
}
Dry Run โ "AAAAACCCCCAAAAACCCCCCAAAA"
Window
Substring
Hash (20-bit)
In seen?
Action
0-9
"AAAAACCCCC"
0x00000
No
Add to seen
1-10
"AAAACCCCCA"
0x00001
No
Add to seen
...
...
...
...
...
9-18
"AAAAACCCCC"
0x00000
Yes!
Add to repeated
Key Insight
๐ Why It Works: This is a full Rabin-Karp rolling hash for a 4-letter alphabet. Base 4 (2 bits per character) with a 10-character window produces a 20-bit hash โ small enough that we don't need modular arithmetic (no collisions). The mask (1 << 20) - 1 keeps only the lowest 20 bits, automatically discarding the overflow.
Generalization
This 2-bit-per-base encoding generalizes to any small alphabet:
Alphabet size
Bits per char
Max window for 32-bit
2 (binary)
1
32 chars
4 (DNA)
2
16 chars (10 works)
8
3
10 chars
26 (lowercase)
5
6 chars
Warning
โ ๏ธ Overflow Caution: For larger alphabets or window sizes, the hash can overflow 32 bits. In those cases, use modular arithmetic (Rabin-Karp with a large prime) or accept collisions and verify with string comparison.
Q1: When should I use a bitmask instead of a Set for character tracking? When the alphabet is small and known (26 lowercase, 5 vowels, 4 DNA bases). A 26-bit integer fits in one register, comparison is O(1), and it uses less memory. Use a Set for Unicode or large alphabets.
Key Insight
Q2: How do I check if two strings share any character? Compute mask1 and mask2. If (mask1 & mask2) !== 0, they share at least one character. This is O(1) vs O(min(k1,k2)) for set intersection.
Key Insight
Q3: What's the XOR parity trick for substring problems? Represent each property as a bit. XOR toggles the bit (evenโodd, oddโeven). If the prefix state at index i equals the state at index j, the substring (i+1..j) has all properties in even count. This is the core of the vowel parity problem โ only 32 states!
Key Insight
Q4: How does the rolling hash work for DNA sequences? Encode each base in 2 bits (A=00, C=01, G=10, T=11). A 10-char window = 20 bits. Slide by:hash = ((hash << 2) | newChar) & mask. The mask keeps only the lowest 20 bits. No collisions for DNA because 2ยฒโฐ is much larger than the string length.
Key Insight
Q5: How do I handle the sliding window bitmask for binary strings? Initialize with first k chars. Then: mask = ((mask << 1) | bit) & ((1 << k) - 1). The mask drops the leftmost bit and adds the new rightmost bit, keeping exactly k bits.
Key Insight
Q6: What's the difference between 'consistent strings' and 'similar strings'? Consistent checks (allowedMask & wordMask) === wordMask (subset containment). Similar checks mask1 === mask2 (set equality). Both are O(1) with bitmasks!
๐ Key Takeaways
Bitmasks pack character sets into a single integer โ 26 bits for lowercase a-z, 5 bits for vowels, 2 bits per DNA base
OR is idempotent โ building a mask with mask |= (1 << ch) automatically deduplicates, giving you the character set
XOR toggles parity โ state ^= (1 << bit) flips a bit's even/odd count. Same state twice โ substring between has even counts
Subset check:(allowedMask & wordMask) === wordMask โ a single O(1) operation
Set equality:mask1 === mask2 โ group by mask to count similar pairs in O(nยทk)
Overlap check:(mask1 & mask2) === 0 โ no shared characters, safe to concatenate