A permutation where each element indicates either number of elements before or after it?

CServer Side ProgrammingProgramming

In this section we will see one problem. Here n elements are given in an array. We have to check whether there is a permutation of that array exists, such that each element indicates the number of elements present either before or after it.

Suppose the array elements are {2, 1, 3, 3}. The appropriate permutation is like {3, 1, 2, 3}. Here the first 3 is indicating there are three elements next of it, the 1 indicates there is only one element before this. The 2 indicates there are two elements before it and the last 3 indicates that there are three elements before it.

Algorithm

checkPermutation(arr, n)

begin
   define a hashmap to hold frequencies. The key and value are of integer type of the map.
   for each element e in arr, do
      increase map[e] by 1
   done
   for i := 0 to n-1, do
      if map[i] is non-zero, then
         decrease map[i] by 1
      else if map[n-i-1] is non-zero, then
         decrease map[n-i-1] by 1
      else
         return false
      end if
   done
   return true
end

Example

 Live Demo

#include<iostream>
#include<map>
using namespace std;
bool checkPermutation(int arr[], int n) {
   map<int, int> freq_map;
   for(int i = 0; i < n; i++){ //get the frequency of each number
      freq_map[arr[i]]++;
   }
   for(int i = 0; i < n; i++){
      if(freq_map[i]){ //count number of elements before current element
         freq_map[i]--;
      } else if(freq_map[n-i-1]){ //count number of elements after current element
         freq_map[n-i-1]--;
      } else {
         return false;
      }
   }
   return true;
}
main() {
   int data[] = {3, 2, 3, 1};
   int n = sizeof(data)/sizeof(data[0]);
   if(checkPermutation(data, n)){
      cout << "Permutation is present";
   } else {
      cout << "Permutation is not present";
   }
}

Output

Permutation is present
raja
Published on 26-Jul-2019 06:19:01
Advertisements