Last Car in the Garage

Easybit manipulationAlso known as Single Number

A small parking garage logs a ticket number at the gate twice for every car: once when it drives in and once when it drives out. The log is one long list of ticket numbers, in no useful order, because cars come and go all day.

At closing time exactly one car is still inside, so exactly one ticket number shows up only once. The attendant wants that number, and the gate computer is tiny: it can read the log once but has almost no spare memory.

Your task

Write carStillInside(log). Every ticket number in log appears exactly twice, except one that appears exactly once. Return that number.

Aim for one pass over the log and O(1) extra memory: no map, no set, no sorted copy.

carStillInside(log: int[]) → int

Examples

Example 1
Input
log = [512, 87, 340, 87, 512]
Output
340
Why

512 came in and went out. So did 87. 340 appears only once, so that car is still inside.

Example 2
Input
log = [9, 4, 4, 2, 9]
Output
2
Why

The two 4s sit next to each other, but the two 9s and the lone 2 do not. Do not assume partners are neighbours. The answer is 2.

Constraints

  • 1 ≤ log.length ≤ 30,001, and log.length is odd
  • 0 ≤ log[i] ≤ 1,000,000,000
  • Exactly one number appears once. Every other number appears exactly twice.
Start with brute force

Count every ticket in a hash map and return the one with count 1. That is O(n) time, but it stores up to n / 2 numbers, which the gate computer cannot afford. Checking each ticket against every other one uses no memory but costs O(n²): with 30,001 entries that is about 900 million comparisons.

Sorting and then comparing neighbours in steps of two works with little memory, but it still costs O(n log n) and needs a sortable copy or permission to reorder the log.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code