Search This Blog

2026/08/09

Javascript find duplicate in array without hashmap.



Find duplicate in an array without using hashmap.

Code:
    const arr = [4, 2, 7, 4, 2, 8, 4, 9];

    arr.sort((a, b) => a - b);
    console.log("After Sorting", arr)

    let duplicates = [];

    //array starts from index 1 because we are comparing with previous element
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] === arr[i - 1]) {
            if (!duplicates.includes(arr[i]))
                duplicates.push(arr[i]);
        }
    }

    console.log("Duplicates", duplicates);

Result:
    After Sorting [ 2, 2, 4, 4, 4, 7, 8, 9 ]
    Duplicates [ 2, 4 ]

Explanation:
1. We first sort the array in ascending order using the `sort()` method.
2. We then initialize an empty array called `duplicates` to store the duplicate values.
3. We loop through the sorted array starting from index 1, comparing each element with its previous element.
4. If the current element is equal to the previous element, we check if it is already in the `duplicates`
array. If not, we add it to the `duplicates` array.
5. Finally, we log the `duplicates` array to the console, which contains all the duplicate values found
in the original array.

No comments:

Post a Comment