⌘K
Flycodx

Single Number

Single Number

EasyBit Manipulation100% accepted

Given a non-empty array of integers where every element appears exactly twice except for one element which appears exactly once, find and return that single element. Your solution must have O(n) time complexity and use O(1) extra space — no hash maps or sets. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=5, nums=[4 1 2 1 2] → 4

Input format — only if your code reads from stdin

Input format (stdin): - First line: integer n (array size, always odd) - Second line: n space-separated integers Output: the element that appears exactly once.

Approach

XOR trick: XOR of a number with itself is 0; XOR of any number with 0 is that number. XOR all elements together — pairs cancel out (a^a=0), leaving only the single element. Result = nums[0]^nums[1]^...^nums[n-1].

Input

5 4 1 2 1 2

Output

4
  • •1 ≤ n ≤ 3×10^4, n is always odd, -3×10^4 ≤ nums[i] ≤ 3×10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3