Array ( [0] => [1] => questions [2] => Arrays [3] => Most-Frequent-Element ) Arrays | Most Frequent Element | THE INQUISITIVE





Most Frequent Element

LEVEL:Beginner

Description

Given list of elements. You have to find the most frequent element in given array. If there are more than two frequency elements then print the first occurrence in the given array.

Input Format

First line contains a number N. Next line contains N integers separated by spaces

Output Format

Print the resultant sum value.


Example 1:

Input
5
3 5 4 4 1
Output
4
Example 2:

Input
8
5 4 3 6 5 4 3 4	
Output
4
Example 3:

Input
10
3 2 5 4 6 7 6 7 6 5
Output
6

oops

Login to see Discussion




Approach

Approach 1: using brute force

Step-i) initialize two variables prev_count and curr_count to zero
Step-ii) initialize a variable with first element of the array assuming for now that it is the most frequent element
Step-iii) take the current element and check how many times it is repeated in the array
Step-iv) every time it is repeated increment the curr_count
Step-v) after checking entire array for that number check if curr_count is greater than prev_count
Step-vi) if it is greater assign curr_count to prev_count and answer variable to the current element
Step-vii)initialize curr_count to 0
Step-viii) repeat steps iii,iv,v,vi,vii till all the elements of the array are traversed
Step-ix) return the answer

Time Complexity: O(n^2)
Space Complexity:O(1)

Approach 2: using HashMap

Step-i) create a hashmap of both keys and values as integers
Step-ii)assign current element of the array to temp
Step-iii) if temp is in keys of hashmap increment its key value
Step-iv) if temp is not in keys of hashmap add current element as key and 1 as its value
Step-v)go to next element
Step-vi) repeat steps ii, iii, iv and v till you traverse the complete array
Step-vii) create a iterator for the hashmap
Step-viii) iterate over the hashmap and get the key of the highest value present in it
Step-ix) return the key

Time Complexity: O(n)
Space Complexity: O(n) as hashmap need to be maintained


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution