Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Single Number

EasyLeetCode 136 ↗

The problem, in one line. Every value in the list appears twice except one that appears once, so find that one using a single pass and no growing scratch space. LeetCode 136.

The tell. “Everything comes in pairs except one” together with “constant extra space”. Any method that remembers what it has seen is ruled out, so the pairs have to cancel each other instead.

The wrong first idea

Count every value in a dictionary, then return the one with a count of 1.

counts = {}
for x in nums:
    counts[x] = counts.get(x, 0) + 1
return next(x for x, c in counts.items() if c == 1)

It is correct and runs in one pass. But the dictionary grows with the list. If all the left halves of the pairs come first, half the list sits in memory before any pair closes. The statement asks for constant space, and this is linear.

The invariant

This card is the one-page summary of Clinic #32: Single Number. XOR flips a bit only where two numbers disagree, so a number XORed with itself is 0, and a number XORed with 0 is itself. Order does not matter.

4 ^ 9 ^ 4
= 4 ^ 4 ^ 9
= 0 ^ 9
= 9

The sentence that stays true every step: the running value is the XOR of everything seen so far, and every pair already seen has cancelled to 0. At the end only the loner is left.

The solution

def single_number(nums):
    acc = 0
    for x in nums:
        acc ^= x                   # a pair cancels itself
    return acc

print(single_number([4, 9, 4]))
print(single_number([5, 8, 8, 6, 5]))
print(single_number([7]))
9
6
7
func singleNumber(nums []int) int {
	acc := 0
	for _, x := range nums {
		acc ^= x // a pair cancels itself
	}
	return acc
}

Same three calls print 9, 6, 7.

Complexity

  • Time O(n): one XOR per number.
  • Space O(1): one integer, whatever the length of the list.

Traps

  • Starting acc at the first element and then looping over all of them. The first value is XORed in twice and cancels itself, so [4, 9, 4] returns 13 instead of 9.
  • Treating a result of 0 as “nothing found”. The loner can be 0, and [0, 3, 3] correctly returns 0, so never test if acc: to decide whether an answer exists.
  • Assuming the list is sorted and comparing neighbours. [5, 8, 8, 6, 5] is not sorted, and the statement never promises order.

Next in the ladder

Number of 1 Bits stops asking which number is alone and starts asking how many bits are on inside a single number.