1358. Generate Gray Code Sequence

MediumBit ManipulationGray CodeBit ManipulationSequence

The n-bit reflected Gray code lists all integers from 0 to 2^n - 1 so that consecutive entries differ in exactly one bit, and the sequence is cyclic. Given n and a starting position s in that sequence, return the whole sequence read from position s, wrapping around after the last entry. The classic sequence is the case s = 0.

Input: A JSON object {"n": <bit width>, "s": <starting position>} with 0 <= s < 2^n.

Output: Return the 2^n Gray code values beginning at position s.

Examples

Example 1
Input: {"n":3,"s":0}
Output: [0,1,3,2,6,7,5,4]
Explanation: The standard 3-bit Gray code sequence.
Example 2
Input: {"n":2,"s":1}
Output: [1,3,2,0]
Explanation: Starting one step in and wrapping around gives 1, 3, 2, 0.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →