Bit Manipulation
bit-manipulation
Data Structures
Fenwick Tree (BIT)
A complete Fenwick Tree implementation fits in fifteen lines of code, half the memory of a segment tree, and a smaller constant factor on every operation. The price of admission is that you only get prefix-style aggregates, but for the enormous class of problems that need exactly that, a **Fenwick Tree** (also called a Binary Indexed Tree, or BIT) is the right answer. This lesson covers the dynamic prefix-sum problem (static prefix sums are `O(1)` query and `O(n)` update; you want both in `O(log n)`), the `i & -i` lowbit trick that isolates the lowest set bit and implicitly defines which range each index covers, point update and prefix query in `O(log n)`, and the `prefix(R) - prefix(L-1)` identity that turns those into general range queries. You will also meet the difference-array technique that swaps the roles, supporting `O(log n)` range updates with `O(log n)` point queries. In **Arrays & Strings**, you saw how a flat array can encode rich structure when the indexing scheme is clever; the Fenwick tree pushes that idea further by letting binary representation itself carry the partition information. **Segment Tree** solved a more general version of this problem with explicit nodes; the BIT trades flexibility for simplicity and memory and wins on both metrics whenever prefix queries suffice. Next, **Sparse Table** addresses a different point in the trade space: arbitrary range minimum (and similar idempotent) queries, with `O(1)` queries when no updates are involved.
Not Started
0%
Van Emde Boas Tree
For a set of 32-bit integers, balanced BSTs answer successor and predecessor queries in `log_2(2^32) = 32` comparisons, and hash tables cannot answer those queries at all. A **Van Emde Boas (vEB) tree** answers them in `log_2(log_2(2^32)) = 5`, by recursively halving the bit-length of the universe at each level rather than halving the number of elements. That doubly-logarithmic bound is one of the most striking results in data structure theory. This lesson covers the recursive vEB structure (an integer universe `[0, u-1]` is split into `sqrt(u)` clusters of size `sqrt(u)` plus a summary structure over which clusters are non-empty, applied recursively), the explicit `min` and `max` fields that short-circuit the recursion to a single level when possible, the `O(log log u)` analysis for insert, delete, member, successor, predecessor, min, and max, and the `O(u)` space cost that makes vEB trees practical only for moderate universes. In **Binary Search Tree (BST)**, the height (and thus the operation cost) was governed by the number of stored keys; the vEB tree is governed instead by the size of the integer universe, a fundamentally different parameter. **Heaps & Priority Queue** introduced fast min and max access through a structural invariant; vEB trees push that idea further by also providing fast `successor` and `predecessor` over the same set. With Van Emde Boas, the data structures track is complete; the algorithms track is where these structures come alive in real problem solving.
Not Started
0%
Algorithms
Advanced Bit Manipulation
Iterating over all subsets of every subset of an `n`-element set sounds like `4^n` work. The actual cost is `3^n`: each element is in three states (in the outer mask only, in both, or in neither), and the binomial theorem collapses the sum. Insights like that turn what looks like a complexity wall into a tight, elegant solution. **Advanced Bit Manipulation** collects those insights. You will generate Gray codes (adjacent values differ by one bit, used in error correction), enumerate all subsets of a bitmask via the `for (s = mask; s > 0; s = (s - 1) & mask)` template, and master bit tricks like isolating the lowest set bit with `x & -x`, turning it off with `x & (x - 1)`, counting trailing zeros, and swapping without a temp variable. The lesson also covers advanced XOR applications (range XOR, two missing numbers, XOR basis over GF(2)) and bitwise DP including profile DP for grid tiling. In **Bit Manipulation (Intro)**, you mastered the basic operators and the single-number XOR trick. This lesson treats bits as a full algorithmic medium. Next, **Complexity & Proof Intuition (Optional)** revisits the theoretical foundations behind everything built so far.
Not Started
0%
Bit Manipulation (Intro)
Given an array where every element appears twice except one, find the loner. The hash-map solution is `O(n)` time and `O(n)` space. XOR-ing every element together solves it in `O(n)` time and `O(1)` space, in three lines, exploiting the fact that `a ^ a = 0` and `a ^ 0 = a`. Knowing how integers are laid out as bits unlocks solutions like that across an entire family of problems. **Bit Manipulation (Intro)** covers the building blocks. You will master the six bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) and the standard tricks: check whether `n` is a power of two with `n & (n - 1) == 0`, count set bits, get/set/clear/toggle the ith bit, and the XOR "single number" pattern. The lesson then introduces bitmasks as compact set representations and previews how subset enumeration powers later bitmask DP and TSP algorithms. In **How to Read Code (JS & Python)**, you saw integers and arithmetic. This lesson zooms in past arithmetic: the same integer is also a fixed-width string of bits you can address one at a time. Next, **Divide and Conquer (Intro)** returns to recursion with the recurrence framework that explains merge and quick sort.
Not Started
0%
Practice Problems
Add Binary
Given two binary strings, return their sum as a binary string.
Counting Bits
Given an integer n, return an array of length n + 1 where each element ans[i] is the number of 1s in the binary representation of i.
Missing Number
Given an array of n distinct numbers from the range [0, n], find the one number that is missing from the array.
Number of 1 Bits
Given a positive integer, return the number of set bits (1s) in its binary representation, also known as the Hamming weight.
Reverse Bits
Reverse all 32 bits of a given unsigned integer and return the result as an unsigned integer.
Single Number
Given a non-empty array of integers where every element appears twice except for one, find that single element using constant extra space.
Bitwise AND of Numbers Range
Given two integers left and right representing a range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Reverse Integer
Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows the 32-bit signed integer range, return 0.
Single Number II
Given an integer array where every element appears exactly three times except for one element which appears exactly once, find the single element. The solution must use linear time and constant extra space.
Sum of Two Integers
Calculate the sum of two integers a and b without using the operators + or -. Use bitwise operations to simulate addition.
Community
Hamming Distance
Count the bit positions where two non-negative integers differ using XOR plus a population-count loop.
Power of Two
Determine whether a 32-bit signed integer is a power of two using a single bit-AND trick.
Maximum XOR of Two Numbers in an Array
Find the maximum bitwise XOR of any two elements in an integer array using a bit-trie that's queried greedily from the most significant bit down.
Power of Three
Decide whether a 32-bit signed integer is a power of three using a divisibility shortcut against the largest 32-bit power of three.
Bit Manipulation Tricks I Keep Forgetting
A working programmer's cheat sheet of bitwise operations: the moves I look up every six months, what each one does, real production uses, and the ones that look clever but I avoid.
Bitmask DP: The Trick for Subset Problems
Encoding subsets as integers, iterating subsets in O(2^n), and the TSP example that demonstrates the 2^n * n^2 state space. When n is at most 20, bitmask DP is a cheat code.
