Check if an Array is a permutation of numbers from 1 to N
Last Updated :
12 Jul, 2025
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.
Algorithm:
- Initialize a flag variable "isPermutation" to true.
- Initialize a variable "N" to the length of the array.
- Loop through integers from 1 to N:
- Initialize a flag variable "found" to false.
- Loop through the array elements and If the integer "i" is found in the array, set "found" to true and break the loop.
- If "found" is false, set "isPermutation" to false and break the loop.
- If "isPermutation" is true, print "Array represents a permutation".
- Else, print "Array does not represent a permutation".
Below is the implementation of the approach:
C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if an Array is a
// permutation of numbers from 1 to N
bool isPermutation(int arr[], int n) {
// Check for each element from 1 to N in the array
for(int i=1; i<=n; i++) {
bool found = false;
for(int j=0; j<n; j++) {
if(arr[j] == i) {
found = true;
break;
}
}
// If any element is not found, array is not a permutation
if(!found) {
return false;
}
}
// All elements found, array is a permutation
return true;
}
// Driver's code
int main() {
// Input
int arr[] = { 1, 2, 5, 3, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
// Function Call
if(isPermutation(arr, n)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
Java
// Java code for the approach
import java.util.*;
public class GFG {
// Function to check if an Array is a
// permutation of numbers from 1 to N
public static boolean isPermutation(int[] arr, int n)
{
// Check for each element from
// 1 to N in the array
for (int i = 1; i <= n; i++) {
boolean found = false;
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
found = true;
break;
}
}
// If any element is not found,
// array is not a permutation
if (!found) {
return false;
}
}
// All elements found, array
// is a permutation
return true;
}
// Driver's code
public static void main(String[] args)
{
int[] arr = { 1, 2, 5, 3, 2 };
int n = arr.length;
if (isPermutation(arr, n)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Python3
# Function to check if a list is a permutation of numbers from 1 to N
def is_permutation(arr):
n = len(arr)
# Check for each element from 1 to N in the list
for i in range(1, n + 1):
found = False
for j in range(n):
if arr[j] == i:
found = True
break
# If any element is not found, the list is not a permutation
if not found:
return False
# All elements found, the list is a permutation
return True
# Driver's code
arr = [1, 2, 5, 3, 2]
# Function Call
if is_permutation(arr):
print("Yes")
else:
print("No")
C#
using System;
public class GFG {
// Function to check if an Array is a
// permutation of numbers from 1 to N
public static bool IsPermutation(int[] arr, int n)
{
// Check for each element from
// 1 to N in the array
for (int i = 1; i <= n; i++) {
bool found = false;
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
found = true;
break;
}
}
// If any element is not found,
// array is not a permutation
if (!found) {
return false;
}
}
// All elements found, array
// is a permutation
return true;
}
// Driver's code
public static void Main(string[] args)
{
int[] arr = { 1, 2, 5, 3, 2 };
int n = arr.Length;
if (IsPermutation(arr, n)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
// Function to check if an Array is a permutation of numbers from 1 to N
function isPermutation(arr, n) {
// Check for each element from 1 to N in the array
for (let i = 1; i <= n; i++) {
let found = false;
for (let j = 0; j < n; j++) {
if (arr[j] === i) {
found = true;
break;
}
}
// If any element is not found, array is not a permutation
if (!found) {
return false;
}
}
// All elements found, array is a permutation
return true;
}
// Driver's code
const arr = [1, 2, 5, 3, 2];
const n = arr.length;
if (isPermutation(arr, n)) {
console.log("Yes");
} else {
console.log("No");
}
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.
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>
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 contributed 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
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 <cstring>
#include <iostream>
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;
}
Java
import java.util.Arrays;
public class Main {
public static boolean permutation(int[] arr, int n) {
// create a boolean array to keep track of which numbers
// have been seen before
boolean[] x = new boolean[n];
// initialize the boolean array with false values
Arrays.fill(x, false);
// 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;
}
public static void main(String[] args) {
// initialize the array to be checked
int[] arr = { 1, 2, 3, 4, 5 };
int n = arr.length;
// check if the array represents a permutation
if (permutation(arr, n)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
// This code is contributed by shiv1043g
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
C#
using System;
public class Gfg
{
public static bool permutation(int[] arr, int n)
{
// create a boolean array to keep track of which numbers
// have been seen before
bool[] x = new bool[n];
// initialize the boolean array with false values
for (int i = 0; i < n; i++)
{
x[i] = false;
}
// 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;
}
public static void Main()
{
// initialize the array to be checked
int[] arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
// check if the array represents a permutation
if (permutation(arr, n))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
JavaScript
// Function to check if an array represents a permutation or not
// time complexity O(N)
// space O(N)
function permutation(arr, n) {
// create a boolean array to check if the element we're
// traversing already exists in the array or not
let x = new Array(n).fill(false);
// check for every element in array
for (let i = 0; i < n; i++) {
if (x[arr[i] - 1] == false) {
x[arr[i] - 1] = true;
} else {
return false;
}
}
// for corner cases
for (let i = 0; i < n; i++) {
if (x[i] == false) {
return false;
}
}
return true;
}
// Drive code
let arr = [1, 2, 3, 4, 5];
let n = arr.length;
if (permutation(arr, n)) {
console.log("YES");
} else {
console.log("NO");
}
// This code is contributed by shushant kumar
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem