New update is available. Click here to update.

Last Updated: 30 Nov, 2020

Difficulty: Easy

```
For 'arr' = [ 1, 2, 3, 1, 2]. you need to return 1.
```

```
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.
The first line of each test case contains a single integer ‘N’ denoting the size of the array.
The second line of each test case contains ‘N’ space-separated integers denoting the elements of the array.
```

```
For each case, we need to print an integer that has the maximum frequency.
The output of each test case will be printed in a separate line.
```

```
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 5
1 <= N <= 10000
-10 ^ 3 <= |arr| <= 10 ^ 3
Time Limit: 1 sec
```

Here, we can simply run two loops. The outer loop picks all elements one by one and the inner loop finds the frequency of the picked element and compares it with the maximum present so far.

- Declare 4 variables as ‘maxFrequency’ , ‘currentFrequency’ , ‘maxElement’ , ‘currentElement’ and initialize them with 0
- Run a loop from ‘i’ = ‘0’ to ‘N’
- Set ‘currentElement’ as arr[i] and ‘currentFrequency’ to 0
- Run a loop ‘j’ = ‘i’ to ‘N’
- If ‘arr[j]’ is equal to currentElement
- Increment currentFrequency by 1

- If ‘arr[j]’ is equal to currentElement
- If our ‘currentFrequency’ is greater than ‘maxFrequency’
- Update ‘maxFrequency’ and ‘maxElement' with 'currentFrequency' and ‘currentFrequency’ respectively.

- Return 'maxElement'

We can use hashing and count the frequency of all the elements and simultaneously find the maximum frequency. Now we can iterate through the array and find the first element with the maximum frequency and return that element.

- Declare a unorder map
- Declare a variable ‘maxFrequency' and initialize it with ‘0’
- Run a loop from ‘i’ = ‘0’ to ‘N’
- Update the frequency of current element arr[i]
- Update the ‘maxFrequency’ till the current element.

- Declare a variable ‘maxElement’ and initialize it with ‘0’
- Run a loop from ‘i’ = ‘0’ to ‘N’
- If the frequency of our current element is equal to the ‘maxFrequency’ computed
- Update the ‘maxElement’ with the current element and break the loop

- If the frequency of our current element is equal to the ‘maxFrequency’ computed
- Return the 'maxElement'

SIMILAR PROBLEMS

Sort an Array According to the Relative Order of Another Array

Posted: 30 Jul, 2022

Difficulty: Moderate

The Food Inspector

Posted: 31 Jul, 2022

Difficulty: Easy

LRU Cache

Posted: 10 Sep, 2022

Difficulty: Moderate

Longest Subarray With Zero Sum

Posted: 3 Nov, 2022

Difficulty: Moderate

Maximum GCD

Posted: 8 Dec, 2022

Difficulty: Hard

Popular Interview Problems: