You are given an array 'arr' of length 'n' containing integers within the range '1' to 'x'.
Your task is to count the frequency of all elements from 1 to n.
Note:You do not need to print anything. Return a frequency array as an array in the function such that index 0 represents the frequency of 1, index 1 represents the frequency of 2, and so on.
Example:
Input: ‘n’ = 6 ‘x’ = 9 ‘arr’ = [1, 3, 1, 9, 2, 7]
Output: [2, 1, 1, 0, 0, 0]
Explanation: Below Table shows the number and their counts, respectively, in the array
Number Count
1 2
2 1
3 1
4 0
5 0
6 0
The first line contains two integers, ‘n’ and ‘x’.
The following line contains ‘n’ integers and the array ‘arr’.
Output format:
Return the frequency array.
6 4
1 3 4 3 4 1
2 0 2 2 0 0
Frequency table:
Number Count
1 2
2 0
3 2
4 2
5 0
6 0
5 5
1 2 3 4 5
1 1 1 1 1
Frequency table:
Number Count
1 1
2 1
3 1
4 1
5 1
1 <= n <= 10^5
1 <= x <= 10^5
1 <= arr[i] <= x
1. Since the range of the elements is known, we can iterate over the range.
2. Since the bounds of the elements are known, a frequency array can be maintained.
3. Try to use the input array as the answer array itself.
We iterate over ‘1’ to 'n', and for each value in ‘1’ to 'n', we loop over the array ‘arr’ and find the frequency of that element.
Algorithm:
O(n^2) where n is the size of the array
We are iterating through the array for each integer in 1 to n, so there would be n iterations in total.
Hence the time complexity is O(n^2).
O(n), Where n is the length of the array.
We are creating a new freq array of size n to store the frequency for each element from 1 to n.
Hence the space complexity is O(n).