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 the only even or the only odd number in a string of space separated numbers in JavaScript
We are required to write a JavaScript function that takes in a string that contains numbers separated by spaces.
The string either contains all odd numbers and only one even number or all even numbers and only one odd number. Our function should return that one different number from the string.
Problem
Given a string of space-separated numbers where all numbers are either odd or even except for one, we need to find and return that unique number that differs from the rest.
Example
Following is the code:
const str = '2 4 7 8 10';
const findDifferent = (str = '') => {
const odds = [];
const evens = [];
const arr = str
.split(' ')
.map(Number);
arr.forEach(num => {
if(num % 2 === 0){
evens.push(num);
}else{
odds.push(num);
};
});
return odds.length === 1 ? odds[0] : evens[0];
};
console.log(findDifferent(str));
Output
Following is the console output:
7
How It Works
The function splits the input string into an array of numbers, then separates them into odd and even arrays. Since we know exactly one number will be different, we check which array has only one element and return it.
Alternative Approach
Here's a more efficient solution that doesn't require storing all numbers:
const str1 = '1 3 5 2 7';
const str2 = '2 4 6 8 9';
const findDifferentOptimized = (str = '') => {
const numbers = str.split(' ').map(Number);
// Check if first three numbers to determine the pattern
const evenCount = numbers.slice(0, 3).filter(num => num % 2 === 0).length;
const lookingForEven = evenCount === 1;
return numbers.find(num => (num % 2 === 0) === lookingForEven);
};
console.log(findDifferentOptimized(str1)); // 2 (even among odds)
console.log(findDifferentOptimized(str2)); // 9 (odd among evens)
2 9
Conclusion
Both approaches work effectively, but the optimized version is more memory-efficient as it doesn't store all numbers in separate arrays. The key insight is identifying the pattern early and finding the number that breaks it.
