Single Occurrence Identifier — Problem Statement & Solution Guide
Problem Description
Given a non-empty array of integers, every element appears twice except for one. Find the first element that appears once in the order they appear in the array. If no such element exists, return 'there is no unique number'.
Examples
Input
[2, 3, 5, 4, 5, 3, 4]
Output
2
Explanation: Step-by-step: with input [2, 3, 5, 4, 5, 3, 4], we create a frequency map. The first element that appears once is 2, so the output is 2.
Input
[10, 20, 10, 30, 30, 40, 40]
Output
20
Explanation: Step-by-step: with input [10, 20, 10, 30, 30, 40, 40], we create a frequency map. The first element that appears once is 20, so the output is 20.
Constraints
- 1 <= n <= 10^5
- n is always odd.
Optimal Approach & Strategy
Use a hash map to count the occurrences of each batch ID in O(n) time complexity
Brute Force Approach
Compare each batch ID with every other batch ID to find the one that appears exactly once
Verified Code Solutions
function solution(nums) {
let map = new Map();
for (let num of nums) {
if (map.has(num)) {
map.set(num, map.get(num) + 1);
} else {
map.set(num, 1);
}
}
for (let num of nums) {
if (map.get(num) === 1) {
return num;
}
}
return 'there is no unique number';
}class Solution {
public:
string solution(vector<int>& nums) {
unordered_map<int, int> countMap;
for (int num : nums) {
countMap[num]++;
}
for (int num : nums) {
if (countMap[num] == 1) {
return to_string(num);
}
}
return "there is no unique number";
}
};import java.util.HashMap;
import java.util.Map;
class Solution {
public String solution(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
for (int num : nums) {
if (countMap.get(num) == 1) {
return String.valueOf(num);
}
}
return "there is no unique number";
}
}def solution(nums):
count_map = {}
for num in nums:
if num in count_map:
count_map[num] += 1
else:
count_map[num] = 1
for num in nums:
if count_map[num] == 1:
return num
return 'there is no unique number'function solution(nums) {
let map = new Map();
for (let num of nums) {
if (map.has(num)) {
map.set(num, map.get(num) + 1);
} else {
map.set(num, 1);
}
}
for (let num of nums) {
if (map.get(num) === 1) {
return num;
}
}
return 'there is no unique number';
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.