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 array can be sorted by swapping adjacent elements of opposite parity
Next article icon

Check if an Array can be Sorted by picking only the corner Array elements

Last Updated : 29 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 elements from the array and placing in the sorted array are as follows: 
{2, 3, 4, 10, 4, 3, 1} -> {1} 
{2, 3, 4, 10, 4, 3} -> {1, 2} 
{3, 4, 10, 4, 3} -> {1, 2, 3} 
{4, 10, 4, 3} -> {1, 2, 3, 3} 
{4, 10, 4} -> {1, 2, 3, 3, 4} 
{10, 4} -> {1, 2, 3, 3, 4, 4} 
{10} -> {1, 2, 3, 3, 4, 4, 10}
Input: a[] = {2, 4, 2, 3} 
Output: No 
 

Approach: To solve the problem, we need to use a concept similar to Bitonic Sequence.Follow the below steps to solve the problem:

  • Traverse the array and check if the sequence of array elements is decreasing, i.e. if the next element is smaller than previous element, then all the remaining elements should be decreasing or equal as well.
  • That is, if the sequence is non-increasing, non-decreasing or non-decreasing followed by non-increasing, only then the array can be sorted by the given operations.

Below is implementation of above approach:

C++
// C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std;  // Function to check if an array can // be sorted using given operations bool check(int arr[], int n) {     int i, g;     g = 0;     for (i = 1; i < n; i++) {          // If sequence becomes increasing         // after an already non-decreasing to         // non-increasing pattern         if (arr[i] - arr[i - 1] > 0 && g == 1)             return false;          // If a decreasing pattern is observed         if (arr[i] - arr[i - 1] < 0)             g = 1;     }     return true; }  // Driver Code int main() {      int arr[] = { 2, 3, 4, 10, 4, 3, 1 };     int n = sizeof(arr) / sizeof(int);     if (check(arr, n) == true)         cout << "Yes"                 "\n";     else         cout << "No"              << "\n";      return 0; } 
Java
// Java program to implement // the above approach class GFG{  // Function to check if an array can // be sorted using given operations static boolean check(int arr[], int n)  {     int i, g;     g = 0;      for(i = 1; i < n; i++)     {                  // If sequence becomes increasing         // after an already non-decreasing to         // non-increasing pattern         if (arr[i] - arr[i - 1] > 0 && g == 1)             return false;          // If a decreasing pattern is observed         if (arr[i] - arr[i - 1] < 0)             g = 1;     }     return true; }  // Driver Code public static void main(String[] args)  {     int arr[] = { 2, 3, 4, 10, 4, 3, 1 };     int n = arr.length;          if (check(arr, n) == true)     {         System.out.println("Yes");     } else     {         System.out.println("No");     } } }  // This code is contributed by rutvik_56 
Python3
# Python3 program to implement # the above approach  # Function to check if an array can  # be sorted using given operations def check(arr, n):      g = 0          for i in range(1, n):          # If sequence becomes increasing         # after an already non-decreasing to         # non-increasing pattern         if(arr[i] - arr[i - 1] > 0 and g == 1):             return False          # If a decreasing pattern is observed         if(arr[i] - arr[i] < 0):             g = 1      return True  # Driver Code arr = [ 2, 3, 4, 10, 4, 3, 1 ] n = len(arr)  if(check(arr, n) == True):     print("Yes") else:     print("No")  # This code is contributed by Shivam Singh 
C#
// C# program to implement // the above approach using System; class GFG{  // Function to check if an array can // be sorted using given operations static bool check(int []arr, int n)  {     int i, g;     g = 0;      for(i = 1; i < n; i++)     {                  // If sequence becomes increasing         // after an already non-decreasing to         // non-increasing pattern         if (arr[i] - arr[i - 1] > 0 && g == 1)             return false;          // If a decreasing pattern is observed         if (arr[i] - arr[i - 1] < 0)             g = 1;     }     return true; }  // Driver Code public static void Main(String[] args)  {     int []arr = { 2, 3, 4, 10, 4, 3, 1 };     int n = arr.Length;          if (check(arr, n) == true)     {         Console.WriteLine("Yes");     } else     {         Console.WriteLine("No");     } } }  // This code is contributed by sapnasingh4991 
JavaScript
<script> // Javascript Program to implement // the above approach  // Function to check if an array can // be sorted using given operations function check(arr, n) {     var i, g;     g = 0;     for (i = 1; i < n; i++) {          // If sequence becomes increasing         // after an already non-decreasing to         // non-increasing pattern         if (arr[i] - arr[i - 1] > 0 && g == 1)             return false;          // If a decreasing pattern is observed         if (arr[i] - arr[i - 1] < 0)             g = 1;     }     return true; }  // Driver Code var arr = [ 2, 3, 4, 10, 4, 3, 1 ]; var n = arr.length; if (check(arr, n) == true)     document.write( "Yes"+             "<br>"); else     document.write( "No"          + "<br>");  // This code is contributed by noob2000. </script>   

 
 


