Single Number
EASYDescription
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.
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.
Approaches
Checkout 4 different approaches to solve Single Number. Click on different approaches to view the approach and algorithm in detail.
Brute Force Approach
This approach uses nested loops to find the single number. For each element in the array, we iterate through the entire array again to count its occurrences. If an element's count is one, it is the unique element.
Algorithm
-
- Iterate through the array with an outer loop from
i = 0ton-1.
- Iterate through the array with an outer loop from
-
- For each element
nums[i], initialize acountvariable to 0.
- For each element
-
- Start an inner loop from
j = 0ton-1.
- Start an inner loop from
-
- Inside the inner loop, if
nums[i]is equal tonums[j], incrementcount.
- Inside the inner loop, if
-
- After the inner loop finishes, check if
countis equal to 1.
- After the inner loop finishes, check if
-
- If
countis 1,nums[i]is the single number. Returnnums[i].
- If
The brute force method is the most straightforward way to solve the problem, but also the least efficient. The core idea is to check every element and see how many times it appears in the array.
We use two nested loops. The outer loop picks an element, and the inner loop iterates through the entire array to count the occurrences of the picked element. If the count for an element is exactly one, we have found our single number and can return it immediately.
public int singleNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[i] == nums[j]) {
count++;
}
}
if (count == 1) {
return nums[i];
}
}
return -1; // Should not be reached given the problem constraints
}
Complexity Analysis
Pros and Cons
- Simple to understand and implement.
- Uses constant extra space.
- Highly inefficient with a quadratic time complexity.
- Will likely result in a 'Time Limit Exceeded' error for large inputs.
Code Solutions
Checking out 5 solutions in different languages for Single Number. Click on different languages to view the code.
public class Solution {
public int SingleNumber(int[] nums) {
return nums.Aggregate(0, (a, b) => a ^ b);
}
}Video Solution
Watch the video walkthrough for Single Number
Similar Questions
5 related questions you might find useful
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.