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

08 Mar, 2022
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.  
Traverse the given array and insert every element in the set data structure.Also, find the maximum element in the array. This maximum element will be value N which will represent the size of the set.After traversal of the array, check if the size of the set is equal to N.If the size of the set is equal to N then the array represents a permutation else it doesn’t.
Traverse the given array and insert every element in the set data structure.
Also, find the maximum element in the array. This maximum element will be value N which will represent the size of the set.
After traversal of the array, check if the size of the set is equal to N.
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++
Java
Python3
C#
Javascript
// 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 notbool 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 codeint 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 Program to decide if an// array represents a permutation or notimport java.util.*; class GFG{ // Function to check if an// array represents a permutation or notstatic 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 codepublic 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 Program to decide if an# array represents a permutation or not # Function to check if an# array represents a permutation or notdef 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 codeif __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# Program to decide if an// array represents a permutation or notusing System;using System.Collections.Generic; class GFG{  // Function to check if an// array represents a permutation or notstatic 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 codepublic 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
<script> // JavaScript Program to decide if an// array represents a permutation or not // Function to check if an// array represents a permutation or notfunction 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>
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)
princi singh
SURENDRA_GANGWAR
susmitakundugoaldanga
subham348
anilyogi2801
permutation
Arrays
Hash
Mathematical
Searching
Write From Home
Arrays
Searching
Hash
Mathematical
permutation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Most frequent element in an array