1536. Bit Reversal Order

Easy1.5 points estimatedBit ManipulationArray

Fast transform routines often reorder an array of length 2^k so that the element at index i moves to the index obtained by reversing the k low bits of i. For example, with k = 2 the indices 0, 1, 2, 3 are 00, 01, 10, 11 in binary, whose reversals are 00, 10, 01, 11, i.e. 0, 2, 1, 3.

Given k, return an array of length 2^k whose i-th entry is the value of i with its k low bits reversed. When k is 0 the array is just [0]. Entries are always between 0 and 2^k - 1, so a reversed index never leaves the range.

Input: one integer k. Output: an integer array of length 2^k, in index order. Build it in O(2^k) time using the recurrence rev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (k - 1)), with O(2^k) space for the output.

Example 1

Input:
k = 2
Output:
[0,2,1,3]
Explanation:

00, 01, 10, 11 reverse to 00, 10, 01, 11.

Example 2

Input:
k = 3
Output:
[0,4,2,6,1,5,3,7]
Explanation:

For k = 3, index 1 (001) becomes 100 = 4 and index 3 (011) becomes 110 = 6.

Constraints

0 ≤ k ≤ 8 (the output has at most 256 numbers)

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^k)
Space
O(2^k)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…