SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Single Number

Description: In array nums every element appears twice except for one which appears once. Find that element.

Example 1:

Input: nums = [2,2,1]
Output: 1
Explanation: Two appears twice, one appears once

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4
Explanation: Only four has no pair

Constraints:

1 <= nums.length <= 3·10⁴

Каждый элемент кроме одного встречается ровно дважды

Recommended time and space complexity

Aim for O(n) time and **O(1) space** — no extra data structures.


Hint 1

A hash table works but needs O(n) space. The constraint asks for O(1).


Hint 2

Recall XOR properties: x ^ x = 0 and x ^ 0 = x.


Hint 3

XOR is commutative, so order does not matter. Pairs cancel out.

A bit manipulation problem. Teaches using XOR properties to solve in O(1) space where the obvious solution needs a hash table.

Expected Input :

[2,2,1]

Expected Output

1