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
Selected Reading
Picking the odd one out in JavaScript
We are required to write a JavaScript function that takes in an array of literals that contains all similar elements but one.
Our function should return the unlike number.
Therefore, let's write the code for this function ?
Example
The code for this will be ?
const arr = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4];
// considering that the length of array is at least 3
const findUnlike = arr => {
for(let i = 1; i
Output
The output in the console will be ?
2
Alternative Approach Using Frequency Count
A simpler approach is to count the frequency of each element and return the one that appears only once:
const findUnlikeSimple = arr => {
const count = {};
// Count frequency of each element
for(let num of arr) {
count[num] = (count[num] || 0) + 1;
}
// Find the element that appears only once
for(let num in count) {
if(count[num] === 1) {
return parseInt(num);
}
}
};
console.log(findUnlikeSimple([2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])); // 2
console.log(findUnlikeSimple([1, 1, 1, 3, 1, 1])); // 3
console.log(findUnlikeSimple([5, 7, 7, 7, 7])); // 5
2
3
5
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Comparison Method | O(n) | O(1) | Complex |
| Frequency Count | O(n) | O(n) | Simple |
Conclusion
Both methods effectively find the odd element. The frequency count approach is more readable and handles various array arrangements, while the comparison method uses less memory space.
Advertisements
