Find duplicates in an array using javascript
Problem :
Given an array of positive integers find all the duplicate elements.
Algorithm :
- Iterate over the array using
forEach- Find if there is a duplicate for the element using
indexOf indexOftakes two arguments first the element and the second one is the starting index- We provide the starting index as the
index + 1where index is the index of the current element - We will find if the same element exists on the
right hand sideof that element or not -
If there's a
duplicateand the element is not already being added to theresultthen push it to the array.
- Find if there is a duplicate for the element using
Solution :