Check if an array can be Arranged in Left or Right Positioned Array - GeeksforGeeks

20 Apr, 2021
Given an array arr[] of size n>4, the task is to check whether the given array can be arranged in the form of Left or Right positioned array? Left or Right Positioned Array means each element in the array is equal to the number of elements to its left or number of elements to its right.Examples :  
Input  : arr[] = {1, 3, 3, 2}
Output : "YES"  
This array has one such arrangement {3, 1, 2, 3}. 
In this arrangement, first element '3' indicates 
that three numbers are after it, the 2nd element 
'1' indicates that one number is before it, the 
3rd element '2' indicates that two elements are 
before it.

Input : arr[] = {1, 6, 5, 4, 3, 2, 1}
Output: "NO"
// No such arrangement is possible

Input : arr[] = {2, 0, 1, 3}
Output: "YES"
// Possible arrangement is {0, 1, 2, 3}

Input : arr[] = {2, 1, 5, 2, 1, 5}
Output: "YES"
// Possible arrangement is {5, 1, 2, 2, 1, 5}
 
A simple solution is to generate all possible arrangements (see this article) and check for the Left or Right Positioned Array condition, if each element in the array satisfies the condition then “YES” else “NO”. Time complexity for this approach is O(n*n! + n), n*n! to generate all arrangements and n for checking the condition using temporary array.An efficient solution for this problem needs little bit observation and pen-paper work. To satisfy the Left or Right Positioned Array condition all the numbers in the array should either be equal to index, i or (n-1-i) and arr[i] < n. So we create an visited[] array of size n and initialize its element with 0. Then we traverse array and follow given steps : 
If visited[arr[i]] = 0 then make it 1, which checks for the condition that number of elements on the left side of array arr[0]...arr[i-1] is equal to arr[i].
Else make visited[n-arr[i]-1] = 1, which checks for the condition that number of elements on the right side of array arr[i+1]...arr[n-1] is equal to arr[i].
Now traverse visited[] array and if all the elements of visited[] array become 1 that means arrangement is possible “YES” else “NO”.
 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if an array can be arranged// to left or right positioned array.#include<bits/stdc++.h>using namespace std; // Function to check Left or Right Positioned// Array.// arr[] is array of n elements// visited[] is boolean array of size nbool leftRight(int arr[],int n){    // Initially no element is placed at any position    int visited[n] = {0};     // Traverse each element of array    for (int i=0; i<n; i++)    {        // Element must be smaller than n.        if (arr[i] < n)        {            // Place "arr[i]" at position "i"            // or at position n-arr[i]-1            if (visited[arr[i]] == 0)                visited[arr[i]] = 1;            else                visited[n-arr[i]-1] = 1;        }    }     // All positions must be occupied    for (int i=0; i<n; i++)        if (visited[i] == 0)            return false;     return true;} // Driver program to test the caseint main(){    int arr[] = {2, 1, 5, 2, 1, 5};    int n = sizeof(arr)/sizeof(arr[0]);    if (leftRight(arr, n) == true)        cout << "YES";    else        cout << "NO";    return 0;}
