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 array number that have no matching positive or negative number in the array using JavaScript
We need to write a JavaScript function that finds a number in an array that doesn't have its positive or negative counterpart. For example, in an array containing both 1 and -1, both 2 and -2, but only 3 (without -3), we should return 3.
Problem
Given an array of integers where each number has its negative or positive complement, except for exactly one number, our function should find and return that unpaired number.
Example Input
Consider the array [1, -1, 2, -2, 3]. Here, 1 has -1, 2 has -2, but 3 has no -3, so 3 is our answer.
Solution Using Reduce Method
We can solve this by summing all numbers in the array. Since pairs cancel out (1 + (-1) = 0), only the unpaired number remains.
const arr = [1, -1, 2, -2, 3];
const findOddNumber = (arr = []) => {
return arr.reduce((total, num) => total + num, 0);
};
console.log("Array:", arr);
console.log("Unpaired number:", findOddNumber(arr));
Array: [ 1, -1, 2, -2, 3 ] Unpaired number: 3
Alternative Solution Using Set
Another approach uses a Set to track which numbers we've seen and remove pairs as we encounter them.
const findUnpairedNumber = (arr = []) => {
const seen = new Set();
for (let num of arr) {
if (seen.has(-num)) {
seen.delete(-num);
} else {
seen.add(num);
}
}
return seen.values().next().value;
};
const testArr = [4, -4, 7, -7, 1, -1, 5];
console.log("Array:", testArr);
console.log("Unpaired number:", findUnpairedNumber(testArr));
Array: [ 4, -4, 7, -7, 1, -1, 5 ] Unpaired number: 5
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Sum with Reduce | O(n) | O(1) | High |
| Set Approach | O(n) | O(n) | Medium |
Testing with Multiple Examples
const testCases = [
[1, -1, 2, -2, 3],
[-5, 5, -3, 3, 7],
[0, 1, -1],
[10, -10, 20, -20, -30]
];
testCases.forEach((arr, index) => {
const result = arr.reduce((sum, num) => sum + num, 0);
console.log(`Test ${index + 1}: [${arr.join(', ')}] ? ${result}`);
});
Test 1: [1, -1, 2, -2, 3] ? 3 Test 2: [-5, 5, -3, 3, 7] ? 7 Test 3: [0, 1, -1] ? 0 Test 4: [10, -10, 20, -20, -30] ? -30
Conclusion
The simplest solution is to sum all array elements using reduce(). Since positive-negative pairs cancel out, only the unpaired number remains. This approach is efficient with O(1) space complexity and clear, readable code.
