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:Â
, 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: Perform the following swaps:Â
Swap A[1] and A[2], now A[] = { 3, 1, 2, 4 }Â
Swap A[0] and A[1], now A[] = { 1, 3, 2, 4 }Â
No further swaps are possible as A[1] and A[2] have already been swapped.
Input: A[] = { 2, 1, 4, 3, 6, 5 }Â
Output: 1 2 3 4 5 6Â
Explanation: Perform the following swaps:Â
Swap A[0] and A[1], now A[] = { 1, 2, 4, 3, 6, 5 }Â
Swap A[2] and A[3], now A[] = { 1, 2, 3, 4, 6, 5 }Â
Swap A[4] and A[5], now A[] = { 1, 2, 3, 4, 5, 6 }Â
Â
Â
Approach:Â
To solve the problem mentioned above we can apply Greedy method. We know that we can perform at most N – 1 swaps to make the given array as smallest as possible.Â
Â
- Create a counter variable and initialize with N-1 and a hash-map to store performed swaps.
- Find the position of the minimum element from current index onward.
- Now perform swap backwards until we reach current element position.
- Also check if current swap is possible or not and decrement the counter also at each swap.
- Finally print the required array.
Below is the implementation of above approach:
Â
C++
// C++ implementation to find the// lexicographically smallest// array by at most single swap// for every pair of adjacent indicesÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the// lexicographically smallest arrayvoid findSmallestArray(int A[], int n){    // maximum swaps possible    int count = n - 1;Â
    // hash to store swaps performed    map<pair<int, int>, int> mp;Â
    for (int i = 0; i < n && count > 0; ++i) {Â
        // let current element be        // the minimum possible        int mn = A[i], pos = i;Â
        // Find actual position of        // the minimum element        for (int j = i + 1; j < n; ++j) {Â
            // Update minimum element and            // its position            if (A[j] < mn) {                mn = A[j];                pos = j;            }        }Â
        // Perform swaps if possible        while (pos > i && count > 0               && !mp[{ pos - 1, pos }]) {Â
            // Insert current swap in hash            mp[{ pos - 1, pos }] = 1;Â
            swap(A[pos], A[pos - 1]);            --pos;            --count;        }    }Â
    // print the required array    for (int i = 0; i < n; ++i)        cout << A[i] << " ";}Â
// Driver codeint main(){Â
    int A[] = { 2, 1, 4, 3, 6, 5 };    int n = sizeof(A) / sizeof(A[0]);Â
    findSmallestArray(A, n);Â
    return 0;} |
Java
// Java implementation to find the// lexicographically smallest// array by at most single swap// for every pair of adjacent indicesimport java.util.*;Â
class GFG {Â
  // Function to find the  // lexicographically smallest array  static void findSmallestArray(int[] A, int n)  {Â
    // maximum swaps possible    int count = n - 1;Â
    // hash to store swaps performed    HashMap<String, Integer> mp      = new HashMap<String, Integer>();Â
    for (int i = 0; i < n && count > 0; ++i) {Â
      // let current element be      // the minimum possible      int mn = A[i];      int pos = i;Â
      // Find actual position of      // the minimum element      for (int j = i + 1; j < n; ++j) {Â
        // Update minimum element and        // its position        if (A[j] < mn) {          mn = A[j];          pos = j;        }      }Â
      // Perform swaps if possible      while (pos > i && count > 0             && !mp.containsKey(               String.valueOf(pos - 1) + "#"               + String.valueOf(pos))) {Â
        // Insert current swap in hash        mp.put(String.valueOf(pos - 1) + "#"               + String.valueOf(pos), 1);Â
        var temp = A[pos];        A[pos] = A[pos - 1];        A[pos - 1] = temp;        --pos;        --count;      }    }Â
    // print the required array    for (int i = 0; i < n; ++i)      System.out.print(A[i] + " ");  }Â
  // Driver code  public static void main(String[] args)  {Â
    int[] A = { 2, 1, 4, 3, 6, 5 };    int n = A.length;Â
    findSmallestArray(A, n);  }}Â
