Frequencies of Limited Range Array Elements | Practice | GeeksforGeeks

Given an array A[] of N positive integers which can contain integers from 1 to P where elements can be repeated or can be absent from the array. Your task is to count the frequency of all elements from 1 to N.
Note: The elements greater than N in the array can be ignored for counting.

Example 1:
Input:
N = 5
arr[] = {2, 3, 2, 3, 5}
P = 5
Output:
0 2 2 0 1
Explanation: 
Counting frequencies of each array element
We have:
1 occurring 0 times.
2 occurring 2 times.
3 occurring 2 times.
4 occurring 0 times.
5 occurring 1 time.
Example 2:
Input:
N = 4
arr[] = {3,3,3,3}
P = 3
Output:
0 0 4 0
Explanation: 
Counting frequencies of each array element
We have:
1 occurring 0 times.
2 occurring 0 times.
3 occurring 4 times.
4 occurring 0 times.

Your Task:
Complete the function frequencycount() that takes the array and n as input parameters and modify the array in place to denote the frequency count of each element from 1 to N. i,e element at index 0 should represent the frequency of 1 and so on.

Note: Can you solve this problem without using extra space (O(1) Space) !

Constraints:
1 ≤ N ≤ 105
1 ≤ P ≤ 4*104 
1 <= A[i] <= P
0
19bcs21531 day ago
Easy C++ solution:
 
class Solution{
public:

	void frequencyCount(vector<int>& arr,int N, int P)

