![]() |
We are given an array that has n number of elements and an integer k, we have to return all the elements which will appear more than n/k times in the array using JavaScript. Examples:Input: arr = {4, 2, 4, 1, 4, 5, 5, 5}, k=3 Table of Content Using SortingIn this approach, we will count the frequency of each element by sorting the array and then check the frequency of each element with the n/k value. Example: The below code implements the sorting approach to find the elements that appear more than n/k times.
Output 4 1 None of the elements appear more than n/k times None of the elements appear more than n/k times Time Complexity : O(n*logn), we are sorting the array. Space Complexity : O(1), constant space Using MapIn this approach, we will reduce the space complexity by using map data structure and traversing the array only once. We initialize an empty map to store frequency of each element of array. Now, we will iterate through array and check if element exist in the map, increment its count by 1. Now, iterate through map and print those element that appear more than n/k times. Example: The below code implements JavaScript Map to find all elements that appear more than n/k times.
Output 4 1 Time Complexity : O(n), as we are traversing the array. Space Complexity : O(n), as we are using map data structure. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |