oneby7

Heaps Top K

411. Sort a Nearly Sorted Array

Medium

You are given an array of integers nums that is nearly sorted, and an integer k. Every element of nums is at most k positions away from its place in the sorted array, to the left or to the right. Return nums sorted from smallest to largest.

When a value appears more than once, its copies keep their order: the first copy belongs at the first of their places. The distance of each copy is measured that way.

You may sort nums itself and return it, or return a new array.

Example 1

Input: nums = [4, 2, 7, 3, 9, 5, 8], k = 2

Output: [2,3,4,5,7,8,9]

Explanation: The 3 sits at index 3 and belongs at index 1, two places to its left. The 9 sits at index 4 and belongs at index 6. No element is more than 2 places from where it belongs.

Example 2

Input: nums = [-3, -8, -8, 0, -1], k = 2

Output: [-8,-8,-3,-1,0]

Explanation: The −3 belongs at index 2, two places to its right. The two −8s belong at indexes 0 and 1, so each one moves one place to the left.

Example 3

Input: nums = [-1000000000, 6, 6, 1000000000], k = 0

Output: [-1000000000,6,6,1000000000]

Explanation: With k = 0 every element is already in its place.

Check your understanding

Work out the answer for this input before you write any code.

nums = [6, -2, 6, 0, 9, 12], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k < nums.length
  • Every element of nums is at most k positions from its place in the sorted array.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.