NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 1. Two SumEasy
  • 14. Longest Common PrefixEasy
  • 26. Remove Duplicates from Sorted ArrayEasy
  • 27. Remove ElementEasy
  • 49. Group AnagramsMedium

136. Single Number

Easy
ArrayBit Manipulation
Answered: May 2, 2026
View on LeetCode

Problem Description

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 a linear runtime complexity and use only constant extra space.

Examples

Example 1

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

Example 2

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

Example 3

Input: nums = [1]
Output: 1

Constraints

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

💡 Hints (1)


Solutions

Complexity Analysis

Time Complexity:O(n2)

We have a nested loop: for each of the nnn elements, we scan up to nnn others, giving O(n2)O(n^{2})O(n2) total comparisons.

Space Complexity:O(1)

Only a constant number of variables (found, i, j) are used regardless of input size.

This brute-force approach checks each element to see whether any other element in the array shares its value. For each index i, we scan all other indices j; if no match is found, that element has no duplicate and must be the single number. While correct, this requires comparing every element against every other, which is inefficient for large inputs.

Complexity Analysis

Time Complexity:O(n)

Building the set and computing both sums each require a single pass over the input, so the overall time is O(n)O(n)O(n).

Space Complexity:O(n)

The set stores up to ⌊n/2⌋+1\lfloor n/2 \rfloor + 1⌊n/2⌋+1 unique elements, which is O(n)O(n)O(n) in the worst case.

This approach exploits a mathematical identity: if every number appeared exactly twice, the sum of the array would equal twice the sum of its unique values. Since one number appears only once, computing 2 * sum(unique_values) - sum(all_values) cancels out all pairs and isolates the single number. We build a set to deduplicate, then compute both sums in a single linear pass each.

Complexity Analysis

Time Complexity:O(n)

We make a single pass through the array, and each set add/remove/has operation is O(1)O(1)O(1) on average, giving O(n)O(n)O(n) total.

Space Complexity:O(n)

The set holds at most ⌊n/2⌋+1\lfloor n/2 \rfloor + 1⌊n/2⌋+1 elements simultaneously, so space is O(n)O(n)O(n).

This approach uses a set as a toggle: the first time we encounter a number we add it to seen, and the second time we remove it. Since every number except one appears exactly twice, paired numbers are added and then removed, leaving only the single number in the set at the end.

Complexity Analysis

Time Complexity:O(nlogn)

The sort dominates the runtime at O(nlog⁡n)O(n \log n)O(nlogn); the subsequent linear scan is O(n)O(n)O(n) and does not change the overall complexity.

Space Complexity:O(1)

Sorting is done in-place with no auxiliary data structures needed.

By sorting the array, all duplicate pairs become adjacent. We then step through the sorted array two elements at a time; if a pair doesn't match, the current element is the single number. If no mismatch is found during the loop, the single number must be the last element, which had no pair to sit beside.

Complexity Analysis

Time Complexity:O(n)

We make a single pass through the array performing one XOR operation per element, so the time complexity is O(n)O(n)O(n).

Space Complexity:O(1)

Only a single result variable is needed regardless of input size.

This approach leverages two key XOR properties: any number XORed with itself equals 0, and any number XORed with 0 equals itself. By XORing all elements together, every number that appears twice cancels out to 0, and only the single unpaired number remains as the final result.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Brute Force
O(n2)O(n^{2})O(n2)O(1)O(1)O(1)No extra space neededQuadratic time makes it impractical for large inputs
Math
O(n)O(n)O(n)O(n)O(n)O(n)Intuitive mathematical identityRequires O(n)O(n)O(n) extra space for the set
Toggle Set
O(n)O(n)O(n)O(n)O(n)O(n)Clean, readable toggle logicRequires O(n)O(n)O(n) extra space for the set
Sorting
O(nlog⁡n)O(n \log n)O(nlogn)O(1)O(1)O(1)Constant space with no extra data structuresSuperlinear time due to sorting
XOR Bit Manipulation
O(n)O(n)O(n)O(1)O(1)O(1)Optimal time and space; elegantly leverages XOR propertiesRequires familiarity with bitwise operations

The optimal approach for this problem is Solution 5: XOR Bit Manipulation, which achieves O(n)O(n)O(n) time complexity and O(1)O(1)O(1) space complexity. By XORing all elements together, every paired duplicate cancels out to zero, leaving only the single unpaired number with no extra memory required.


Previous125. Valid Palindrome
Next196. Delete Duplicate Emails
Related posts
  • 1. Two SumEasy
  • 14. Longest Common PrefixEasy
  • 26. Remove Duplicates from Sorted ArrayEasy
  • 27. Remove ElementEasy
  • 49. Group AnagramsMedium
On this page
14 lines
1class Solution:
2 def singleNumber(self, nums: List[int]) -> int:
3 # Iterate through each number in the list and check if it appears more than once.
4 for i in range(len(nums)):
5 found = False # Flag to indicate if a duplicate is found
6
7 # Check if the current number appears more than once in the list.
8 for j in range(len(nums)):
9 if i != j and nums[i] == nums[j]:
10 found = True
11 break
12
13 if not found: # If no duplicate is found, return the current number as the single number.
14 return nums[i]
10 lines
1class Solution:
2 def singleNumber(self, nums: List[int]) -> int:
3 set_nums = set(nums)
4
5 # Calculate the sum of the unique numbers and the sum of all numbers.
6 sum_set = sum(set_nums)
7 sum_nums = sum(nums)
8
9 # The single number is the difference between twice the sum of the unique numbers and the sum of all numbers.
10 return 2 * sum_set - sum_nums
13 lines
1class Solution:
2 def singleNumber(self, nums: List[int]) -> int:
3 # Using a set to track seen numbers. If a number is seen again, it is removed from the set.
4 seen = set()
5
6 for num in nums:
7 if num in seen: # If the number is already in the set, it means we've seen it before, so we remove it.
8 seen.remove(num)
9 else: # If the number is not in the set, we add it to the set.
10 seen.add(num)
11
12 # The single number will be the only element left in the set.
13 return seen.pop()
12 lines
1class Solution:
2 def singleNumber(self, nums: List[int]) -> int:
3 # Sort the array to bring duplicates together
4 nums.sort()
5
6 # Iterate through the sorted array and check for pairs
7 for i in range(0, len(nums) - 1, 2):
8 if nums[i] != nums[i + 1]:
9 return nums[i]
10
11 # If the single number is the last element in the sorted array
12 return nums[-1]
9 lines
1class Solution:
2 def singleNumber(self, nums: List[int]) -> int:
3 # XOR of a number with itself is 0, and XOR of a number with 0 is the number itself.
4 result = 0
5
6 for num in nums:
7 result ^= num
8
9 return result