#140 · Bit manipulation · Advanced · 130 XP · about 25 min
A secret list perm holds the numbers 1, 2, ..., n in some order, each exactly once, and n is odd. Instead of the list itself you were given encoded, where encoded[i] is perm[i] ^ perm[i + 1], the bitwise XOR of two neighbours. So encoded has n - 1 numbers.
Write decode_permutation(encoded) that returns the secret list perm. There is always exactly one answer.
decode_permutation([3, 1]) # returns [1, 2, 3] decode_permutation([6, 5, 4, 6]) # returns [2, 4, 1, 5, 3] decode_permutation([6, 2, 3, 6]) # returns [5, 3, 1, 2, 4]
In the first example, 1 ^ 2 = 3 and 2 ^ 3 = 1, which is exactly encoded.
encoded always comes from a real arrangement of 1 to nReady?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.