code golf
gray code
programming challenge
algorithm optimization
competitive coding

Code Golf Gray Code

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Gray code is a natural code-golf target because the core formula is tiny but the output pattern is nontrivial. The key fact is that the Gray-code value for integer n is n ^ (n >> 1), which gives you a very short way to generate the sequence.

What Gray Code Is

A Gray-code sequence is an ordering of binary values where adjacent entries differ by exactly one bit. For three bits, a standard sequence is:

  • '000'
  • '001'
  • '011'
  • '010'
  • '110'
  • '111'
  • '101'
  • '100'

That one-bit-change property is what makes the sequence interesting both mathematically and for golf-style code generation.

The Tiny Formula

For any non-negative integer n, the Gray-code value is:

python
g = n ^ (n >> 1)

That formula is the reason code golfers like this problem. You do not need recursion, explicit bit-flipping logic, or a precomputed table.

A Straightforward Python Version

python
1def gray_sequence(bits):
2    return [i ^ (i >> 1) for i in range(1 << bits)]
3
4
5print(gray_sequence(3))

Output:

text
[0, 1, 3, 2, 6, 7, 5, 4]

If you want binary strings:

python
1def gray_strings(bits):
2    return [format(i ^ (i >> 1), f"0{bits}b") for i in range(1 << bits)]
3
4
5print(gray_strings(3))

Why This Works

Right-shifting n lines up each bit with the bit to its left. XOR then marks where adjacent binary bits differ. That transformation produces the standard binary-reflected Gray code directly.

The formula is compact, but it is not a trick. It is the actual mathematical relationship between binary integers and their Gray-code representation.

Why It Shows Up in Code Golf

Gray-code challenges are popular because they reward:

  • using bitwise operators directly
  • avoiding loops in languages with vectorized operators
  • printing formatted output compactly
  • exploiting built-in binary conversion functions

In golf terms, the problem has a short kernel and lots of language-specific opportunities to shrink syntax.

That balance is ideal for golfing: the underlying algorithm is elegant enough to fit in very few bytes, but there is still room for creativity in formatting, looping, and language-specific bitwise shortcuts.

It is also a nice example of a challenge where the shortest solution can still be built from the standard mathematical definition rather than from obscure special cases.

Beyond Golf: Decoding Too

Encoding is short. Decoding is less obvious because you must fold bits back cumulatively. That difference is another reason the encoding challenge is common in golfing communities: the forward direction is unusually elegant.

A simple decoder in Python looks like this:

python
1def gray_to_binary(g):
2    n = g
3    while g:
4        g >>= 1
5        n ^= g
6    return n
7
8
9print(gray_to_binary(3))

Common Pitfalls

  • Forgetting that the formula gives numeric Gray-code values, not padded binary strings.
  • Mixing up Gray-code generation with Gray-code decoding.
  • Assuming any one-bit-change ordering is the same as the standard reflected sequence.
  • Formatting output in a way that costs extra bytes in a golf setting.
  • Overengineering the solution instead of using n ^ (n >> 1).

Summary

  • Gray code maps cleanly from binary integers with n ^ (n >> 1).
  • That tiny formula is why Gray code is a classic code-golf task.
  • The sequence changes only one bit at a time between adjacent values.
  • Python can generate either numeric or binary-string output very compactly.
  • For golf problems, the main challenge is minimizing syntax, not inventing a new algorithm.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.