Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding unlike number in an array - JavaScript
We are required to write a JavaScript function that takes in an array of literals containing all similar elements but one. Our function should return the unlike number.
The Problem
Given an array where all elements are the same except one, we need to identify and return the unique element. This is a common programming challenge that can be solved efficiently using different approaches.
Method 1: Using Frequency Count
The most straightforward approach is to count the frequency of each element and return the one that appears only once.
const arr = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4];
const findUnlike = (arr) => {
const frequency = {};
// Count frequency of each element
for (let num of arr) {
frequency[num] = (frequency[num] || 0) + 1;
}
// Find the element with frequency 1
for (let num in frequency) {
if (frequency[num] === 1) {
return parseInt(num);
}
}
};
console.log(findUnlike(arr)); // 2
2
Method 2: Using Array Methods
We can use JavaScript's built-in array methods to find the unique element more concisely.
const arr = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4];
const findUnlike = (arr) => {
return arr.find(num => arr.indexOf(num) === arr.lastIndexOf(num));
};
console.log(findUnlike(arr)); // 2
// Alternative using filter
const findUnlikeFilter = (arr) => {
return arr.filter(num => arr.indexOf(num) === arr.lastIndexOf(num))[0];
};
console.log(findUnlikeFilter(arr)); // 2
2
Method 3: Optimized Comparison Approach
For arrays with exactly one unique element, we can compare the first three elements to determine which one is different.
const arr1 = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4];
const arr2 = [4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4];
const findUnlike = (arr) => {
// Compare first three elements to identify pattern
if (arr[0] === arr[1]) {
return arr.find(num => num !== arr[0]);
} else if (arr[0] === arr[2]) {
return arr[1];
} else {
return arr[0];
}
};
console.log(findUnlike(arr1)); // 2
console.log(findUnlike(arr2)); // 2
2 2
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Frequency Count | O(n) | O(n) | High |
| Array Methods | O(n²) | O(1) | Very High |
| Comparison Approach | O(n) | O(1) | Medium |
Conclusion
The frequency count method offers the best balance of performance and readability. For small arrays, the array methods approach provides the most concise solution, while the comparison approach is most memory-efficient for large datasets.
