Sort a K-Sorted Array

You are given an integer array arr and an integer k.

The array is k-sorted, meaning every element is at most k positions away from its correct position in the completely sorted array.

Sort the array in non-decreasing order and return the sorted array.

Your solution should take advantage of the k-sorted property rather than simply sorting the entire array.

Example 1:

Input: arr = [3, 1, 2, 5, 4, 7, 6], k = 2

Output: [1, 2, 3, 4, 5, 6, 7]

Explanation: Every element is at most 2 positions away from its position in the sorted array. After sorting, the array becomes [1, 2, 3, 4, 5, 6, 7].

Example 2:

Input: arr = [4, 2, 3, 1, 6, 5], k = 3

Output: [1, 2, 3, 4, 5, 6]

Explanation: The array satisfies the k = 3 condition. Sorting it gives [1, 2, 3, 4, 5, 6].

Now Your Turn!

Pick the correct output for the given input

Input: arr = [10, 20, 30, 25, 35, 40], k = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= arr.size() <= 105
  • 0 <= k < arr.size()
  • 1 <= arr[i] <= 105
0
class Solution {
public:
vector<int> sortKSortedArray(vector<int>& arr, int k) {
// Your code goes here
return {};
}
};
Test Case

Input:

Arr
K