← DiffPush

Find element present only once

Baseline Arrays · Easy O(n) · O(1)

The Singleton Tenant in the Door Log

A building turnstile logs every entry and exit, so each badge id appears an even number of times except one badge whose second swipe was lost by the controller. The security team needs that unpaired badge. The answer must be produced in a single pass over the log using no extra storage.

Input: An array nums of n integers where every value appears exactly twice except one value that appears once.

Output: The value that appears exactly once.

Constraints

Examples

Example 1

Input: {"nums":[2,2,1]}
Output: 1
The pair 2,2 cancels out and the leftover badge is 1.

Example 2

Input: {"nums":[4,1,2,1,2]}
Output: 4
Both pairs are matched regardless of position, leaving 4 unpaired.

Solve this in your browser →

Also on LeetCode ↗