Tutorialspoint
Problem
Solution
Submissions

Single Number

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

Write a C program to find the element that appears only once in an array where every other element appears exactly twice. Given a non-empty array of integers, every element appears twice except for one. Find that single element.

Example 1
  • Input: nums = [2,2,1]
  • Output: 1
  • Explanation:
    • Step 1: Scan through the array [2,2,1]
    • Step 2: Element 2 appears twice
    • Step 3: Element 1 appears only once
    • Step 4: Therefore, the output is 1
Example 2
  • Input: nums = [4,1,2,1,2]
  • Output: 4
  • Explanation:
    • Step 1: Scan through the array [4,1,2,1,2]
    • Step 2: Element 1 appears twice
    • Step 3: Element 2 appears twice
    • Step 4: Element 4 appears only once
    • Step 5: Therefore, the output is 4
Constraints
  • The array will have a length between 1 and 3 × 10^4
  • Each element in the array will be between -3 × 10^4 and 3 × 10^4
  • Each element appears exactly twice except for one element which appears only once
  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(1)
ArraysGoldman SachsApple
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

  • A brute force approach would be to count occurrences of each element, but that would require O(n) space
  • Consider using bitwise operations to solve this problem in O(1) space
  • XOR (exclusive OR) of a number with itself results in 0
  • XOR of a number with 0 results in the number itself
  • XOR has the associative property: (a ^ b) ^ c = a ^ (b ^ c)

Steps to solve by this approach:

 Step 1: Initialize a variable 'result' to 0.

 Step 2: Iterate through the array elements one by one.
 Step 3: For each element, perform XOR operation with the 'result' variable.
 Step 4: When we XOR a number with itself, it becomes 0.
 Step 5: When we XOR a number with 0, it remains the same.
 Step 6: Due to these properties, duplicate elements will cancel each other out.
 Step 7: The final value of 'result' will be the element that appears only once.

Submitted Code :