    { 

        // code here

        int a[P+1] = {0};

        for(int i=0; i<N; i++){

            a[arr[i]]++;

        }

        

        for(int i=0; i<N; i++){

            if(i+1<=P){

                arr[i] = a[i+1];

            }

            else{

                arr[i] = 0;

            }

        }

    }

}
 
 
0
rexsunar370101 week ago
JAVA 
Time Complexity - O(n)
Space Complexity - O(n)
public static void frequencyCount(int arr[], int N, int P) {              // int[] res = new int[N];       Map<Integer, Integer> map = new HashMap<>()        ;              for (int i = 0; i < N; i++) {           if (map.containsKey(arr[i]))               map.put(arr[i], map.get(arr[i]) + 1);           else               map.put(arr[i], 1);       }              for (int i = 0; i < N; i++) {           if (!map.containsKey(i+1)) {               arr[i] = 0;           } else               arr[i] = map.get(i+1);       }   }
0
geeta1997cs1 week ago
Python3 Solution 
 
   def frequencyCount(self, arr, N, P):       # code here       d={}       for i in arr:           if i not in d:               d[i]=1           else:               d[i]=d.get(i,0)+1       for i in range(1,N+1):           if i not in d:               arr[i-1]=0           else:               arr[i-1]=d.get(i)       return arr
0
shyampatel21 week ago
PYthon baba    def frequencyCount(self, arr, N, P):       # code here       arr2 = {}       for i in arr:           if i in arr2:               arr2[i] += 1           else:               arr2[i] = 1       for i in range(1,N+1):           if i in arr2:               arr[i-1] = arr2[i]           else:               arr[i-1] = 0
0
lawbindpandey01w1 week ago
 
 
  void frequencyCount(vector<int>& arr,int N, int P)   {        // code here              for(int i = 0; i < N; i++) arr[i] -= 1;              int counte0 = 0;       for(int i = 0; i < N; i++){                      if(arr[i] >= N){               counte0++;               arr[i] = 0;           }                   }                     for(int i = 0; i < N; i++)                      arr[arr[i]%N] += N;                  for(int i = 0; i < N; i++) arr[i] /= N;              arr[0] -= counte0;          }};
0
hari_krishna2 weeks ago
Solution with O(n) space and time;
void frequencyCount(vector<int>& arr,int n, int p)
   { 
       // code here
       long long arrFreqCount[n+1];
       memset(arrFreqCount,0,sizeof(arrFreqCount));
       for(long i=0;i<n;i++) {
           if(arr[i]<=n) {
           arrFreqCount[arr[i]]++;
           }
       }
       
       for(long i=1;i<=n;i++) {
           arr[i-1]=arrFreqCount[i];
       }
   }
0
mayank180919992 weeks ago
    void frequencyCount(vector<int>& arr,int N, int P)
    { 
        // code here
        unordered_map<int,int>mp;
        vector<int>nums;
        for(int i=0;i<N;i++){
            mp[arr[i]]++;
        }
        for(int i=1;i<=N;i++){
            if(mp.count(i)){
                nums.push_back(mp[i]);
            }else{
                       nums.push_back(mp.count(i));  
            }
        }
        for(int i=0;i<nums.size();i++)
        {
            arr[i]=nums[i];
        }
        
    }
0
anirbanhaldar6002 weeks ago
Solution With O(n) Time and O(1) Space complexity
Problem StatementThe problem is like, we have a array "arr" of “N” elements and it contains elements within range [1 ... P]. Our task is to report the frequency of elements as
arr[0] -> Frequency of element 1.arr[1] -> Frequency of element 2.arr[2] -> Frequency of element 3....arr[N-1] -> Frequency of element N.
 
Now, if N > P then ignore the frequency of elements from [N ... P].
 
ApproachAs we are using the same array (arr, which contains the input) to store the counts as well, to distinguish between them, we are marking count as negative values or zero. So all positive values are original arr elements and  <= 0  values are frequency of -> (that index + 1).
Now, as we don't have extra space, we start from say index 0. we store the value in a variable (say "next") and make that arr[0] = 0 (which implies, we haven't seen any 1 yet). Next we go the location (next-1) and make arr[next-1] = -1 which means We have seen one value == next. Now, before replacing the value with -1, we will extract the existing value into next and continue this loop until we reach a location which doesn't contain a value but count. Then we decrement that value and break the loop. Next we search for a new starting position for a new chain.
 
Hope this explanation is helpful.
 
void frequencyCount(vector<int>& arr,int N, int P){
   int pos = 0, next, temp;
   while(true){
       while(pos < N && arr[pos] < 0) pos++;
       if(pos == N) break;
       next = arr[pos];
       if(pos == next-1) arr[pos] = -1;
       else if(next > N) arr[pos] = 0;
       else{
           arr[pos] = 0;
           while(0 < next && next <= N){
               temp = arr[next-1];
               if(temp <= 0) arr[next-1]--;
               else arr[next-1] = -1;
               next = temp;
           }
       }
       pos++;
   }
   for(int i = 0; i < N; i++) arr[i] *= -1;
}
(You may think there is nested while loops, then how the time complexity is O(n), but it is O(n) complexity algorithm and those while loops don't depend on each other and both of them are of linear time)
0
dipeshmishra6262 weeks ago
//my unique solution using BST ;)
//space-- O(1)
class Node{   int count,data;   Node left,right;   public Node(int data,int count)   {       this.data=data;       this.count=count;   }}class Solution{   //Function to count the frequency of all elements from 1 to N in the array.   public static void frequencyCount(int arr[], int N, int P)   {       // code here       Node root=null;       for(int i=0;i<N;i++)       {           root=createBST(root,arr[i]);       }       Arrays.fill(arr,0);       inorder(root,arr,N);   }   static Node createBST(Node root,int key)   {       if(root==null)       {           return new Node(key,1);       }       if(key<root.data)       {           root.left=createBST(root.left,key);       }       else if(key>root.data)       {           root.right=createBST(root.right,key);       }       else{       root.count++;       }       return root;   }   static void inorder(Node root,int[] arr,int N)   {       if(root==null)return;       inorder(root.left,arr,N);       if(root.data<=N)       arr[root.data-1]=root.count;       inorder(root.right,arr,N);       return;   }}
0
harshpandeyalfa23 weeks ago
C++
(0.8 sec)
void frequencyCount(vector<int>&arr,int N, int P)   {        unordered_map<int,int> um;       for(int x: arr)       {           if(x<=P)            um[x]++;       }                     unordered_map<int,int> ::iterator it;       for(int i=1;i<=N;i++)       {           it=um.find(i);           if(it == um.end() )           {               arr[i-1]=0;           }           else if(it!=um.end())           {               arr[i-1]=it->second;           }       }   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.