// Java program to check if an array// can be arranged to left or// right positioned array. class GFG {         // Function to check Left or    // Right Positioned Array.    // arr[] is array of n elements    // visited[] is boolean array of size n    static boolean leftRight(int arr[], int n) {         // Initially no element is    // placed at any position    int visited[] = new int[n];     // Traverse each element of array    for (int i = 0; i < n; i++) {             // Element must be smaller than n.    if (arr[i] < n) {                 // Place "arr[i]" at position "i"        // or at position n-arr[i]-1        if (visited[arr[i]] == 0)        visited[arr[i]] = 1;        else        visited[n - arr[i] - 1] = 1;    }    }     // All positions must be occupied    for (int i = 0; i < n; i++)    if (visited[i] == 0)        return false;     return true;} // Driver codepublic static void main(String[] args){    int arr[] = {2, 1, 5, 2, 1, 5};    int n = arr.length;    if (leftRight(arr, n) == true)    System.out.print("YES");    else    System.out.print("NO");}} // This code is contributed by Anant Agarwal.
# Python3 program to check# if an array can be arranged# to left or right positioned array. # Function to check Left# or Right Positioned# Array.# arr[] is array of n elements# visited[] is boolean array of size ndef leftRight(arr,n):     # Initially no element    # is placed at any position    visited=[]    for i in range(n+1):        visited.append(0)      # Traverse each element of array    for i in range(n):             # Element must be smaller than n.        if (arr[i] < n):                     # Place "arr[i]" at position "i"            # or at position n-arr[i]-1            if (visited[arr[i]] == 0):                visited[arr[i]] = 1            else:                visited[n-arr[i]-1] = 1      # All positions must be occupied    for i in range(n):        if (visited[i] == 0):            return False      return True     # Driver code arr = [2, 1, 5, 2, 1, 5]n = len(arr) if (leftRight(arr, n) == True):    print("YES")else:    print("NO") # This code is contributed# by Anant Agarwal.
     // C# program to check if an array// can be arranged to left or// right positioned array.using System;public class GFG {         // Function to check Left or        // Right Positioned Array.        // arr[] is array of n elements        // visited[] is boolean array of size n        static bool leftRight(int []arr, int n) {         // Initially no element is        // placed at any position        int []visited = new int[n];         // Traverse each element of array        for (int i = 0; i < n; i++) {         // Element must be smaller than n.        if (arr[i] < n) {             // Place "arr[i]" at position "i"            // or at position n-arr[i]-1            if (visited[arr[i]] == 0)            visited[arr[i]] = 1;            else            visited[n - arr[i] - 1] = 1;        }        }         // All positions must be occupied        for (int i = 0; i < n; i++)        if (visited[i] == 0)            return false;         return true;    }     // Driver code    public static void Main()    {        int []arr = {2, 1, 5, 2, 1, 5};        int n = arr.Length;        if (leftRight(arr, n) == true)        Console.WriteLine("YES");        else        Console.WriteLine("NO");    }}// This code is contributed by PrinciRaj1992
<?php// PHP program to check if an// array can be arranged to// left or right positioned array. // Function to check Left or// Right Positioned Array.// arr[] is array of n elements// visited[] is boolean array of size nfunction leftRight($arr, $n){    // Initially no element is    // placed at any position    $visited[$n] = array(0);     // Traverse each element of array    for ($i = 0; $i < $n; $i++)    {        // Element must be smaller than n.        if ($arr[$i] < $n)        {            // Place "arr[i]" at position "i"            // or at position n-arr[i]-1                $visited[$arr[$i]] = 1;                $visited[$n - $arr[$i] - 1] = 1;        }    }     // All positions must be occupied    for ($i = 0; $i < $n; $i++)        if ($visited[$i] == 0)            return false;     return true;} // Driver Code$arr = array(2, 1, 5, 2, 1, 5);$n = sizeof($arr);if (leftRight($arr, $n) == true)    echo "YES";else    echo "NO"; // This code is contributed by ajit?>
<script>     // Javascript program to check if an array    // can be arranged to left or    // right positioned array.         // Function to check Left or    // Right Positioned Array.    // arr[] is array of n elements    // visited[] is boolean array of size n    function leftRight(arr, n) {           // Initially no element is        // placed at any position        let visited = new Array(n);           // Traverse each element of array        for (let i = 0; i < n; i++) {             // Element must be smaller than n.          if (arr[i] < n) {               // Place "arr[i]" at position "i"              // or at position n-arr[i]-1              if (visited[arr[i]] == 0)                  visited[arr[i]] = 1;              else                  visited[n - arr[i] - 1] = 1;          }        }           // All positions must be occupied        for (let i = 0; i < n; i++)          if (visited[i] == 0)              return false;           return true;    }         let arr = [2, 1, 5, 2, 1, 5];    let n = arr.length;    if (leftRight(arr, n) == true)      document.write("YES");    else      document.write("NO");       </script>
Output : 
"YES"
Time Complexity : O(n) Auxiliary Space : O(n)This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
princiraj1992
divyesh072019
permutation
Arrays
Arrays
permutation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Subset Sum Problem | DP-25
Array of Strings in C++ (5 Different Ways to Create)