XOR to Toggle Boolean Flags

Hard ⏱ 18 min 24% acceptance ★★★★☆ 4.2
Write a function toggle_bits(flags, mask) that returns flags with every bit set in mask flipped (on bits turned off, off bits turned on), using the bitwise XOR operator ^. Also write find_unique(numbers) that, given a list numbers where every value appears exactly twice except for one value that appears exactly once, returns that unique value in O(n) time using XOR (no counting dict).

Examples

Example 1
Input
toggle_bits(0b1010, 0b0110)
Output
12
Explanation

0b1010 ^ 0b0110 = 0b1100 = 12.

Example 2
Input
find_unique([4, 1, 2, 1, 2])
Output
4
Explanation

XOR-ing all values cancels out pairs, leaving 4.

Constraints

  • flags and mask are non-negative integers.
  • numbers has an odd length with exactly one non-paired value.

Topics

Operatorsbitwise XOR

Companies

CiscoIntelSalesforce

Hints

Hint 1

XOR-ing a bit with 1 flips it, XOR-ing with 0 leaves it unchanged — that is exactly what `flags ^ mask` does.

Hint 2

For find_unique, XOR-ing a value with itself yields 0, and XOR is associative/commutative, so XOR-ing the whole list cancels every pair.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.