All topics
133

The one item that lost its pair

Tier 2Locked

Where it runs

1. The problem

A warehouse scans every item twice: once on the way in, once on the way out. By evening the log holds every ID twice, except for one item that went missing: its ID appears only once. You need that single ID out of a million scans.

The safe answer is a map of counts: count every ID, then find the one with count 1. It works. But it needs O(n) memory to hold a million counts, just to find one number.

A few bit tricks do the same job in one line and O(1) memory. This lesson is about those tricks.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

Recognise it

Bit manipulation

Say these words and it is this pattern

  • find the single or unique number using XOR
  • set, clear, toggle, or test a bit
  • pack many yes/no flags into one integer
  • count set bits or check a power of two

Looks similar, isn't

One operation is O(1) on a 32-bit value. Looping the bits is O(32), which counts as constant.

On LeetCode

Problems where one number is missing or left without a pair, and quick tests on the lowest bit. XOR cancels equal numbers, x & (x-1) clears the lowest 1 bit, and x & -x keeps only that bit.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy