DSA interview question
A log collector receives events that are almost in timestamp order: network jitter can delay an event, but never by more than k positions from where it belongs. A general sort costs O(n log n). Knowing the disorder is bounded by k, a min-heap of k + 1 elements is enough. The smallest remaining element must be among the next k + 1 candidates, so repeatedly pop the minimum into the output and push the next element. That's O(n log k).
Example: [6, 5, 3, 2, 8, 10, 9], k = 3 → [2, 3, 5, 6, 8, 9, 10].
vector<int> sortKSorted(const vector<int>& arr, int k); // every element is within k positions of its sorted place
Input (arr, k) | Output | Explanation |
|---|---|---|
([6, 5, 3, 2, 8, 10, 9], 3) | [2, 3, 5, 6, 8, 9, 10] | |
([10, 9, 8, 7, 4, 70, 60, 50], 4) | [4, 7, 8, 9, 10, 50, 60, 70] | |
([1, 2, 3], 0) | [1, 2, 3] | Already sorted |
([2, 1], 1) | [1, 2] | |
([3, 1, 2], 2) | [1, 2, 3] |
(Confirm: the input is guaranteed k-sorted; output in ascending order.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in