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

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.


checkPermutation(arr, n)

   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
   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
         return false
      end if
   return true


 Live Demo

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
   for(int i = 0; i < n; i++){
      if(freq_map[i]){ //count number of elements before current element
      } else if(freq_map[n-i-1]){ //count number of elements after current element
      } 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";


Permutation is present