Hone logo
Hone
Problems

Generating Gray Codes

Gray codes are a sequence of binary numbers where each successive value differs in only one bit position. This property makes them incredibly useful in digital systems, error correction, and position encoding. Your task is to generate the Gray code sequence for a given number of bits.

Problem Description

You need to implement a function that takes an integer n as input, representing the number of bits, and returns a list of all possible Gray codes for n bits. The Gray code sequence should start with 0 (represented as n zeros). The generated sequence should follow the standard binary-reflected Gray code pattern.

Key Requirements:

  • The output should be a list of strings, where each string is a binary representation of a Gray code.
  • The length of each binary string should be n.
  • The sequence must be ordered according to the binary-reflected Gray code generation method.
  • The first element of the sequence must be the all-zeros string of length n.

Expected Behavior: For a given n, the function should produce a list containing 2^n Gray code strings.

Edge Cases:

  • n = 0: An empty list or a list containing a single empty string might be considered, depending on interpretation. For this challenge, assume n >= 1.

Examples

Example 1:

Input: n = 1
Output: ["0", "1"]
Explanation: For n=1, the Gray codes are 0 and 1.

Example 2:

Input: n = 2
Output: ["00", "01", "11", "10"]
Explanation: The sequence for n=2 is generated by reflecting the n=1 sequence and prefixing with '0' and '1' respectively:
Reflected n=1 sequence: ["1", "0"]
Prefix with '0': ["00", "01"]
Prefix with '1': ["11", "10"] (reversed)
Combined: ["00", "01", "11", "10"]

Example 3:

Input: n = 3
Output: ["000", "001", "011", "010", "110", "111", "101", "100"]
Explanation: Following the recursive pattern:
n=1: ["0", "1"]
n=2: ["00", "01", "11", "10"]
n=3:
  Prefix n=2 with '0': ["000", "001", "011", "010"]
  Prefix reflected n=2 with '1': ["110", "111", "101", "100"]
  Combined: ["000", "001", "011", "010", "110", "111", "101", "100"]

Constraints

  • 1 <= n <= 16
  • The input n will be an integer.
  • The output should be a list of strings.
  • The size of the output list will be 2^n.

Notes

The binary-reflected Gray code can be generated recursively. To generate the Gray code for n bits, you can take the Gray code for n-1 bits, prefix each element with '0', and then take the Gray code for n-1 bits in reverse order and prefix each element with '1'. This forms the complete Gray code sequence for n bits.

Consider how you will convert the generated binary representations to strings of the correct length, especially for the leading zeros.

Loading editor...
plaintext