Gray Code
Master this topic with zero to advance depth.
Gray Code
An n-bit gray code sequence is a sequence of integers where:
- Every integer is in the inclusive range ,
- The first integer is 0,
- An integer appears no more than once in the sequence,
- The binary representation of every pair of adjacent integers differs by exactly one bit,
- The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.
Examples
00, 01, 11, 10 is a valid Gray code sequence.
Level I: Brute Force (Backtracking)
Intuition
Generate the sequence by exploring all possible next numbers that differ by exactly one bit. Maintain a visited set to ensure uniqueness.
Thought Process
- Start with 0.
- Try flipping each of the bits.
- If the result is not visited, move to it and recurse.
- If all bits visited, return the sequence.
Pattern: State Space Search
Level II: Reflected Construction (Iterative)
Intuition
Gray code for bits can be built from the Gray code for bits by reflecting the sequence and adding a leading 1 (bit ) to the reflected part.
Level III: Optimal (Bit Manipulation Formula)
Intuition
The -th number in the Gray code sequence can be generated using the formula . This formula ensures that adjacent numbers differ by exactly one bit because shifting and XORing cancels out bits that change in a ripple carry but leaves the most significant changing bit.
Thought Process
- The total number of elements is .
- For each index from 0 to :
- Calculate
i ^ (i >> 1).
- Calculate
- Add to result list and return.
Pattern: Formula-based Generation
Detailed Dry Run
n = 2
- i=0: 0 ^ (0>>1) = 0 ^ 0 = 0 (00)
- i=1: 1 ^ (1>>1) = 1 ^ 0 = 1 (01)
- i=2: 2 ^ (2>>1) = 2 ^ 1 = 3 (11)
- i=3: 3 ^ (3>>1) = 3 ^ 1 = 2 (10) Result: [0, 1, 3, 2]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.