Find the duplicate number in an array

In this program, we will demonstrate how to find a duplicate element in an array.

This question is available on Leetcode, so you can see the question details from the below link:



Input: nums = [1,3,4,2,2]
Output: 2


//Find the duplicate number in an array

function findDuplicate(arr) {

    for(let i = 0; i < arr.length; i++) {
        for(let j = i + 1; j < arr.length; j++) {
            if(arr[i] == arr[j]) { //If arr[i] value exist in arr[j]
                return arr[i];
    return undefined;

var result = findDuplicate([1,2,3,4,5,2,0]); //BigO of this program is O(n^2)

console.log('Result = ' + result);

Leave a Reply

Your email address will not be published.