Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimal Sorting with Heaps

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimal Sorting with Heaps. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Asana may provide a sequence of tasks that is almost sorted by due date. Every task is at most k positions away from its position in the fully sorted sequence. Given an integer array, return its sorted order using an algorithm that exploits this guarantee.

Implement sort_nearly_sorted(nums, k). The function must return a new array containing the values from nums in nondecreasing order. Do not call Python's built-in sorting functions.

Formal Specification

  • Input: nums, a list of integers, and k, a nonnegative integer.
  • Output: A new list containing all values from nums in nondecreasing order.
  • Duplicate values must be preserved.
  • The input is guaranteed to be k-sorted: each value is at most k indices from its final sorted index.

Constraints

  • 0 <= nums.length <= 100,000
  • 0 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9
  • Every value is at most k positions from its final sorted position

Function Signature

def sort_nearly_sorted(nums, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output