VOOZH about

URL: https://www.geeksforgeeks.org/dsa/nearly-sorted-algorithm/

⇱ Nearly Sorted - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Nearly Sorted

Last Updated : 20 Dec, 2025

Given an array arr[] and an integer k, where every element is at most k positions away from its correct sorted position. This means that if the array were completely sorted, the element at index i in the given array can be at any index from i - k to i + k.

Examples:

Input: arr[]= [2, 3, 1, 4], k = 2 
Output: [1, 2, 3, 4]
Explanation: All elements are at most k = 2 positions away from their correct positions.
Element 1 moves from index 2 to 0
Element 2 moves from index 0 to 1
Element 3 moves from index 1 to 2
Element 4 stays at index 3

Input: arr[]= [1, 4, 5, 2, 3, 6, 7, 8, 9, 10], k = 2
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation : The sorted array will be 1 2 3 4 5 6 7 8 9 10

[Naive Approach] Using Sorting - O(n log(n)) Time and O(1) Space

We can sort the array using any sorting algorithm to get the required order.

Note: This approach might accepts on online judges, but it ignores the given constraint, so it is not suitable for real interview scenarios where an optimized solution is expected.


Output
1 2 3 4 

[Expected Approach] Using Heap - O(n*log k) Time and O(k) Space

In this array, every element is at most k positions away from its correct spot. This means the element at index i could be anywhere between i - k and i + k in the sorted array. If we start placing the correct elements from left to right, then the element for the current position must be within the next k+1 elements, and we don’t need to check the elements to the left.

For these next k+1 elements, the best element to place at index i in the sorted array is the minimum element. Therefore, the problem reduces to finding the minimum element in a window of size k+1 for each position. To do this efficiently, we can use a min-heap, which allows us to quickly extract the minimum and insert the next element as we move through the array.


Output
1 2 3 4 
Comment