Advertisement
srijan44

frequencies of array O(1) space

Apr 22nd, 2021
1,073
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main(){
  5.  
  6.     int n;
  7.     cin >> n;
  8.  
  9.     int arr[n];
  10.     for(int i=0;i<n;i++){
  11.         cin >> arr[i];
  12.     }
  13.  
  14.     int i=0;
  15.     while(i<n){
  16.  
  17.         // element is already processed nothing to do
  18.         if(arr[i]<=0){
  19.             i++;
  20.             continue;
  21.         }
  22.         int e=arr[i]-1;
  23.         if(arr[e] > 0){
  24.             arr[i] = arr[e];
  25.             arr[e] = -1;
  26.         }
  27.         else{
  28.             arr[e]--;
  29.  
  30.             // initialise it bcoz the element i+1 is not seen so far
  31.             arr[i] = 0;
  32.             i++;
  33.         }
  34.     }
  35.  
  36.     for(int i=0;i<n;i++){
  37.         arr[i] = abs(arr[i]);
  38.         cout << arr[i] << " ";
  39.     }
  40.  
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement