Google | Phone Screen | Single Element
10845

Given an array nums of length n. All elements appear in pairs except one of them. Find this single element that appears alone.
Pairs of the same element cannot be adjacent:

[2, 2, 1, 2, 2] // ok
[2, 2, 2, 2, 1] // not allowed

Example 1:

Input: [2, 2, 1, 1, 9, 9, 5, 2, 2]
Output: 5

Example 2:

Input: [1, 1, 2]
Output: 2

Example 3:

Input: [3, 3, 2, 3, 3]
Output: 2
Follow-up

Can you do better than O(n)?

My solution

Java binary search: https://leetcode.com/playground/PeyK4kLt
Time complexity: O(logn).
Space complexity: O(1).

Comments (43)