progress

~/problems / Bit manipulation

Missing Number

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A raffle printed tickets 0, 1, ..., n. One was lost, and the other n were collected in no particular order.

Write lost_ticket(tickets: list[int]) -> int: the number on the lost ticket.

lost_ticket([4, 0, 1, 3])   # 2
lost_ticket([1])            # 0
lost_ticket([0, 1, 2])      # 3   (the last ticket can be the lost one)

Up to 2 * 10^5 distinct tickets, each in [0, n].

⭐ Bonus: a speed test with 200,000 tickets earns a star in O(n) time. For the real trick, use O(1) extra space too: no set, boolean array or sorted copy.

Show hint

picture a complete list 0..n next to yours: every ticket that isn't lost appears twice across the two. How can pairs vanish?

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc