Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Lexicographically smallest Permutation of Array by reversing at most one Subarray
Next article icon

Lexicographically smallest Permutation of Array by reversing at most one Subarray

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N which is a permutation from 1 to N, the task is to find the lexicographically smallest permutation that can be formed by reversing at most one subarray.

Examples:

Input : arr[] = {1, 3, 4, 2, 5}
Output : 1 2 4 3 5
Explanation: The subarray from index 1 to index 3 can be reversed to get the lexicographically smallest permutation.

Input : arr[] = {4, 3, 1, 2}
Output: 1 3 4 2

 

Approach: The idea to solve the problem is based on the traversal of the array. 

  • In the given problem the lexicographically smallest permutation can be obtained by placing the least number at its correct place by one reversal by traversing from left and checking (i+1) is equal to arr[i]
  • If it is not equal find the index of that i+1 in the array and reverse the subarray from ith index to the position (i+1).

Below is the implementation of the above approach.

C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the // Lexicographically smallest // Permutation by one subarray reversal void lexsmallest(vector<int>& arr, int n) {      // Initialize the variables     // To store the first and last     // Position of the subarray     int first = -1, flag = 0, find = -1, last = -1;      // Traverse the array     // And check if arr[i]!=i+1     for (int i = 0; i < n; i++) {         if (arr[i] != i + 1) {             flag = 1;              // Mark the first position             // Of the Subarray to be reversed             first = i;             find = i + 1;             break;         }     }      // If flag == 0, it is the     // Smallest permutation,     // So print the array     if (flag == 0) {         for (int i = 0; i < n; i++) {             cout << arr[i] << " ";         }     }      // Check where the minimum element is present     else {         for (int i = 0; i < n; i++) {              // It is the last position             // Of the subarray to be             // Reversed             if (arr[i] == find) {                 last = i;                 break;             }         }          // Reverse the subarray         // And print the array         reverse(arr.begin() + first,                 arr.begin() + last + 1);         for (int i = 0; i < n; i++) {             cout << arr[i] << " ";         }     } }  // Driver Code int main() {     // Initialize the array arr[]     vector<int> arr = { 1, 3, 4, 2, 5 };     int N = arr.size();      // Function call     lexsmallest(arr, N);     return 0; } 
Java
// Java code for the above approach import java.util.*;  class GFG{  // Function to find the // Lexicographically smallest // Permutation by one subarray reversal static void lexsmallest(int []arr, int n) {      // Initialize the variables     // To store the first and last     // Position of the subarray     int first = -1, flag = 0, find = -1, last = -1;      // Traverse the array     // And check if arr[i]!=i+1     for (int i = 0; i < n; i++) {         if (arr[i] != i + 1) {             flag = 1;              // Mark the first position             // Of the Subarray to be reversed             first = i;             find = i + 1;             break;         }     }      // If flag == 0, it is the     // Smallest permutation,     // So print the array     if (flag == 0) {         for (int i = 0; i < n; i++) {             System.out.print(arr[i]+ " ");         }     }      // Check where the minimum element is present     else {         for (int i = 0; i < n; i++) {              // It is the last position             // Of the subarray to be             // Reversed             if (arr[i] == find) {                 last = i;                 break;             }         }          // Reverse the subarray         // And print the array         arr = reverse(arr,first,last);         for (int i = 0; i < n; i++) {             System.out.print(arr[i]+ " ");         }     } } static int[] reverse(int str[], int start, int end) {      // Temporary variable to store character      int temp;     while (start <= end) {         // Swapping the first and last character          temp = str[start];         str[start] = str[end];         str[end] = temp;         start++;         end--;     }     return str; }    // Driver Code public static void main(String[] args) {        // Initialize the array arr[]     int []arr = { 1, 3, 4, 2, 5 };     int N = arr.length;      // Function call     lexsmallest(arr, N); } }  // This code contributed by shikhasingrajput  
Python3
# Python code for the above approach  # Function to find the # Lexicographically smallest # Permutation by one subarray reversal def lexsmallest(arr, n):      # Initialize the variables     # To store the first and last     # Position of the subarray     first = -1     flag = 0     find = -1     last = -1      # Traverse the array     # And check if arr[i]!=i+1     for i in range(0, n):         if (arr[i] != i + 1):             flag = 1              # Mark the first position             # Of the Subarray to be reversed             first = i             find = i + 1             break      # If flag == 0, it is the     # Smallest permutation,     # So print the array     if (flag == 0):         for i in range(0, n):             print(arr[i], end=" ")      # Check where the minimum element is present     else:         for i in range(0, n):              # It is the last position             # Of the subarray to be             # Reversed             if (arr[i] == find):                 last = i                 break          # Reverse the subarray         # And print the array         arr[first: last + 1] = arr[first: last + 1][::-1]          print(*arr)  # Driver Code  # Initialize the array arr[] arr = [1, 3, 4, 2, 5] N = len(arr)  # Function call lexsmallest(arr, N)  # This code is contributed by Samim Hossain Mondal. 
C#
// C# code for the above approach using System;  class GFG{    // Function to find the   // Lexicographically smallest   // Permutation by one subarray reversal   static void lexsmallest(int []arr, int n)   {      // Initialize the variables     // To store the first and last     // Position of the subarray     int first = -1, flag = 0, find = -1, last = -1;      // Traverse the array     // And check if arr[i]!=i+1     for (int i = 0; i < n; i++) {       if (arr[i] != i + 1) {         flag = 1;          // Mark the first position         // Of the Subarray to be reversed         first = i;         find = i + 1;         break;       }     }      // If flag == 0, it is the     // Smallest permutation,     // So print the array     if (flag == 0) {       for (int i = 0; i < n; i++) {         Console.Write(arr[i]+ " ");       }     }      // Check where the minimum element is present     else {       for (int i = 0; i < n; i++) {          // It is the last position         // Of the subarray to be         // Reversed         if (arr[i] == find) {           last = i;           break;         }       }        // Reverse the subarray       // And print the array       arr = reverse(arr,first,last);       for (int i = 0; i < n; i++) {         Console.Write(arr[i]+ " ");       }     }   }   static int[] reverse(int[] str, int start, int end) {      // Temporary variable to store character      int temp;     while (start <= end)     {              // Swapping the first and last character        temp = str[start];       str[start] = str[end];       str[end] = temp;       start++;       end--;     }     return str;   }    // Driver Code   static public void Main (){      // Initialize the array arr[]     int [] arr = { 1, 3, 4, 2, 5 };     int N = arr.Length;      // Function call     lexsmallest(arr, N);   } }  // This code is contributed by hrithikgarg03188. 
JavaScript
    <script>         // JavaScript code for the above approach          // Function to find the         // Lexicographically smallest         // Permutation by one subarray reversal         const lexsmallest = (arr, n) => {              // Initialize the variables             // To store the first and last             // Position of the subarray             let first = -1, flag = 0, find = -1, last = -1;              // Traverse the array             // And check if arr[i]!=i+1             for (let i = 0; i < n; i++) {                 if (arr[i] != i + 1) {                     flag = 1;                      // Mark the first position                     // Of the Subarray to be reversed                     first = i;                     find = i + 1;                     break;                 }             }              // If flag == 0, it is the             // Smallest permutation,             // So print the array             if (flag == 0) {                 for (let i = 0; i < n; i++) {                     document.write(`${arr[i]} `);                 }             }              // Check where the minimum element is present             else {                 for (let i = 0; i < n; i++) {                      // It is the last position                     // Of the subarray to be                     // Reversed                     if (arr[i] == find) {                         last = i;                         break;                     }                 }                  // Reverse the subarray                 // And print the array                 arr.splice(first, last, ...arr.slice(first, last + 1).reverse());                 for (let i = 0; i < n; i++) {                     document.write(`${arr[i]} `);                 }             }         }          // Driver Code          // Initialize the array arr[]         let arr = [1, 3, 4, 2, 5];         let N = arr.length;          // Function call         lexsmallest(arr, N);      // This code is contributed by rakeshsahni      </script> 

 
 


