Leetcode 89: Gray Code

grid47
grid47
Exploring patterns and algorithms
Oct 29, 2024 5 min read

A peaceful, spiraling Gray code sequence glowing softly as it shifts from one value to the next.
Solution to LeetCode 89: Gray Code Problem

Given an integer n, generate an n-bit Gray code sequence. A Gray code sequence is a sequence of integers where each integer’s binary representation differs from the next one by exactly one bit. The first integer in the sequence is always 0, and every integer appears only once in the sequence. The binary representation of the first and last integers should also differ by exactly one bit.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n, representing the number of bits in the Gray code sequence.
Example: Input: n = 3
Constraints:
• 1 <= n <= 16
Output: The output should be a list of integers that represent a valid n-bit Gray code sequence.
Example: Output: [0, 1, 3, 2, 6, 7, 5, 4]
Constraints:
• Each integer in the sequence must be a valid n-bit number.
Goal: The goal is to generate a sequence of integers such that every adjacent pair of integers differs by exactly one bit in their binary representation, and the first and last integers differ by exactly one bit.
Steps:
• Start with the sequence containing only the integer 0.
• Iteratively generate the next integer by flipping a bit in the binary representation of the integers already in the sequence, ensuring that each new integer differs by exactly one bit from the previous one.
Goal: The input value n will always be between 1 and 16, inclusive.
Steps:
• The sequence must contain exactly 2^n integers.
• The binary representation of each integer should be n bits long.
Assumptions:
• The input value n is always within the specified range (1 <= n <= 16).
• The Gray code sequence will be valid for any input within this range.
Input: Input: n = 2
Explanation: For n = 2, a valid Gray code sequence is [0, 1, 3, 2]. The binary representations are: 00, 01, 11, 10. Each adjacent pair of numbers differs by exactly one bit.

Input: Input: n = 3
Explanation: For n = 3, a valid Gray code sequence is [0, 1, 3, 2, 6, 7, 5, 4]. The binary representations are: 000, 001, 011, 010, 110, 111, 101, 100. Each adjacent pair of numbers differs by exactly one bit.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus