Counting the occurrences of array elements and print only the element value is greater than 1 [closed]

Counting the occurrences of array elements and print only the element value is greater than 1 using javascript.

Input : [1,3,6,1,4,7,1,3]
output:
1: 3
3: 2

  • 1

    There doesn’t seem to be a question here. SO is not a code-sharing site. If you want to share the solution to a problem, the answer should be posted below in the “Your Answer” section.

    – 




The time complexity of the code is O(n). The first loop that iterates through arrayList has a time complexity of O(n). In this loop, you are creating the newArray object, and for each element in arrayList, you either increment the count for that element in newArray or set it to 1 if it doesn’t exist.

The second loop that iterates through newArray and prints elements with counts greater than 1 also has a time complexity of O(n). In the worst case, it will iterate through all unique elements in arrayList.

Therefore, the overall time complexity is O(n + n), which simplifies to O(n).

function mainfunction(arrayList){
    newArray = {};
    for(const item of arrayList){
        newArray[item] = newArray[item] ? newArray[item] += 1 : 1;
    }

    for (const key in newArray) {
        if (newArray[key] > 1) {
            console.log(`${key}: ${newArray[key]}`);
        }
    }
}
mainfunction([1,3,6,1,4,7,1,3]) 
# output:
# 1: 3
# 3: 2

Leave a Comment