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?- A. [0, 1, 3, 2, 6, 7, 5, 4] 101
- B. [0, 1, 2, 3, 4, 5, 6, 7] 101
- C. [0, 1, 3, 2, 6, 7, 5, 4] 111
- 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
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…
- Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a…
- Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking). python def palparts(s): res =…
- Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing…