Check if Array elements of given range form a permutation
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++
#include <bits/stdc++.h>
using namespace std;
void findPermutation( int arr[], int N,
int Q[][2], int M)
{
int prefix[N + 1] = { 0 };
for ( int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
for ( int i = 0; i < M; i++) {
int L = Q[i][0], R = Q[i][1];
int size = R - L + 1;
int total_From_1_To_Size
= size * (size + 1) / 2;
int total_From_L_To_R
= prefix[R] - prefix[L - 1];
if (total_From_L_To_R == total_From_1_To_Size) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
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]);
findPermutation(arr, N, Q, M);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void findPermutation( int arr[], int N,
int Q[][], int M)
{
int prefix[] = new int [N + 1 ];
for ( int i = 1 ; i <= N; i++) {
prefix[i] = prefix[i - 1 ] + arr[i - 1 ];
}
for ( int i = 0 ; i < M; i++) {
int L = Q[i][ 0 ], R = Q[i][ 1 ];
int size = R - L + 1 ;
int total_From_1_To_Size
= size * (size + 1 ) / 2 ;
int total_From_L_To_R
= prefix[R] - prefix[L - 1 ];
if (total_From_L_To_R == total_From_1_To_Size) {
System.out.println( "YES" );
}
else {
System.out.println( "NO" );
}
}
}
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;
findPermutation(arr, N, Q, M);
}
}
|
Python3
def findPermutation(arr, N, Q, M) :
prefix = [ 0 ] * (N + 1 )
for i in range ( 1 , N + 1 ):
prefix[i] = prefix[i - 1 ] + arr[i - 1 ]
for i in range ( 0 , M):
L = Q[i][ 0 ]
R = Q[i][ 1 ]
size = R - L + 1
total_From_1_To_Size = size * (size + 1 ) / / 2
total_From_L_To_R = prefix[R] - prefix[L - 1 ]
if (total_From_L_To_R = = total_From_1_To_Size) :
print ( "YES" )
else :
print ( "NO" )
if __name__ = = "__main__" :
arr = [ 6 , 4 , 1 , 2 , 3 , 5 , 7 ]
Q = [[ 3 , 5 ], [ 1 , 5 ], [ 2 , 6 ]]
N = len (arr)
M = len (Q)
findPermutation(arr, N, Q, M)
|
C#
using System;
public class GFG {
public static void findPermutation( int [] arr, int N,
int [, ] Q, int M)
{
int [] prefix = new int [N + 1];
for ( int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
for ( int i = 0; i < M; i++) {
int L = Q[i, 0], R = Q[i, 1];
int size = R - L + 1;
int total_From_1_To_Size
= size * (size + 1) / 2;
int total_From_L_To_R
= prefix[R] - prefix[L - 1];
if (total_From_L_To_R == total_From_1_To_Size) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
}
static public void Main()
{
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);
findPermutation(arr, N, Q, M);
}
}
|
Javascript
const findPermutation = (arr, N, Q, M) => {
let prefix = new Array(N + 1).fill(0);
for (let i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
for (let i = 0; i < M; i++) {
let L = Q[i][0], R = Q[i][1];
let size = R - L + 1;
let total_From_1_To_Size
= size * parseInt((size + 1) / 2);
let total_From_L_To_R
= prefix[R] - prefix[L - 1];
if (total_From_L_To_R == total_From_1_To_Size) {
console.log( "YES<br/>" );
}
else {
console.log( "NO<br/>" );
}
}
}
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;
findPermutation(arr, N, Q, M);
|
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)
{
vector< int > range_arr(arr.begin() + left,
arr.begin() + right + 1);
sort(range_arr.begin(), range_arr.end());
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
import java.util.Arrays;
public class Main {
public static String isPermutation( int [] arr, int left, int right) {
int [] rangeArr = Arrays.copyOfRange(arr, left, right + 1 );
Arrays.sort(rangeArr);
for ( int i = 0 ; i < rangeArr.length; i++) {
if (rangeArr[i] != i + 1 ) {
return "NO" ;
}
}
return "YES" ;
}
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):
range_arr = arr[left:right + 1 ]
range_arr.sort()
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)
{
List< int > range_arr = arr.GetRange(left, right - left + 1);
range_arr.Sort();
for ( int i = 0; i < range_arr.Count; i++)
{
if (range_arr[i] != i + 1)
{
return "NO" ;
}
}
return "YES" ;
}
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) {
const rangeArr = arr.slice(left, right + 1);
rangeArr.sort((a, b) => a - b);
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
Last Updated :
17 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...