Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1).

Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1).
def gray(n):
    return [i ^ (i >> 1) for i in range(1 << n)]
print(gray(3), [format(x, "03b") for x in gray(3)][5])
What is printed?
  1. A. [0, 1, 3, 2, 6, 7, 5, 4] 101
  2. B. [0, 1, 2, 3, 4, 5, 6, 7] 101
  3. C. [0, 1, 3, 2, 6, 7, 5, 4] 111
  4. D. [0, 2, 3, 1, 5, 7, 6, 4] 111

Correct answer: C. [0, 1, 3, 2, 6, 7, 5, 4] 111

i ^ (i >> 1) keeps the top bit and XORs each lower bit with the bit above it, so incrementing i flips exactly one output bit. i = 5 (101) → 101 ^ 010 = 111 (7). The sequence 000, 001, 011, 010, 110, 111, 101, 100 is the reflected Gray code. O(2ⁿ).

More Coding Interview Problems questions

Exams that ask this topic