Unique Number I
Given an array of integers, every element in the array appears twice except for one element which appears only once. The task is to identify and return the element that occurs only once.
Examples:
Input: arr[] = [2, 3, 5, 4, 5, 3, 4]
Output: 2
Explanation: Since 2 occurs once, while other numbers occur twice, 2 is the answer.Input: arr[] = [2, 2, 5, 5, 20, 30, 30]
Output: 20
Explanation: Since 20 occurs once, while other numbers occur twice, 20 is the answer.
Table of Content
[Naive Approach] Nested Loop Frequency Counting - O(n^2) Time and O(1) Space
This approach iterates through the array and counts the frequency of each element using a nested loop. For each element, the inner loop counts how many times it appears in the array. If an element appears exactly once, it is returned as the result. This method ensures that the correct element is identified but is inefficient due to the nested loop.
#include <iostream>
#include <vector>
using namespace std;
int findUnique(vector<int>& arr) {
int n = arr.size();
// Iterate over every element
for (int i = 0; i < n; i++) {
// Initialize count to 0
int count = 0;
for (int j = 0; j < n; j++) {
// Count the frequency of the element
if (arr[i] == arr[j]) {
count++;
}
}
// If the frequency of the element is one
if (count == 1) {
return arr[i];
}
}
// If no element exists at most once
return -1;
}
int main() {
vector<int> arr = { 2, 3, 5, 4, 5, 3, 4 };
cout << findUnique(arr) << endl;
return 0;
}
import java.util.*;
class GfG {
static int findUnique(int[] arr) {
int n = arr.length;
// Iterate over every element
for (int i = 0; i < n; i++) {
// Initialize count to 0
int count = 0;
for (int j = 0; j < n; j++) {
// Count the frequency of the element
if (arr[i] == arr[j]) {
count++;
}
}
// If the frequency of the element is one
if (count == 1) {
return arr[i];
}
}
// If no element exists at most once
return -1;
}
public static void main(String[] args) {
int[] arr = {2, 3, 5, 4, 5, 3, 4};
System.out.println(findUnique(arr));
}
}
def findUnique(arr):
n = len(arr)
# Iterate over every element
for i in range(n):
# Initialize count to 0
count = 0
for j in range(n):
# Count the frequency of the element
if arr[i] == arr[j]:
count += 1
# If the frequency of the element is one
if count == 1:
return arr[i]
# If no element exists at most once
return -1
if __name__ == "__main__":
arr = [2, 3, 5, 4, 5, 3, 4]
print(findUnique(arr))
using System;
class GfG {
static int findUnique(int[] arr) {
int n = arr.Length;
// Iterate over every element
for (int i = 0; i < n; i++) {
// Initialize count to 0
int count = 0;
for (int j = 0; j < n; j++) {
// Count the frequency of the element
if (arr[i] == arr[j]) {
count++;
}
}
// If the frequency of the element is one
if (count == 1) {
return arr[i];
}
}
// If no element exists at most once
return -1;
}
static void Main(string[] args) {
int[] arr = {2, 3, 5, 4, 5, 3, 4};
Console.WriteLine(findUnique(arr));
}
}
function findUnique(arr) {
let n = arr.length;
// Iterate over every element
for (let i = 0; i < n; i++) {
// Initialize count to 0
let count = 0;
for (let j = 0; j < n; j++) {
// Count the frequency of the element
if (arr[i] === arr[j]) {
count++;
}
}
// If the frequency of the element is one
if (count === 1) {
return arr[i];
}
}
// If no element exists at most once
return -1;
}
let arr = [2, 3, 5, 4, 5, 3, 4];
console.log(findUnique(arr));
Output
2
[Better Approach] Using Hash Map - O(n) Time and O(n) Space
This approach uses a hash map (or dictionary) to track the frequency of each element in the array. First, we iterate through the array to record how many times each element appears. Then, we scan the hash map to find the element that appears exactly once. If such an element is found, it is returned; otherwise, the function returns
-1
. This method efficiently solves the problem in linear time with a linear space complexity.
Step by step approach:
- Traverse all elements and insert them into a hash table. Element is used as key and the frequency is used as the value in the hash table.
- Iterate through the map and return the value with count equal to 1.
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int findUnique(vector<int>& arr) {
int n = arr.size();
// Hash map to store the count of each element
unordered_map<int, int> cnt;
// Store frequency of each element
for (int i = 0; i < n; i++) {
cnt[arr[i]]++;
}
// Return the value with count = 1
for (auto p : cnt) {
if (p.second == 1) {
return p.first;
}
}
// If no element exists that appears only once
return -1;
}
int main() {
vector<int> arr = { 2, 3, 5, 4, 5, 3, 4 };
cout << findUnique(arr) << endl;
return 0;
}
import java.util.HashMap;
import java.util.Map;
public class GfG {
public static int findUnique(int[] arr) {
// Hash map to store the count of each element
HashMap<Integer, Integer> cnt = new HashMap<>();
// Store frequency of each element
for (int num : arr) {
cnt.put(num, cnt.getOrDefault(num, 0) + 1);
}
// Return the value with count = 1
for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
// If no element exists that appears only once
return -1;
}
public static void main(String[] args) {
int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
System.out.println(findUnique(arr));
}
}
def findUnique(arr):
# Dictionary to store the count of each element
cnt = {}
# Store frequency of each element
for num in arr:
cnt[num] = cnt.get(num, 0) + 1
# Return the value with count = 1
for key, value in cnt.items():
if value == 1:
return key
# If no element exists that appears only once
return -1
arr = [2, 3, 5, 4, 5, 3, 4]
print(findUnique(arr))
using System;
using System.Collections.Generic;
class GfG {
public static int findUnique(int[] arr) {
// Dictionary to store the count of each element
Dictionary<int, int> cnt = new Dictionary<int, int>();
// Store frequency of each element
foreach (int num in arr) {
if (cnt.ContainsKey(num)) {
cnt[num]++;
} else {
cnt[num] = 1;
}
}
// Return the value with count = 1
foreach (var pair in cnt) {
if (pair.Value == 1) {
return pair.Key;
}
}
// If no element exists that appears only once
return -1;
}
static void Main() {
int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
Console.WriteLine(findUnique(arr));
}
}
function findUnique(arr) {
// Object to store the count of each element
const cnt = {};
// Store frequency of each element
for (const num of arr) {
cnt[num] = (cnt[num] || 0) + 1;
}
// Return the value with count = 1
for (const key in cnt) {
if (cnt[key] === 1) {
return parseInt(key);
}
}
// If no element exists that appears only once
return -1;
}
const arr = [2, 3, 5, 4, 5, 3, 4];
console.log(findUnique(arr));
Output
2
[Expected Approach] Using XOR Operation - O(n) Time and O(1) Space
This approach uses the XOR operation to find the unique element in an array where every other element appears twice. XOR of two identical numbers cancels them out (results in zero), so after XORing all the elements, only the element that appears once will remain.
#include <iostream>
#include <vector>
using namespace std;
int findUnique(vector<int>& arr) {
int n = arr.size();
int res = 0;
// Find XOR of all elements
for (int i = 0; i < n; i++) {
res = res ^ arr[i];
}
return res;
}
int main() {
vector<int> arr = { 2, 3, 5, 4, 5, 3, 4 };
cout << findUnique(arr) << endl;
return 0;
}
import java.util.List;
import java.util.Arrays;
public class GfG {
public static int findUnique(int[] arr) {
int res = 0;
// Find XOR of all elements
for (int i = 0; i < arr.length; i++) {
res ^= arr[i];
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 3, 5, 4, 5, 3, 4};
System.out.println(findUnique(arr));
}
}
def findUnique(arr):
res = 0
# Find XOR of all elements
for num in arr:
res ^= num
return res
if __name__ == '__main__':
arr = [2, 3, 5, 4, 5, 3, 4]
print(findUnique(arr))
using System;
class GfG {
static int findUnique(int[] arr) {
int res = 0;
// Find XOR of all elements
foreach (int num in arr) {
res ^= num;
}
return res;
}
static void Main() {
int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
Console.WriteLine(findUnique(arr));
}
}
function findUnique(arr) {
let res = 0;
// Find XOR of all elements
for (let i = 0; i < arr.length; i++) {
res ^= arr[i];
}
return res;
}
const arr = [2, 3, 5, 4, 5, 3, 4];
console.log(findUnique(arr));
Output
2