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

In this problem, we need to check whether there exists a permutation of a given array such that each element indicates the number of elements either before or after it in that permutation.

For example, consider the array {2, 1, 3, 3}. A valid permutation is {3, 1, 2, 3} where the first 3 indicates there are three elements after it, 1 indicates there is one element before it, 2 indicates there are two elements before it, and the last 3 indicates there are three elements before it.

Algorithm

The approach uses a frequency map to track available elements and tries to place each position optimally −

checkPermutation(arr, n)
begin
    create frequency map of array elements
    for each position i from 0 to n-1:
        if element i is available (elements before current position)
            use it and decrement frequency
        else if element (n-i-1) is available (elements after current position)
            use it and decrement frequency
        else
            return false (no valid permutation exists)
    return true
end

Example

Here's the implementation to check if a valid permutation exists −

#include <stdio.h>

int checkPermutation(int arr[], int n) {
    int freq_map[100] = {0}; // Assuming elements are within range 0-99
    
    // Count frequency of each element
    for(int i = 0; i < n; i++) {
        if(arr[i] >= 0 && arr[i] < 100) {
            freq_map[arr[i]]++;
        }
    }
    
    // Check if valid permutation is possible
    for(int i = 0; i < n; i++) {
        if(freq_map[i] > 0) { // Element indicating 'i' elements before
            freq_map[i]--;
        } else if(freq_map[n-i-1] > 0) { // Element indicating 'n-i-1' elements after
            freq_map[n-i-1]--;
        } else {
            return 0; // No valid permutation possible
        }
    }
    return 1;
}

int main() {
    int data[] = {3, 2, 3, 1};
    int n = sizeof(data)/sizeof(data[0]);
    
    if(checkPermutation(data, n)) {
        printf("Permutation is present<br>");
    } else {
        printf("Permutation is not present<br>");
    }
    
    return 0;
}
Permutation is present

How It Works

The algorithm works by checking if for each position i in the permutation, we can place an element that represents either:

  • Elements before: An element with value i (indicating i elements before current position)
  • Elements after: An element with value n-i-1 (indicating n-i-1 elements after current position)

If at any position neither option is available in our frequency map, then no valid permutation exists.

Conclusion

This greedy approach efficiently determines if a valid permutation exists by checking position-wise constraints. The time complexity is O(n) and space complexity is O(n) for the frequency mapping.

Updated on: 2026-03-15T10:56:42+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements