KatInterview

89. Gray Code

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate an n-bit Gray code sequence. A Gray code sequence is a list of 2^n integers with specific properties:

Solution

Gray Code in Python

class Solution:
    def grayCode(self, n: int) -> List[int]:
        # The total number of gray codes for n bits is 2^n.
        # This can be calculated using the left bit shift operator: 1 << n.
        
        # We can generate the sequence using a list comprehension for conciseness.
        # For each integer i from 0 to 2^n - 1, we calculate its Gray code.
        # The formula for the i-th Gray code is i XOR (i shifted right by 1).
        return [i ^ (i >> 1) for i in range(1 << n)]

Gray Code in Java

class Solution {
    public List<Integer> grayCode(int n) {
        // The total number of gray codes for n bits is 2^n.
        int count = 1 << n;
        // Use an ArrayList to store the results, pre-allocating capacity is a good practice.
        List<Integer> result = new ArrayList<>(count);
        
        // Iterate from 0 to 2^n - 1.
        for (int i = 0; i < count; i++) {
            // The i-th Gray code is given by the formula i ^ (i >> 1).
            // This is a standard formula to convert a binary number to its Gray code equivalent.
            result.add(i ^ (i >> 1));
        }
        
        return result;
    }
}

Gray Code in C++

class Solution {
public:
    vector<int> grayCode(int n) {
        // The total number of gray codes for n bits is 2^n.
        int count = 1 << n;
        vector<int> result;
        // Reserve space to avoid reallocations, which is a performance optimization.
        result.reserve(count);
        
        // Iterate from 0 to 2^n - 1.
        for (int i = 0; i < count; ++i) {
            // The i-th Gray code is given by the formula i ^ (i >> 1).
            // This is a standard formula to convert a binary number to its Gray code equivalent.
            result.push_back(i ^ (i >> 1));
        }
        
        return result;
    }
};

Gray Code in TypeScript

function grayCode(n: number): number[] {
    // The total number of gray codes for n bits is 2^n.
    const count = 1 << n;
    const result: number[] = [];
    
    // Iterate from 0 to 2^n - 1.
    for (let i = 0; i < count; i++) {
        // The i-th Gray code is given by the formula i ^ (i >> 1).
        // This is a standard formula to convert a binary number to its Gray code equivalent.
        result.push(i ^ (i >> 1));
    }
    
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.