Output
1 2 4 3 5 


 

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

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article
Lexicographically smallest Permutation of Array by reversing at most one Subarray

L

lokeshpotta20
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • Geeks-Premier-League-2022
  • permutation
  • subarray
  • lexicographic-ordering
Practice Tags :
  • Arrays
  • permutation

Similar Reads

    Lexicographically smallest permutation of the array possible by at most one swap
    Given an array arr[] representing a permutation of first N natural numbers, the task is to find the lexicographically smallest permutation of the given array arr[] possible by swapping at most one pair of array elements. If it is not possible to make the array lexicographically smaller, then print "
    8 min read
    Lexicographically largest permutation of array possible by reversing suffix subarrays
    Given an array arr[] of size N, the task is to find the lexicographically largest permutation array by reversing any suffix subarrays from the array. Examples: Input: arr[] = {3, 5, 4, 1, 2}Output: 3 5 4 2 1Explanation: Reversing the suffix subarray {1, 2} generates the lexicographically largest per
    7 min read
    Lexicographically smallest permutation of [1, N] based on given Binary string
    Given a binary string S of size (N - 1), the task is to find the lexicographically smallest permutation P of the first N natural numbers such that for every index i, if S[i] equals '0' then P[i + 1] must be greater than P[i] and if S[i] equals '1' then P[i + 1] must be less than P[i]. Examples: Inpu
    6 min read
    Lexicographically smallest permutation of Array such that prefix sum till any index is not equal to K
    Given an array arr[], consisting of N distinct positive integers and an integer K, the task is to find the lexicographically smallest permutation of the array, such that the sum of elements of any prefix of the output array is not equal to the K. If there exists no such permutation, then print "-1".
    7 min read
    Lexicographically smallest array formed by at most one swap for every pair of adjacent indices
    Given an array A[] of length N, the task is to find lexicographically smallest array by swapping adjacent elements for each index atmost once. Thus, for any index: 0 <= K < N-1 , at most one swap between A[K] and A[K+1] is allowed.Example: Input: A[] = { 3, 2, 1, 4} Output: 1 3 2 4 Explanation
    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