Single Number
Given a non-empty array nums in which every element appears exactly twice except for one element that appears once, find and return the single element. Solve it with linear time and constant extra space.
Open official problem prompt ↗Identify the one value that lacks a partner, using no extra data structure and a single pass.
Pairing up socks by tossing each matching pair into the trash; whatever sock remains at the end is the odd one out.
- Input
- nums = [4, 1, 2, 1, 2]
- Output
- 4
- Why
- 1 and 2 each appear twice and cancel out; 4 is the only unpaired value.
1 <= nums.length <= 3 * 10^4-3 * 10^4 <= nums[i] <= 3 * 10^4Each element appears twice except one which appears onceMust run in O(n) time and O(1) extra space