#89
Medium Algorithms Gray code
Math Backtracking Bit Manipulation
64.1% acceptance
Jan 12, 2026
2521
2832
An n-bit gray code sequence is a sequence of 2n integers where:
Every integer is in the inclusive range [0, 2n - 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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn gray_code(n: i32) -> Vec<i32> {
let mut result = vec![0];
for i in 0..n {
let size = result.len();
let mask = 1 << i;
for j in (0..size).rev() {
result.push(result[j] | mask);
}
}
result
}
}