Ctrl K

XOR Top-Up While Trimming

Medium
You are given an array of non-negative integers values and a number bits; every element is below 2^bits. Repeat len(values) times: 1. Pick the number k, 0 ≤ k < 2^bits, that makes the XOR of all current elements together with k as large as possible, and record it. 2. Remove the last element of the array. Return the recorded numbers in the order you got them.
Example 1
values=[5, 1, 6], bits=3 → [5, 3, 2]

5 XOR 1 XOR 6 = 2, and topping it up to 7 takes 5. Drop the 6: 5 XOR 1 = 4, which needs 3. Drop the 1: 5 is left, which needs 2. The answer is [5, 3, 2].

Example 2
values=[3, 3], bits=2 → [3, 0]

At first the XOR is 0, so k = 3. After one removal it is 3, so nothing has to be added: k = 0.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ bits ≤ 20
  • 0 ≤ values[i] < 2^bits
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPalindrome After a Few Fixes MediumRange XOR Lookups MediumSplit Into Equal-XOR Halves MediumK-th Largest Corner XOR MediumProducts of Binary Pieces Medium
loading Python…
Input
values=[5, 1, 6], bits=3
Expected
[5, 3, 2]

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.