Gray Code
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
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
Input: n = 2
Output: [0,1,3,2]
00, 01, 11, 10 is a valid Gray code sequence.
Approach 1
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
⏱ O(2^n) - We generate $2^n$ numbers exactly once.💾 O(2^n) - To store the result and visited set.
Approach 2
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.
⏱ $O(2^N)$💾 $O(1)$ (excluding output)
Approach 3
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
⏱ O(2^n) - Constant time per element.💾 O(1) - Excluding the output storage.
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]
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.