Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if the end of the Array can be reached from a given position
Next article icon

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

Last Updated : 05 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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}
Recommended Practice
Left or Right Positioned Array
Try It!

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”.

Implementation:

C++




// 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 n
bool 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 case
int 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




// 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 code
public 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




# 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 n
def 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#




     
// 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
// 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 n
function 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
?>
 
 

Javascript




<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)

 



Next Article
Check if the end of the Array can be reached from a given position

S

Shashank Mishra ( Gullu )
Improve
Article Tags :
  • Arrays
  • DSA
  • permutation
Practice Tags :
  • Arrays
  • permutation

Similar Reads

  • Check if the end of the Array can be reached from a given position
    Given an array arr[] of N positive integers and a number S, the task is to reach the end of the array from index S. We can only move from current index i to index (i + arr[i]) or (i - arr[i]). If there is a way to reach the end of the array then print "Yes" else print "No". Examples: Input: arr[] =
    13 min read
  • Check whether a given array is a k sorted array or not
    Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
    12 min read
  • Check if an Array can be Sorted by picking only the corner Array elements
    Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking
    5 min read
  • Check whether we can sort two arrays by swapping A[i] and B[i]
    Given two arrays, we have to check whether we can sort two arrays in strictly ascending order by swapping A[i] and B[i]. Examples: Input : A[ ]={ 1, 4, 3, 5, 7}, B[ ]={ 2, 2, 5, 8, 9} Output : True After swapping A[1] and B[1], both the arrays are sorted. Input : A[ ]={ 1, 4, 5, 5, 7}, B[ ]={ 2, 2,
    12 min read
  • Check if Array can be rearranged such that arr[i] XOR arr[i+2] is 0
    Given an array arr[] of size N, the task is to check if the array elements can be rearranged in a way such that the bitwise XOR of ith and (i+2)th element is always 0 for any value of i (0 ≤ i < N-2) Examples: Input: arr[] = {1, 1, 2, 2}, N = 4Output: YESExplanation: Rearrange the array like {1,
    8 min read
  • Check whether an array can be fit into another array rearranging the elements in the array
    Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second
    6 min read
  • Check if array can be sorted with one swap
    Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap. Examples: Input : arr[] = {1, 2, 3, 4} Output : YES The array is already sorted Input : arr[] = {3, 2, 1} Output : YES Swap 3 and 1 to get [1, 2, 3] Input : arr[] = {4, 1, 2, 3} Out
    11 min read
  • Search, Insert, and Delete in an Unsorted Array | Array Operations
    In this post, a program to search, insert, and delete operations in an unsorted array is discussed. Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element. Coding implementation of the search operation:[GFGTABS] C++
    15+ min read
  • Check if an array is sorted and rotated
    Given an array arr[] of size n, the task is to return true if it was originally sorted in non-decreasing order and then rotated (including zero rotations). Otherwise, return false. The array may contain duplicates. Examples: Input: arr[] = { 3, 4, 5, 1, 2 }Output: YESExplanation: The above array is
    7 min read
  • Check if an array arr[] can be rearranged such that arr[2 × i + 1] = 2* arr[2 × i] for every ith index
    Given an array arr[] consisting of 2*N integers, the task is to check if it is possible to rearrange the array elements such that arr[2 * i + 1] = 2* arr[2 * i] for every ith index. If it is possible to do so, then print "Yes. Otherwise, print "No". Examples: Input: arr[] = {4, -2, 2, -4}, N = 2Outp
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences