Tutorialspoint
Problem
Solution
Submissions

Find Single Number in Array

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to find the single number in an array where every other number appears exactly twice except for one number that appears only once. The solution should have linear time complexity and constant space complexity.

Example 1
  • Input: nums = [2, 2, 1]
  • Output: 1
  • Explanation: Array contains [2, 2, 1]. Number 2 appears twice. Number 1 appears only once. Therefore, the single number is 1.
Example 2
  • Input: nums = [4, 1, 2, 1, 2]
  • Output: 4
  • Explanation: Array contains [4, 1, 2, 1, 2]. Number 1 appears twice (positions 1 and 3). Number 2 appears twice (positions 2 and 4). Number 4 appears only once (position 0). Therefore, the single number is 4.
Constraints
  • 1 ≤ nums.length ≤ 30000
  • Each element in the array appears twice except for one
  • All numbers are integers
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use XOR (exclusive OR) operation properties
  • XOR of a number with itself is 0 (a ^ a = 0)
  • XOR of a number with 0 is the number itself (a ^ 0 = a)
  • XOR operation is commutative and associative
  • Iterate through array and XOR all elements together

Steps to solve by this approach:

 Step 1: Initialize a result variable to 0.
 Step 2: Iterate through each element in the input array.
 Step 3: Apply XOR operation between result and current element.
 Step 4: Continue XORing all elements (duplicates will cancel out to 0).
 Step 5: The remaining value after all XOR operations is the single number.
 Step 6: Return the result which contains the single occurring number.
 Step 7: This works because XOR of identical numbers is 0, and XOR with 0 returns the original number.

Submitted Code :