Gray Code

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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
  • The binary representation of the first and last integers also differ by exactly one bit

Given an integer n, return any valid n-bit gray code sequence.

Examples

Example 1:

Input: n = 2

Output: [0,1,3,2]

Explanation:

  • 00 - 0
  • 01 - 1
  • 11 - 3
  • 10 - 2

Example 2:

Input: n = 1

Output: [0,1]

Constraints

  • 1 <= n <= 16
Source: Bitwise Manipulation pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle