Introduction
The Frequency Count problem involves counting how many times each element appears in an array or string.
Given:
- an array
or - a string
the task is to:
- count frequency of every element
- display occurrence count
This problem helps in understanding:
- hashing
- frequency counting
- traversal techniques
- data grouping
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:
s = "coding"
Output:
c → 1
o → 1
d → 1
i → 1
n → 1
g → 1
Explanation:
Every character appears once.
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse every element
- Count frequency manually
- Print frequencies
This approach is easy to understand but repeated counting increases time complexity.
Steps
- Traverse array elements.
- Count frequency of current element.
- Print frequency if not already processed.
- Continue traversal.
Dry Run
Input:arr = [1,2,2,3,1]
Check 1:
Frequency = 2
Print: 1 → 2
Check 2: Frequency = 2 Print: 2 → 2
Check 3:
Frequency = 1
Print:
3 → 1
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
Nested traversal is used for counting frequencies.
Space Complexity: O(n) Explanation:
Visited array is used.
Approach 2 : Optimized Solution (Hashing)
Explanation
The optimized solution uses hashing.
The idea is:
- Store frequencies inside hashmap
- Traverse array once
- Print stored frequencies
This avoids repeated counting.
Steps
- Create hashmap.
- Traverse array.
- Increment frequencies.
- Print hashmap values.
Dry Run
Input:arr = [1,2,2,3,1]
Store frequencies: 1 → 2
2 → 2
3 → 1
Final Result: 1 → 2
2 → 2
3 → 1
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Each element is processed once.
Space Complexity: O(n)
Explanation:
Extra hashmap is used for frequencies.