DrawCode Algorithm Visualizer • Bit Manipulation • Medium

Gray Code

Tags: Bit, Gray Code, Hamming, Encoding

1. One-Liner

Gray code orders binary numbers so successive values differ in exactly one bit—reflection construction g = i ^ (i>>1).


2. The Problem It Solves

Used in rotary encoders, Karnaugh maps, error reduction in switching, and minimizing glitches.


3. The Core Idea

Binary to Gray XORs with half-shifted copy—each step flips the bit where binary carry propagates.


4. How It Works (Step-by-Step)

StepAction
1For i in 0..2^n-1
2g = i ^ (i >> 1)
3Collect sequence

5. Dry Run Example

n=2: 00,01,11,10—each hop toggles one bit.


6. Key Properties

PropertyDetail
Hamming distance1 between neighbors
CyclicWrap may differ requirement
InverseBinary Gray decoding exists

7. Where It Is Used

Domain / SystemUse
HardwareEncoders
DigitalK-maps
AlgorithmsHamiltonian on hypercube

8. Interview Tips

Know n-bit reflected construction recursively; streaming parity relations optional depth.


9. Comparison with Other Algorithms

TechniqueNotes
Binary countingMany bit changes
Johnson counterHardware alternative
De BruijnDifferent sequence

10. Complexity

----
TimeO(2^n) to list all
SpaceO(2^n) output

Implementation Example (PYTHON)

def gray_code(n):
    return [i ^ (i >> 1) for i in range(1 << n)]

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer