![]() |
VOOZH | about |
Given a number n, generate bit patterns from 0 to 2^(n-1) such that successive patterns differ by one bit.
Examples:
Input: n = 2
Output: 00 01 11 10
Explanation: We begin with all 0s, and then add the smallest next number that has only one bit difference, we keep adding this way to generate the full sequence.
Input: n = 3
Output: 000 001 011 010 110 111 101 100
Table of Content
The idea is based on the fact that n bit Gray codes can be generated using (n-1) bit Gray codes. We start with the 1 bit Gray code, which is {0, 1}.
How to generate n bit Gray code from (n-1) Gray codes?
Why does this work?
000 001 011 010 110 111 101 100
Time Complexity: O(n*(2^n))
Auxiliary Space: O(1), while the overall space complexity is O(n*(2^n)) to store the resulting Gray code sequence.
We directly generate the i'th Gray Code using the formula Gray(i) = i XOR (i >> 1), we iterate from 0 to 2^(n - 1), apply this formula for each value, convert the result into an n-bit binary string, store it, and finally print the sequence.
Why does this formula work?
If we take a closer look at the formula,
0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000
Time Complexity: O(n*(2^n))
Auxiliary Space: O(n), while the overall space complexity is O(n*(2^n)) to store the resulting Gray code sequence.