k-sorted


Nearly Sorted – GeeksforGeeks


Problem: Nearly Sorted

Problem Statement

Given an array of n elements, where each element is at most k positions away from its target position in the sorted array (i.e., the array is nearly sorted), your task is to sort the array efficiently.


Examples

Example 1
Input: arr = [6,5,3,2,8,10,9], n = 7, k = 3
Output: [2,3,5,6,8,9,10]

Example 2
Input: arr = [10,9,8,7,4,70,60,50], n = 8, k = 4
Output: [4,7,8,9,10,50,60,70]


Constraints


Intuition

In a nearly sorted array, the element which should be at position i can be found between indices i-k and i+k. Thus, for each index, we only need to consider a window of size k+1. This makes it ideal to use a min-heap of size k+1 to always get the next minimum element efficiently.


Approach

  1. Initialize a min-heap and insert the first k+1 elements into it.

  2. Starting from index k+1 to n-1, do the following:

    • Extract the minimum from the heap and append it to the result array.

    • Add the next element from the array to the heap.

  3. Once all elements have been processed, extract and append all remaining elements from the heap.


Code (Java)

import java.util.*;

class Solution {
    ArrayList<Integer> nearlySorted(int arr[], int n, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        ArrayList<Integer> result = new ArrayList<>();

        // Step 1: Add first k+1 elements to the heap
        for (int i = 0; i <= k && i < n; i++) {
            pq.add(arr[i]);
        }

        // Step 2: Process the remaining elements
        for (int i = k + 1; i < n; i++) {
            result.add(pq.poll());
            pq.add(arr[i]);
        }

        // Step 3: Extract remaining elements
        while (!pq.isEmpty()) {
            result.add(pq.poll());
        }

        return result;
    }
}

Time and Space Complexity


Dry Run

Input: arr = [6,5,3,2,8,10,9], k = 3


Conclusion

This problem efficiently demonstrates how a min-heap can be leveraged to sort a nearly sorted array in O(n log k) time instead of O(n log n). It’s a common technique used in external sorting and real-time streaming data where elements are only slightly out of order.