Find duplicate element in a progression of first n terms JavaScript


Let’s say, we are given an array of numbers that contains first n natural numbers, but one element appears twice in the array, so the total number of elements is n+1. Our job is to write a function that takes in the array and returns the number that appears twice in linear time.

Method 1: Using Array.prototype.reduce()

This is a bit trickier approach but the most compressed in terms of code written. First, let’s see the code for it −

const arr = [1,4,8,5,6,7,9,2,3,7];
const duplicate = a => a.reduce((acc, val, ind) => val+acc-
(ind+1))+a.length-1;
console.log(duplicate(arr));

Here we have used the reduce function, its callback, which operates once for each element of array, in our case is taking three arguments,

  • acc → accumulator, value returned in the previous pass, and
  • val → the current element value,
  • ind → the index of current element

Now, let’s apply our code to this array −

[ 2, 3, 1, 2]

As the length of this array is 4, there should be a total of 4 pass of callback function, but as we have not provided the initialValue argument to the reduce() function, iterations will start from index 1 and accumulator will be initially assigned with value at zeroth index, so there will be a total of 3 pass.

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

END OF ARRAY

Hence -1 gets returned from the array, and then

-1 + (4-1) = -1 + 3 = 2

gets returned from the duplicate() function, which is actually the correct result.

Method 2: Array.prototype.forEach()

In this method, we iterate over the array, get its sum, and subtract the sum of first (n-1) natural numbers from it, where n is the length of array, what gets left is the number that repeated twice, so we return it.

Example

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));

Output

The output in the console will be −

7

Updated on: 19-Aug-2020

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements