The problem. You're given an array nums that is nearly sorted: every value is at most k positions away from where it belongs in sorted order. Return the values sorted in ascending order — faster than an ordinary sort, by using the fact that nothing is far from home.
nums = [6, 5, 3, 2, 8, 10, 9], k = 3 -> [2, 3, 5, 6, 8, 9, 10]
nums = [2, 1, 4, 3, 6, 5], k = 1 -> [1, 2, 3, 4, 5, 6]
nums = [1, 2, 3], k = 0 -> [1, 2, 3] (already sorted)Members only · free account
The rest of this lesson, with 7 more sections, 1 drawing, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson