Given two integers and start, you need to return a permutation of numbers from 0 to such that:
start.Walmart Labs and other companies use this to test your knowledge of Bit Manipulation and Gray Codes. It evaluations your ability to identify that a circular bit-alternating sequence is a property of the Gray Code system and whether you can transform a standard sequence to start at a given value while maintaining its properties.
The pattern is Gray Code generation combined with Bitwise XOR. The standard -bit Gray Code sequence for is i ^ (i >> 1). To make the sequence start at start while keeping the "one-bit difference" property, you can XOR every element in the standard Gray Code sequence with start. Since A ^ B and (A+1) ^ B still differ by only one bit if A and A+1 differed by one bit in Gray space, the property is preserved.
, start = 3 (11 in binary)
[0, 1, 3, 2] (00, 01, 11, 10)[3, 2, 0, 1]. Each adjacent pair differs by one bit.A common error is trying to use backtracking to find the permutation. While it works for very small , it is and will fail for . Another mistake is trying to "rotate" the Gray Code sequence instead of using the XOR property, which is more complex to implement.
Gray Code is a specific binary numeral system where two successive values differ in only one bit. The formula G(i) = i ^ (i / 2) is one of the most useful bitwise tricks to have in your pocket.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Gray Code | Medium | Solve | |
| XOR Operation in an Array | Easy | Solve | |
| Divide Two Integers | Medium | Solve | |
| Find the Punishment Number of an Integer | Medium | Solve | |
| Sum of Two Integers | Medium | Solve |