![]() |
VOOZH | about |
Given an array arr[] and an integer k, sort the array in ascending order while keeping the element at index k fixed at its original position. Return the resulting array.
Examples:
Input: arr[] = [10, 4, 11, 7, 6, 20], k = 2
Output: [4, 6, 11, 7, 10, 20]
Explanation: The element 11 at index 2 remains fixed, while all other elements are sorted in ascending order.
Input: arr[] = [30, 20, 10], k = 0
Output: [30, 10, 20]
Explanation: The element 30 at index 0 remains fixed, while the remaining elements are sorted in ascending order.
Table of Content
The idea is to keep the element at index k fixed and store all the remaining elements in a temporary array. Sort the temporary array and place the sorted elements back into the original array while skipping index k. This ensures that the element at index k remains unchanged and all other elements are sorted in ascending order.
[30, 10, 20]
Time Complexity: O(n log n)
Auxiliary Space: O(n)
The idea is to temporarily move the element at index
kto the end.. Then, sort the firstn - 1elements. Finally, move the fixed element back to its original position by repeatedly swapping it with its previous element. This sorts all elements except the one at indexkwhile using constant extra space.
[30, 10, 20]
Time Complexity: O(n log n)
Auxiliary Space: O(1)