Advertisement

Gray Code - LeetCode 89 Solution

Gray Code - Complete Solution Guide

Gray Code is LeetCode problem 89, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 . Example 1: Input: n = 2 Output: [0,1,3,2] Explanation: T

Detailed Explanation

The problem asks us to generate an n-bit Gray code sequence. A Gray code is a sequence of 2^n integers where each number is between 0 and 2^n - 1, the first number is 0, each number appears only once, and adjacent numbers differ by exactly one bit in their binary representation. Also, the first and last numbers must differ by only one bit. We need to return *any* valid Gray code sequence.

Solution Approach

The solution leverages the direct formula G(i) = i ^ (i >> 1) to generate the Gray code sequence. It iterates through all numbers from 0 to 2^n - 1, applying the formula to each number to compute its corresponding Gray code value. These values are then added to a list, which is returned as the result. The approach is efficient as it directly computes the Gray code without recursion or backtracking.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty list/vector called `result` to store the Gray code sequence.
  2. Step 2: Iterate through numbers from `i = 0` to `2^n - 1`. We can efficiently calculate `2^n` using `1 << n`.
  3. Step 3: Inside the loop, calculate the Gray code value for the current number `i` using the formula `i ^ (i >> 1)`. `i >> 1` shifts the bits of `i` one position to the right.
  4. Step 4: Add the calculated Gray code value to the `result` list.
  5. Step 5: After the loop completes, return the `result` list containing the Gray code sequence.

Key Insights

  • Insight 1: The core insight is recognizing the formula for generating a Gray code sequence: G(i) = i ^ (i >> 1), where ^ is the bitwise XOR operator and >> is the right bit shift operator. This formula directly produces the Gray code for a given index i.
  • Insight 2: No explicit backtracking or recursion is needed, simplifying the solution. The iterative approach using the formula is the most efficient way to solve this.
  • Insight 3: Understanding bitwise operations is crucial. XOR and right bit shift are fundamental to the Gray code generation.

Complexity Analysis

Time Complexity: O(2^n)

Space Complexity: O(2^n)

Topics

This problem involves: Math, Backtracking, Bit Manipulation.

Companies

Asked at: Amazon, Bloomberg, Google.