Find the number that appears once when every other number appears twice

Quick Overview

Given an integer array where every value appears twice except one, find the value that appears only once in linear time with constant extra space. It tests bit manipulation and whether you can meet a tight space limit without a hash set or sorting.

Find the number that appears once when every other number appears twice

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one. You must implement a solution with linear runtime complexity that uses only constant extra space. ### Function Signature ```python def single_number(nums: list[int]) -> int: ``` ### Constraints - `1 <= len(nums) <= 3 * 10^4` - `-3 * 10^4 <= nums[i] <= 3 * 10^4` - Each element in the array appears twice except for one element, which appears only once. ### Examples #### Example 1 ```text Input: nums = [2,2,1] Output: 1 ``` The value 1 appears only once, while 2 appears twice. #### Example 2 ```text Input: nums = [4,1,2,1,2] Output: 4 ``` The value 4 appears only once, while 1 and 2 each appear twice. #### Example 3 ```text Input: nums = [-1,5,5] Output: -1 ``` Negative values follow the same rule: 5 appears twice and -1 appears once.

Overview: Given an integer array where every value appears twice except one, find the value that appears only once in linear time with constant extra space. It tests bit manipulation and whether you can meet a tight space limit without a hash set or sorting.

Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with linear runtime complexity that uses only constant extra space.

Function Signature

def single_number(nums: list[int]) -> int:

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Each element in the array appears twice except for one element, which appears only once.

Examples

Example 1

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

The value 1 appears only once, while 2 appears twice.

Example 2

Input: nums = [4,1,2,1,2]
Output: 4

The value 4 appears only once, while 1 and 2 each appear twice.

Example 3

Input: nums = [-1,5,5]
Output: -1

Negative values follow the same rule: 5 appears twice and -1 appears once.