#89

Gray Code

Medium
MathBacktrackingBit ManipulationBit ManipulationMathematical Sequences
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a mathematical property of Gray codes. Each Gray code can be generated directly using the formula: G(i) = i ^ (i >> 1). This allows us to generate the sequence in linear time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty list to store the Gray code sequence.
  2. 2Step 2: Loop from 0 to 2^n - 1 and apply the formula G(i) = i ^ (i >> 1) to generate each Gray code.
  3. 3Step 3: Append each generated Gray code to the result list.
solution.py6 lines
1# Full working Python code
2
3def grayCode(n):
4    return [i ^ (i >> 1) for i in range(2 ** n)]
5
6print(grayCode(2))

Complexity note: The time complexity is O(n) because we generate 2^n Gray codes directly using a simple formula, and the space complexity is O(n) for storing the results.

  • 1Gray code sequences differ by one bit between adjacent numbers.
  • 2The optimal formula allows for efficient generation without checking pairs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.