Sort a Nearly Sorted (K-sorted) Array
Problem Statement
You get an array arr and a number k. Every element is at most k positions away from its place in the sorted order.
Sort arr in place, so it ends up in ascending order. Change arr itself. Nothing is returned.
arr: an array of integers. k: the largest distance any element is from its sorted place.
No return value. arr itself is sorted in ascending order.
1 sits at index 2 but belongs at index 0. That is 2 places away, which is allowed.
4 and 5 sit 2 places too early, and 2 and 3 sit 2 places too late. Nothing is farther than k.
- β’ Every element is at most k places away from its place in the sorted order.
- β’ The problem page gives no other limits on n, k or the values.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Use a normal sort and ignore k
Slide each element left into place; each one only passes about k neighbours
Keep k + 1 candidates in a min-heap; each step writes the smallest one into the next slot
The output has to be sorted, so a standard sort gives the right answer. It costs O(n log n). It does not use the fact that every element is already near its place.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like K-way Merge translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.