Introduction
The Frequency Count problem involves counting how many times each element appears in the array.
Given an array arr[] of size n, the task is to calculate the frequency of every distinct element.
This is one of the most important beginner-level Hashing problems and helps in understanding HashMap, frequency tracking, and efficient counting techniques.
Example
Input: arr[] = [1, 2, 2, 3, 1, 4, 2]Output:
1 → 2
2 → 3
3 → 1
4 → 1
Explanation:
1 appears 2 times
2 appears 3 times
3 appears 1 time
4 appears 1 time
Input: arr[] = [5, 5, 5, 5]
Output:
5 → 4
Explanation:
Element 5 appears 4 times.
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse every element
- Count its occurrences manually
- Avoid recounting already processed elements
This approach is easy to understand but repeated traversals increase time complexity.
Steps
- Create a visited array.
- Traverse the array.
- If element is already counted:
- skip it
- Otherwise:
- count occurrences using another loop
- Print element frequency.
Dry Run
Input Array: [1, 2, 2, 3, 1, 4, 2]Traverse 1:
Count occurrences of 1
Frequency = 2
Traverse 2:
Count occurrences of 2
Frequency = 3
Traverse next 2:
Already counted
Skip it
Traverse 3:
Frequency = 1
Traverse 4:
Frequency = 1
Final Frequencies:
1 → 2
2 → 3
3 → 1
4 → 1
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)
Explanation:
Every element may be compared with remaining elements.
Space Complexity: O(n)
Explanation:
Visited array is used.Approach 2 : Optimized Solution (HashMap)
Explanation
Instead of repeatedly counting occurrences, we can use a HashMap.
The idea is:
- Traverse the array
- Store:
- element → frequency
- Update count whenever element appears again
HashMap provides fast insertion and lookup operations.
Steps
- Create an empty HashMap.
- Traverse the array.
- For every element:
- if already exists:
- increment frequency
- otherwise:
- store frequency as 1
- if already exists:
- Print all frequencies.
Dry Run
Input Array: [1, 2, 2, 3, 1, 4, 2]Initially:
HashMap = {}
Traverse 1:
Store:
1 → 1
Traverse 2:
Store:
2 → 1
Traverse next 2:
Update:
2 → 2
Traverse 3:
Store:
3 → 1
Traverse next 1:
Update:
1 → 2
Traverse 4:
Store:
4 → 1
Traverse last 2:
Update:
2 → 3
Final Frequencies:
1 → 2
2 → 3
3 → 1
4 → 1
Optimized Code
Complexity Analysis
Time Complexity: O(n)
Explanation:
Each element is processed once using HashMap operations.
Space Complexity: O(n)
Explanation:
HashMap stores frequencies of elements.