Approach (Brute Force – Hash Map)
Create an empty hash map to store counts of each element.
- Loop through the array, update the count for each element.
- Loop through the array again to find the element with count 1.
- Return that element.
Dry Run
Input: [4, 1, 2, 1, 2]
Step 1: Counting frequency
hash = {}
Insert 4 → hash[4] = 1
Insert 1 → hash[1] = 1
Insert 2 → hash[2] = 1
Update 1 → hash[1] = 2
Update 2 → hash[2] = 2
Step 2: Find the element with count 1
4 → hash[4] = 1 → return 4
Output: 4
var singleNumber = function(nums) {
let hash = {};
for(let i = 0; i < nums.length; i++) {
if (!hash[nums[i]]) {
hash[nums[i]] = 1;
} else {
hash[nums[i]]++;
}
}
for(let i = 0; i < nums.length; i++) {
if (hash[nums[i]] === 1) {
return nums[i];
}
}
};
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> hash;
for (int num : nums) {
hash[num]++;
}
for (int num : nums) {
if (hash[num] == 1)
return num;
}
return -1;
}
};
#include <stdio.h>
int singleNumber(int* nums, int numsSize){
for (int i = 0; i < numsSize; i++) {
int count = 0;
for (int j = 0; j < numsSize; j++) {
if (nums[j] == nums[i]) count++;
}
if (count == 1) return nums[i];
}
return -1;
}
import java.util.HashMap;
public class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> hash = new HashMap<>();
for (int num : nums) {
hash.put(num, hash.getOrDefault(num, 0) + 1);
}
for (int num : nums) {
if (hash.get(num) == 1) {
return num;
}
}
return -1;
}
}
class Solution:
def singleNumber(self, nums):
hash = {}
for num in nums:
hash[num] = hash.get(num, 0) + 1
for num in nums:
if hash[num] == 1:
return num