Thanks to visit codestin.com
Credit goes to leetcode-py.wisl.dev

Skip to main content
LeetCode 89, Medium. Topics: Math, Backtracking, Bit Manipulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

Problem

An n-bit gray code sequence is a sequence of 2^n integers where:
  • Every integer is in the inclusive range [0, 2^n - 1],
  • 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, and
  • 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

Constraints

  • 1 <= n <= 16

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026