Last Car in the Garage

Easybit manipulationAlso known as Single Number

A small parking garage logs a car's ticket number twice, once when the car drives in and once when it drives out. The log is one long list in no useful order.

At closing time exactly one car is still inside, so exactly one ticket appears only once. The gate computer 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 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

Cars 512 and 87 both came in and went out, so each appears twice. Ticket 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 are neighbours, but the two 9s are not, so you cannot assume that matching tickets sit together. The ticket that appears once 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

Counting tickets in a hash map takes O(n) time but stores up to n / 2 numbers, which the gate computer cannot afford. Checking each ticket against every other one uses no extra memory but costs O(n²), which is about 900 million comparisons for 30,001 entries.

Sorting the log and then comparing neighbours in steps of two uses little memory, but it 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