srijan44

frequencies of array O(1) space

Apr 22nd, 2021
996
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×