Output: 
Yes

 


 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 


 


Next Article
Check if array can be sorted by swapping adjacent elements of opposite parity

V

varuntak22
Improve
Article Tags :
  • Greedy
  • Pattern Searching
  • Searching
  • Sorting
  • Mathematical
  • DSA
  • Arrays
  • bitonic
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Pattern Searching
  • Searching
  • Sorting

Similar Reads

  • Check if all array elements can be removed by the given operations
    Given an array arr[] containing distinct elements, the task is to check if all array elements can be removed by the selecting any two adjacent indices such that arr[i] < arr[i+1] and removing one of the two elements or both at each step. If it is possible, then print "Yes". Otherwise, print "No".
    4 min read
  • Check if an array of pairs can be sorted by swapping pairs with different first elements
    Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
    11 min read
  • Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array
    Given an array A[] of size N and a binary array B[] of size N, the task is to check if the array A[] can be converted into a sorted array by swapping pairs (A[i], A[j]) if B[i] is not equal to B[j]. If the array A[] can be sorted, then print "Yes". Otherwise, print "No". Examples: Input: A[] = {3, 1
    15 min read
  • Check if array can be sorted by swapping adjacent elements of opposite parity
    Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times. Examples: Input : n = 4, A = [1, 6, 51, 16]Output: YESExplan
    9 min read
  • Check if the array can be sorted only if the elements on given positions can be swapped
    Given an array arr[] of length N and another array P[] containing {a1, a2, ... ak} which represents the positions of the given array arr[], the task is to check if the array can be sorted by only swapping the elements' arr[ai], arr[ai+1] where 'i' is some element in the array P[].Examples: Input: ar
    8 min read
  • Check if Array can be sorted by changing elements to Absolute difference with j
    Given an array of positive numbers arr[] of size n, the task is to check if we can make the array sorted in non-decreasing order by choosing any positive integer j and changing all elements of the array a[i] to abs(a[i]-j). Examples: Input: arr = { 3, 3, 1 }Output: Yes Explanation: We can make array
    7 min read
  • Check if an array can be sorted by rearranging odd and even-indexed elements or not
    Given an array arr[] of size N, the task is to check if it is possible to sort the array using the following operations: Swap(arr[i], arr[j]), if i & 1 = 1 and j & 1 = 1.Swap(arr[i], arr[j]), if i & 1 = 0 and j & 1 = 0. Examples: Input: arr[] = {3, 5, 1, 2, 6}Output: YesExplanation:
    11 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
  • Sort an array by left shifting digits of array elements
    Given an array arr[] consisting of N positive integers, the task is to left-shift the digits of array elements such that the array modifies to a sorted form. If multiple solutions exist, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 511, 321, 323, 432 } Output: { 115, 1
    8 min read
  • Check if an array can be Arranged in Left or Right Positioned Array
    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
    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