// This code is contributed by phasing17. |
Python3
# Python3 implementation to find the# lexicographically smallest array by# at most single swap for every pair# of adjacent indicesÂ
# Function to find the# lexicographically smallest arraydef findSmallestArray(A, n):         # Maximum swaps possible    count = n - 1Â
    # Hash to store swaps performed    mp = {''}Â
    for i in range(0, n):        if(count <= 0):            break;Â
        # Let current element be        # the minimum possible        mn = A[i]        pos = iÂ
        # Find actual position of        # the minimum element        for j in range(i + 1, n):Â
            # Update minimum element             # and its position            if (A[j] < mn):                mn = A[j]                pos = jÂ
        # Perform swaps if possible        while (pos > i and count > 0 and             ((pos - 1, pos) not in mp)):Â
            # Insert current swap in hash            mp.add((pos - 1, pos))Â
            A[pos], A[pos - 1] = A[pos - 1], A[pos]            pos -= 1            count -= 1Â
    # Print the required array    for i in range(0, n):        print(A[i], end = " ")Â
# Driver codeA = [ 2, 1, 4, 3, 6, 5 ]n = len(A)Â
findSmallestArray(A, n)Â
# This code is contributed by Sanjit_Prasad |
C#
// C# implementation to find the// lexicographically smallest// array by at most single swap// for every pair of adjacent indicesusing System;using System.Collections.Generic;Â
class GFG {Â
  // Function to find the  // lexicographically smallest array  static void findSmallestArray(int[] A, int n)  {         // maximum swaps possible    int count = n - 1;Â
    // hash to store swaps performed    Dictionary<string, int> mp      = new Dictionary<string, int>();Â
    for (int i = 0; i < n && count > 0; ++i) {Â
      // let current element be      // the minimum possible      int mn = A[i];      int pos = i;Â
      // Find actual position of      // the minimum element      for (int j = i + 1; j < n; ++j) {Â
        // Update minimum element and        // its position        if (A[j] < mn) {          mn = A[j];          pos = j;        }      }Â
      // Perform swaps if possible      while (pos > i && count > 0             && !mp.ContainsKey(               Convert.ToString(pos - 1) + "#"               + Convert.ToString(pos))) {Â
        // Insert current swap in hash        mp[Convert.ToString(pos - 1) + "#"           + Convert.ToString(pos)]          = 1;Â
        var temp = A[pos];        A[pos] = A[pos - 1];        A[pos - 1] = temp;        --pos;        --count;      }    }Â
    // print the required array    for (int i = 0; i < n; ++i)      Console.Write(A[i] + " ");  }Â
  // Driver code  public static void Main(string[] args)  {Â
    int[] A = { 2, 1, 4, 3, 6, 5 };    int n = A.Length;Â
    findSmallestArray(A, n);  }}Â
// This code is contributed by phasing17. |
Javascript
// JS implementation to find the// lexicographically smallest// array by at most single swap// for every pair of adjacent indicesÂ
// Function to find the// lexicographically smallest arrayfunction findSmallestArray(A, n){    // maximum swaps possible    let count = n - 1;Â
    // hash to store swaps performed    let mp = {};Â
    for (var i = 0; i < n && count > 0; ++i) {Â
        // let current element be        // the minimum possible        var mn = A[i], pos = i;Â
        // Find actual position of        // the minimum element        for (var j = i + 1; j < n; ++j) {Â
            // Update minimum element and            // its position            if (A[j] < mn) {                mn = A[j];                pos = j;            }        }Â
        // Perform swaps if possible        while (pos > i && count > 0               && !mp.hasOwnProperty(pos - 1 + "#" + pos)) {Â
            // Insert current swap in hash            mp[ pos - 1 + "#" + pos] = 1;                         var temp = A[pos];            A[pos] = A[pos - 1]            A[pos - 1] = temp            --pos;            --count;        }    }Â
    // print the required array    console.log(A.join(" "))     }Â
// Driver codelet A = [ 2, 1, 4, 3, 6, 5 ];let n = A.length;Â
findSmallestArray(A, n);Â
// This code is contributed by phasing17 |
1 2 3 4 5 6
Â
Time Complexity: O(N2)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


