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
Find duplicate element in a progression of first n terms JavaScript
When you have an array of first n natural numbers with one duplicate element, finding the duplicate efficiently is a common programming challenge. We'll explore two mathematical approaches that solve this in linear time.
Method 1: Using Array.prototype.reduce()
This approach uses a mathematical trick with the reduce function to find the duplicate in a single pass:
const arr = [2, 3, 1, 2]; const duplicate = a => a.reduce((acc, val, ind) => val + acc - (ind + 1)) + a.length - 1; console.log(duplicate(arr));
2
How the Reduce Method Works
Let's trace through the algorithm step by step with array [2, 3, 1, 2]:
Since no initial value is provided to reduce(), it starts from index 1 with the first element as the accumulator:
First Pass:
acc = 2, val = 3, ind = 1 return value = 2 + 3 - (1 + 1) = 3
Second Pass:
acc = 3, val = 1, ind = 2 return value = 3 + 1 - (2 + 1) = 1
Third Pass:
acc = 1, val = 2, ind = 3 return value = 1 + 2 - (3 + 1) = -1
Finally: -1 + (4 - 1) = 2, which is our duplicate element.
Method 2: Using Array.prototype.forEach()
This method calculates the sum of all elements and subtracts the sum of first (n-1) natural numbers:
const arr = [1, 4, 8, 5, 6, 7, 9, 2, 3, 7];
const duplicate = a => {
let sum = 0;
const { length: n } = a;
a.forEach(num => sum += num);
return sum - ((n * (n - 1)) / 2);
}
console.log(duplicate(arr));
7
Mathematical Explanation
The forEach method works because:
- Sum of first n natural numbers = n × (n + 1) / 2
- Sum of first (n-1) natural numbers = (n-1) × n / 2
- Array sum - Sum of (n-1) numbers = duplicate element
Comparison
| Method | Readability | Time Complexity | Space Complexity |
|---|---|---|---|
| Reduce | Complex | O(n) | O(1) |
| forEach | Clear | O(n) | O(1) |
Conclusion
Both methods achieve linear time complexity using mathematical formulas. The forEach approach is more readable, while the reduce method is more compact but harder to understand.
