Cranes at VIIT Q6
Find the Most Frequent Element in an Array
Write a C program that finds the most frequent element in an array.
Problem Statement:
-
Given an array of integers, determine the element that occurs the most frequently.
-
If multiple elements have the same highest frequency, return the smallest element among them.
Input Format:
- n: An integer representing the number of elements in the array.
- n space-separated integers representing the elements of the array.
Output Format:
- Print the most frequent element in the array.
Example Inputs & Outputs:
Enter the number of elements: 7
Enter the elements: 1 3 2 3 4 1 3
Most frequent element: 3
Enter the number of elements: 5
Enter the elements: 5 1 5 1 2
Most frequent element: 1
Constraints:
- 1 ≤ n ≤ 1000
- -10⁵ ≤ array[i] ≤ 10⁵
Hint:
To solve this problem, follow these steps:
-
Store Frequencies:
- Create an array or a map to store the frequency of each element.
- Traverse the input array and increment the frequency of each element.
-
Find Maximum Frequency:
- Traverse the frequency array/map to find the element with the highest frequency.
-
Check for Multiple Maximums:
- If multiple elements have the same highest frequency, choose the smallest element.
-
Print the Result:
- Print the element with the highest frequency or the smallest among elements with equal frequency.
Formula Breakdown:
-
Increment Frequency Count:
freq[arr[i] + offset]++;
Note: offset
is used to handle negative values.
-
Check for Most Frequent Element:
if (freq[arr[i] + offset] > max_freq)
-
Resolve Ties by Smallest Element:
if (freq[arr[i] + offset] == max_freq && arr[i] < result)
Task: Implement the above logic and write a C program to find the most frequent element in an array.