Lexicographically smallest array after consecutive swaps
Lexicographically smallest array after consecutive swaps
In the Lexicographically smallest array after consecutive swaps problem, we have to find the lexicographically smallest array obtained after swapping array elements. The problem can be optimally solved using the greedy technique. In this article, we will provide an explanation with a C++ solution.
Lexicographically smallest array after consecutive swaps Problem Description
Given an array of n integers and an integer k. You can swap any two consecutive elements of the array. The operation can be performed at most k times. Output the lexicographically smallest array possible.
Input
- First Line contains two integers n & k – the size of array & the number of swaps.
- Next Line contains n integers – the elements of the array.
Output
- Single line output containing n integers.
Solution
To find the lexicographically smallest arrangement of the array we will fix a position ‘i’ of the array and try to find the best smallest position ‘j’ such that j > i & arr[j] < arr[i].
After finding appropriate j, we just have to elements from i to j-1, one position right and move element at j to i.
Time Complexity – O(n*k)
Space Complexity – O(1)
Code
Output
5
2
5 4 3 2 1
3 5 4 2 1
Login/Signup to comment