Check if Array elements of given range form a permutation
Last Updated :
26 Apr, 2025
Given an array arr[] consisting of N distinct integers and an array Q[][2] consisting of M queries of the form [L, R], the task for each query is to check if array elements over the range [L, R] forms a permutation or not.
Note: A permutation is a sequence of length N containing each number from 1 to N exactly once. For example, (1), (4, 3, 5, 1, 2) are permutations, and (1, 1), (4, 3, 1) are not.
Examples:
Input: arr[] = {6, 4, 1, 2, 3, 5, 7}, Q[][] = {{2, 4}, {0, 4}, {1, 5}}
Output:
YES
NO
YES
Explanation: Query 1: The elements of the array over the range [2, 4] are {1, 2, 3} which forms a permutation. Hence, print “YES”.
Query 2: The elements of the array over the range [0, 4] are {6, 4, 1, 2} which does not forms an permutation. Hence, print “NO”.
Query 3: The elements of the array over the range [1, 5] are {4, 1, 2, 3, 5}, which form an permutation. Hence, print “YES”.
Input: arr[] = {1, 2, 4, 3, 9}, Q[][] = {{0, 3}, {0, 4}}
Output:
YES
NO
Naive Approach: The basic way to solve the problem is as follows:
Traverse the given array over the range [L, R] for each query and check if every element is present or not from 1 to R - L + 1. This can be done by taking the sum of all elements from L to R if it is equal to the sum of 1 + 2 + 3 + 4 + . . . . + size of subarray [L, R], then print “YES”. Otherwise, print “NO”.
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following idea:
The idea is rather than calculating the sum of elements from L to R for each query precomputation can be done using the prefix sum. For Each query Q sum from L to R can be found in O(1) time using prefix sum.
The sum from 1 + 2 + 3 + 4 + . . . + size of subarray [L, R] can be found using the number theory formula for finding the sum of the first n natural numbers which is n * (n + 1) / 2.
Follow the steps below to solve the problem:
- Initialize an array (say prefix[]) to store the prefix sum of the array
- To fill the prefix sum array, we run through index 1 to N and keep on adding the present element with the previous value in the prefix sum array.
- Traverse the given array of queries Q[] and for each query {L, R}.
- Initiate the size variable and fill with R - L + 1 which is the size of the subarray [L, R].
- Initiate the total_From_1_To_Size variable whose value will fill with n * ( n + 1) / 2.
- Initiate the variable total_From_L_To_R whose value will be found using precomputed array prefix[].
- If total_From_L_To_R and total_From_1_To_Size are equal then print "YES" else print "NO".
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if the given range
// of queries form an Permutation or not
// in the given array arr[]
void findPermutation(int arr[], int N,
int Q[][2], int M)
{
// Precomputation array
// stores the sum of all ranges
// for any L to R
int prefix[N + 1] = { 0 };
// Iterates over the range [1, N]
for (int i = 1; i <= N; i++) {
// Finding prefix sum of
// given array
prefix[i] = prefix[i - 1] + arr[i - 1];
}
// Traverse the given queries
for (int i = 0; i < M; i++) {
// Stores range L to R for
// each query
int L = Q[i][0], R = Q[i][1];
// Size variable stores size of
// [L, R] range
int size = R - L + 1;
// Stores total from 1 to size of
// range [L, R]
int total_From_1_To_Size
= size * (size + 1) / 2;
// Stores total sum from L to R
// of Array
int total_From_L_To_R
= prefix[R] - prefix[L - 1];
// If total from 1 to size is equal
// to total from L to R then print
// yes
if (total_From_L_To_R == total_From_1_To_Size) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
// Driver Code
int main()
{
int arr[] = { 6, 4, 1, 2, 3, 5, 7 };
int Q[][2] = { { 3, 5 }, { 1, 5 }, { 2, 6 } };
int N = sizeof(arr) / sizeof(arr[0]);
int M = sizeof(Q) / sizeof(Q[0]);
// Function Call
findPermutation(arr, N, Q, M);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
class GFG {
// Function to check if the given range
// of queries form an Permutation or not
// in the given array arr[]
public static void findPermutation(int arr[], int N,
int Q[][], int M)
{
// Precomputation array
// stores the sum of all ranges
// for any L to R
int prefix[] = new int[N + 1];
// Iterates over the range [1, N]
for (int i = 1; i <= N; i++) {
// Finding prefix sum of
// given array
prefix[i] = prefix[i - 1] + arr[i - 1];
}
// Traverse the given queries
for (int i = 0; i < M; i++) {
// Stores range L to R for
// each query
int L = Q[i][0], R = Q[i][1];
// Size variable stores size of
// [L, R] range
int size = R - L + 1;
// Stores total from 1 to size of
// range [L, R]
int total_From_1_To_Size
= size * (size + 1) / 2;
// Stores total sum from L to R
// of Array
int total_From_L_To_R
= prefix[R] - prefix[L - 1];
// If total from 1 to size is equal
// to total from L to R then print
// yes
if (total_From_L_To_R == total_From_1_To_Size) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 6, 4, 1, 2, 3, 5, 7 };
int Q[][] = { { 3, 5 }, { 1, 5 }, { 2, 6 } };
int N = arr.length;
int M = Q.length;
// Function Call
findPermutation(arr, N, Q, M);
}
}
// This code is contributed by Rohit Pradhan
Python3
# Python code to implement the approach
# Function to check if the given range
# of queries form an Permutation or not
# in the given array arr[]
def findPermutation(arr, N, Q, M) :
# Precomputation array
# stores the sum of all ranges
# for any L to R
prefix = [0] * (N + 1)
# Iterates over the range [1, N]
for i in range(1, N+1):
# Finding prefix sum of
# given array
prefix[i] = prefix[i - 1] + arr[i - 1]
# Traverse the given queries
for i in range(0, M):
# Stores range L to R for
# each query
L = Q[i][0]
R = Q[i][1]
# Size variable stores size of
# [L, R] range
size = R - L + 1
# Stores total from 1 to size of
# range [L, R]
total_From_1_To_Size = size * (size + 1) // 2
# Stores total sum from L to R
# of Array
total_From_L_To_R = prefix[R] - prefix[L - 1]
# If total from 1 to size is equal
# to total from L to R then print
# yes
if (total_From_L_To_R == total_From_1_To_Size) :
print("YES")
else :
print("NO")
# Driver Code
if __name__ == "__main__":
arr = [ 6, 4, 1, 2, 3, 5, 7 ]
Q = [[ 3, 5 ], [ 1, 5 ], [ 2, 6]]
N = len(arr)
M = len(Q)
# Function Call
findPermutation(arr, N, Q, M)
# This code is contributed by sanjoy_62.
C#
// C# code to implement the approach
using System;
public class GFG {
// Function to check if the given range
// of queries form an Permutation or not
// in the given array arr[]
public static void findPermutation(int[] arr, int N,
int[, ] Q, int M)
{
// Precomputation array
// stores the sum of all ranges
// for any L to R
int[] prefix = new int[N + 1];
// Iterates over the range [1, N]
for (int i = 1; i <= N; i++) {
// Finding prefix sum of
// given array
prefix[i] = prefix[i - 1] + arr[i - 1];
}
// Traverse the given queries
for (int i = 0; i < M; i++) {
// Stores range L to R for
// each query
int L = Q[i, 0], R = Q[i, 1];
// Size variable stores size of
// [L, R] range
int size = R - L + 1;
// Stores total from 1 to size of
// range [L, R]
int total_From_1_To_Size
= size * (size + 1) / 2;
// Stores total sum from L to R
// of Array
int total_From_L_To_R
= prefix[R] - prefix[L - 1];
// If total from 1 to size is equal
// to total from L to R then print
// yes
if (total_From_L_To_R == total_From_1_To_Size) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
}
static public void Main()
{
// Code
int[] arr = { 6, 4, 1, 2, 3, 5, 7 };
int[, ] Q = { { 3, 5 }, { 1, 5 }, { 2, 6 } };
int N = arr.Length;
int M = Q.GetLength(0);
// Function Call
findPermutation(arr, N, Q, M);
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// JavaScript code to implement the approach
// Function to check if the given range
// of queries form an Permutation or not
// in the given array arr[]
const findPermutation = (arr, N, Q, M) => {
// Precomputation array
// stores the sum of all ranges
// for any L to R
let prefix = new Array(N + 1).fill(0);
// Iterates over the range [1, N]
for (let i = 1; i <= N; i++) {
// Finding prefix sum of
// given array
prefix[i] = prefix[i - 1] + arr[i - 1];
}
// Traverse the given queries
for (let i = 0; i < M; i++) {
// Stores range L to R for
// each query
let L = Q[i][0], R = Q[i][1];
// Size variable stores size of
// [L, R] range
let size = R - L + 1;
// Stores total from 1 to size of
// range [L, R]
let total_From_1_To_Size
= size * parseInt((size + 1) / 2);
// Stores total sum from L to R
// of Array
let total_From_L_To_R
= prefix[R] - prefix[L - 1];
// If total from 1 to size is equal
// to total from L to R then print
// yes
if (total_From_L_To_R == total_From_1_To_Size) {
console.log("YES<br/>");
}
else {
console.log("NO<br/>");
}
}
}
// Driver Code
let arr = [6, 4, 1, 2, 3, 5, 7];
let Q = [[3, 5], [1, 5], [2, 6]];
let N = arr.length;
let M = Q.length;
// Function Call
findPermutation(arr, N, Q, M);
// This code is contributed by rakeshsahni
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Using Sorting in python:
Approach:
Define a function is_permutation that takes three arguments: arr, left, and right.
Extract the range from the array arr using the left and right indices.
Sort the range using the .sort() method.
Check if the sorted range forms a permutation by iterating over it and comparing each element to its expected value (i.e., i+1 where i is the index of the element in the range).
If any element does not match its expected value, return "NO".
If all elements match their expected values, return "YES".
Define the array arr and the queries queries.
Iterate over the queries and call the is_permutation function for each query, passing in the relevant indices.
Print the result of each query.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
string is_permutation(vector<int>& arr, int left, int right)
{
// Extract the range from the array
vector<int> range_arr(arr.begin() + left,
arr.begin() + right + 1);
// Sort the range
sort(range_arr.begin(), range_arr.end());
// Check if the sorted range forms a permutation
for (int i = 0; i < range_arr.size(); i++) {
if (range_arr[i] != i + 1) {
return "NO";
}
}
return "YES";
}
int main()
{
vector<int> arr = { 1, 2, 4, 3, 9 };
vector<vector<int> > queries = { { 0, 3 }, { 0, 4 } };
for (vector<int>& query : queries) {
cout << is_permutation(arr, query[0], query[1])
<< endl;
}
return 0;
}
Java
//Java program for the above approach
import java.util.Arrays;
public class Main {
public static String isPermutation(int[] arr, int left, int right) {
// extract the range from the array
int[] rangeArr = Arrays.copyOfRange(arr, left, right + 1);
// sort the range
Arrays.sort(rangeArr);
// check if the sorted range forms a permutation
for (int i = 0; i < rangeArr.length; i++) {
if (rangeArr[i] != i + 1) {
return "NO";
}
}
return "YES";
}
//Driver Code
public static void main(String[] args) {
int[] arr = {1, 2, 4, 3, 9};
int[][] queries = {{0, 3}, {0, 4}};
for (int[] query : queries) {
System.out.println(isPermutation(arr, query[0], query[1]));
}
}
}
Python3
def is_permutation(arr, left, right):
# extract the range from the array
range_arr = arr[left:right+1]
# sort the range
range_arr.sort()
# check if the sorted range forms a permutation
for i in range(len(range_arr)):
if range_arr[i] != i+1:
return "NO"
return "YES"
arr = [1, 2, 4, 3, 9]
queries = [[0, 3], [0, 4]]
for query in queries:
print(is_permutation(arr, query[0], query[1]))
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string IsPermutation(List<int> arr, int left, int right)
{
// Extract the range from the array
List<int> range_arr = arr.GetRange(left, right - left + 1);
// Sort the range
range_arr.Sort();
// Check if the sorted range forms a permutation
for (int i = 0; i < range_arr.Count; i++)
{
if (range_arr[i] != i + 1)
{
return "NO";
}
}
return "YES";
}
// Driver code
static void Main(string[] args)
{
List<int> arr = new List<int> { 1, 2, 4, 3, 9 };
List<List<int>> queries = new List<List<int>> { new List<int> { 0, 3 }, new List<int> { 0, 4 } };
foreach (List<int> query in queries)
{
Console.WriteLine(IsPermutation(arr, query[0], query[1]));
}
}
}
JavaScript
function isPermutation(arr, left, right) {
// Extract the range from the array
const rangeArr = arr.slice(left, right + 1);
// Sort the range
rangeArr.sort((a, b) => a - b);
// Check if the sorted range forms a permutation
for (let i = 0; i < rangeArr.length; i++) {
if (rangeArr[i] !== i + 1) {
return "NO";
}
}
return "YES";
}
const arr = [1, 2, 4, 3, 9];
const queries = [[0, 3], [0, 4]];
for (const query of queries) {
console.log(isPermutation(arr, query[0], query[1]));
}
Time Complexity: O(n*log(n)) for each query
Auxiliary Space: O(n) for storing the sorted range
Similar Reads
Check if Array elements in given range form Permutation by performing given updates
Given an array arr[] consisting of N distinct integers and a 2d array Q[][3] consisting of M queries of the 2 types whose operations are as follows: [1, P, X] update position P with X. [2, L, R] check if array elements over the range [L, R] forms a permutation or not. For each query of the second ty
15+ min read
Count of subarrays which forms a permutation from given Array elements
Given an array A[] consisting of integers [1, N], the task is to count the total number of subarrays of all possible lengths x (1 ? x ? N), consisting of a permutation of integers [1, x] from the given array. Examples: Input: A[] = {3, 1, 2, 5, 4} Output: 4 Explanation: Subarrays forming a permutati
6 min read
Check if an array contains all elements of a given range
An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range. Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5Output : YesInput : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6Output : NoRec
15+ min read
Check if given Array can be made a permutation of 1 to N by reducing elements by half
Given an array nums[] of size N, the task is to check whether the given array can be converted into a permutation of 1 to N after performing given operations any number of times (may be 0). An operation is defined as: Pick any element of the array say 'x', and replace it with 'x/2'. Note: In a permu
6 min read
Check if a symmetric plus is possible from the elements of the given array
Given an array arr[] of N elements, the task is to check whether asymmetric plus is possible with the elements of the given array.A square symmetric plus is of the form: Z Y Z Y X Y Z Y Z Note that all the elements of the array must be used in forming the square. Examples: Input: arr[] = {1, 2, 1, 1
6 min read
Permute the elements of an array following given order
A permutation is a rearrangement of members of a sequence into a new sequence. For example, there are 24 permutations of [a, b, c, d]. Some of them are [b, a, d, c], [d, a, b, c] and [a, d, b, c]. A permutation can be specified by an array P[] where P[i] represents the location of the element at ind
7 min read
Print k different sorted permutations of a given array
Given an array arr[] containing N integers, the task is to print k different permutations of indices such that the values at those indices form a non-decreasing sequence. Print -1 if it is not possible. Examples: Input: arr[] = {1, 3, 3, 1}, k = 3 Output: 0 3 1 2 3 0 1 2 3 0 2 1 For every permutatio
8 min read
Check if all array elements can be converted to K using given operations
Given an integer array arr of size N and an integer K, the task is to make all elements of the array equal to K using the following operations: Choose an arbitrary subarray [l....r] of the input arrayReplace all values of this subarray equal to the [((r - l) + 2) / 2]th value in sorted subarray [l..
9 min read
Check if it is possible form a permutation by dividing elements by K
Given an array, arr[] of size N, and an integer K, the task is to check if it is possible to form a permutation from 1 to N, where you can replace arr[i] by arr[i] / K any number of times. Examples: Input: arr[] = [1, 8, 25, 2], K = 2Output: YesExplanation: Replace 8 with â8 / 2â = 4, then arr = [1,
7 min read
Check if Array Elemnts can be Made Equal with Given Operations
Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
6 min read