Skip to content
Related Articles
Open in App
Not now

Related Articles

Check if an Array is a permutation of numbers from 1 to N

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 20 Mar, 2023
Improve Article
Save Article

Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. 
 

A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once.

Examples: 

Input: arr[] = {1, 2, 5, 3, 2} 
Output: No 
Explanation: The given array is not a permutation of numbers from 1 to N, because it contains 2 twice, and 4 is missing for the array to represent a permutation of length 5. 

Input: arr[] = {1, 2, 5, 3, 4} 
Output: Yes 
Explanation: 
Given array contains all integers from 1 to 5 exactly once. Hence, it represents a permutation of length 5.  

Naive Approach: Clearly, the given array will represent a permutation of length N only, where N is the length of the array. So we have to search for each element from 1 to N in the given array. If all the elements are found then the array represents a permutation else it does not.
Time Complexity: O(N2
Efficient Approach: 
The above method can be optimized using a set data structure

  1. Traverse the given array and insert every element in the set data structure.
  2. Also, find the maximum element in the array. This maximum element will be value N which will represent the size of the set.
  3. After traversal of the array, check if the size of the set is equal to N.
  4. If the size of the set is equal to N then the array represents a permutation else it doesn’t.

Below is the implementation of the above approach: 

C++




// C++ Program to decide if an
// array represents a permutation or not
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if an
// array represents a permutation or not
bool permutation(int arr[], int n)
{
    // Set to check the count
    // of non-repeating elements
    set<int> hash;
 
    int maxEle = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Insert all elements in the set
        hash.insert(arr[i]);
 
        // Calculating the max element
        maxEle = max(maxEle, arr[i]);
    }
 
    if (maxEle != n)
        return false;
 
    // Check if set size is equal to n
    if (hash.size() == n)
        return true;
 
    return false;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 5, 3, 2 };
    int n = sizeof(arr) / sizeof(int);
 
    if (permutation(arr, n))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    return 0;
}

Java




// Java Program to decide if an
// array represents a permutation or not
import java.util.*;
 
class GFG{
 
// Function to check if an
// array represents a permutation or not
static boolean permutation(int []arr, int n)
{
    // Set to check the count
    // of non-repeating elements
    Set<Integer> hash = new HashSet<Integer>();
 
    int maxEle = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Insert all elements in the set
        hash.add(arr[i]);
 
        // Calculating the max element
        maxEle = Math.max(maxEle, arr[i]);
    }
 
    if (maxEle != n)
        return false;
 
    // Check if set size is equal to n
    if (hash.size() == n)
        return true;
 
    return false;
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 1, 2, 5, 3, 2 };
    int n = arr.length;
 
    if (permutation(arr, n))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by Surendra_Gangwar

Python3




# Python3 Program to decide if an
# array represents a permutation or not
 
# Function to check if an
# array represents a permutation or not
def permutation(arr, n):
     
        # Set to check the count
    # of non-repeating elements
    s = set()
 
    maxEle = 0;
 
    for i in range(n):
   
        # Insert all elements in the set
        s.add(arr[i]);
 
        # Calculating the max element
        maxEle = max(maxEle, arr[i]);
     
    if (maxEle != n):
        return False
 
    # Check if set size is equal to n
    if (len(s) == n):
        return True;
 
    return False;
 
# Driver code
if __name__=='__main__':
 
    arr = [ 1, 2, 5, 3, 2 ]
    n = len(arr)
 
    if (permutation(arr, n)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by Princi Singh

C#




// C# Program to decide if an
// array represents a permutation or not
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to check if an
// array represents a permutation or not
static bool permutation(int []arr, int n)
{
    // Set to check the count
    // of non-repeating elements
    HashSet<int> hash = new HashSet<int>();
  
    int maxEle = 0;
  
    for (int i = 0; i < n; i++) {
  
        // Insert all elements in the set
        hash.Add(arr[i]);
  
        // Calculating the max element
        maxEle = Math.Max(maxEle, arr[i]);
    }
  
    if (maxEle != n)
        return false;
  
    // Check if set size is equal to n
    if (hash.Count == n)
        return true;
  
    return false;
}
  
// Driver code
public static void Main(String []args)
{
    int []arr = { 1, 2, 5, 3, 2 };
    int n = arr.Length;
  
    if (permutation(arr, n))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by Princi Singh

Javascript




<script>
 
// JavaScript Program to decide if an
// array represents a permutation or not
 
// Function to check if an
// array represents a permutation or not
function permutation(arr, n)
{
    // Set to check the count
    // of non-repeating elements
    let hash =  new Set();
   
    let maxEle = 0;
   
    for (let i = 0; i < n; i++) {
   
        // Insert all elements in the set
        hash.add(arr[i]);
   
        // Calculating the max element
        maxEle = Math.max(maxEle, arr[i]);
    }
   
    if (maxEle != n)
        return false;
   
    // Check if set size is equal to n
    if (hash.length == n)
        return true;
   
    return false;
}
 
// Driver Code
     
    let arr = [ 1, 2, 5, 3, 2 ];
    let n = arr.length;
   
    if (permutation(arr, n))
        document.write("Yes");
    else
        document.write("No");
                   
</script>

Output

No

Time Complexity: O(N log N), Since every insert operation in the set is an O(log N) operation. There will be N such operations hence O(N log N).
Auxiliary Space: O(N)

Efficient Approach:-

  • As we have to check all elements from 1 to N in the array
  • So think that if we just sort the array then if the array element will be from 1 to N then the sequence will be like 1,2,3_____,N.
  • So we can just sort the array and can check is all the elements are like 1,2,3,____,N or not.

Implementation:-

C++




// C++ Program to decide if an
// array represents a permutation or not
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if an
// array represents a permutation or not
bool permutation(int arr[], int n)
{
      //sorting the array
      sort(arr,arr+n);
   
      //traversing the array to find if it is a valid permutation ot not
      for(int i=0;i<n;i++)
    {
          //if i+1 element not present
          //or dublicacy is present
          if(arr[i]!=i+1)return false;
    }
   
      return true;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 5, 3, 2 };
    int n = sizeof(arr) / sizeof(int);
 
    if (permutation(arr, n))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    return 0;
}
//This code is contributed by shubhamrajput6156

Java




// Java Program to decide if an
// array represents a permutation or not
import java.util.*;
 
class GFG
{
 
  // Function to check if an
  // array represents a permutation or not
  static boolean permutation(int arr[], int n)
  {
    // sorting the array
    Arrays.sort(arr);
 
    // traversing the array to find if it is a valid permutation ot not
    for(int i = 0; i < n; i++)
    {
      //if i+1 element not present
      //or dublicacy is present
      if(arr[i]!=i+1)return false;
    }
 
    return true;
  }
 
  // Driver Code
  public static void main(String[] args) {
    int arr[] = { 1, 2, 5, 3, 2 };
    int n = arr.length;
 
    if (permutation(arr, n))
      System.out.println("Yes");
    else
      System.out.println("No");
 
    return ;
  }
}
 
// this code is contibuted by bhardwajji

Python3




# Python3 Program to decide if an
# array represents a permutation or not
 
# Function to check if an
# array represents a permutation or not
 
 
def permutation(arr, n):
    # sorting the array
    arr.sort()
 
    # traversing the array to find if it is a valid permutation or not
    for i in range(n):
        # if i+1 element not present
        # or dublicacy is present
        if arr[i] != i + 1:
            return False
 
    return True
 
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 5, 3, 2]
    n = len(arr)
 
    if permutation(arr, n):
        print("Yes")
    else:
        print("No")

C#




// C# Program to decide if an
// array represents a permutation or not
using System;
 
public class GFG
{
    // Function to check if an
    // array represents a permutation or not
    public static bool permutation(int[] arr, int n)
    {
          //sorting the array
          Array.Sort(arr);
 
          //traversing the array to find if it is a valid permutation ot not
          for (int i = 0;i < n;i++)
          {
              //if i+1 element not present
              //or dublicacy is present
              if (arr[i] != i + 1)
              {
                  return false;
              }
          }
 
          return true;
    }
     
    internal static void Main()
    {
        int[] arr = {1, 2, 5, 3, 2};
        int n = arr.Length;
 
        if (permutation(arr, n))
        {
            Console.Write("Yes");
            Console.Write("\n");
        }
        else
        {
            Console.Write("No");
            Console.Write("\n");
        }
    }
}
 
//This code is contributed by bhardwajji

Javascript




// Function to check if an
// array represents a permutation or not
function permutation(arr, n) {
  // sorting the array
  arr.sort();
 
  // traversing the array to find if it is a valid permutation or not
  for (let i = 0; i < n; i++) {
    // if i+1 element not present
    // or dublicacy is present
    if (arr[i] !== i + 1) {
      return false;
    }
  }
 
  return true;
}
 
// Driver code
const arr = [1, 2, 5, 3, 2];
const n = arr.length;
 
if (permutation(arr, n)) {
  console.log("Yes");
} else {
  console.log("No");
}
// This code is Contributed by Shushant Kumar

Output

No

Time Complexity:- O(NLogN)

Space Complexity:- O(1)

Another Efficient Approach: create a boolean array that help in if we already visited that element return False

else  Traverse the Whole array

Below is the implementation of above approach

C++




#include <iostream>
#include <cstring>
 
using namespace std;
 
bool permutation(int arr[], int n) {
    // create a boolean array to keep track of which numbers have been seen before
    bool x[n];
 
    // initialize the boolean array with false values
    memset(x, false, sizeof(x));
 
    // check each number in the array
    for (int i = 0; i < n; i++) {
        // if the number has not been seen before, mark it as seen
        if (x[arr[i] - 1] == false) {
            x[arr[i] - 1] = true;
        }
        // if the number has been seen before, the array does not represent a permutation
        else {
            return false;
        }
    }
 
    // check if all numbers from 1 to n have been seen in the array
    for (int i = 0; i < n; i++) {
        // if a number has not been seen in the array, the array does not represent a permutation
        if (x[i] == false) {
            return false;
        }
    }
 
    // if the array has passed all checks, it represents a permutation
    return true;
}
 
int main() {
    // initialize the array to be checked
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // check if the array represents a permutation
    if (permutation(arr, n)) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
 
    return 0;
}

Python3




# Python code for the above approach
 
# Function to check if an
# array represents a permutation or not
 
# time complexity O(N)
# space O(N)
def permutation(arr, n):
     # crete a bool array that check if the element
    # we traversing are already exist in array or not
    x = [0] * n
    # checking for every element in array
    for i in range(n):
      if x[arr[i] - 1 ] == 0 :
        x[arr[i] - 1] = 1
      else :
        return False
    # for corner cases
    for i in range(n):
      if x[i] == 0 :
        return False
    return True
 
# Drive code
if __name__ == "__main__" :
  arr = [1 , 2 , 3 , 4, 5]
  n = len(arr)
  if (permutation(arr , n)):
    print("YES")
  else :
    print("NO")
      
 
# This code is contributed by Shushant Kumar

Output

YES

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!