Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1.

Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1.
import heapq
def sort_k(a, k):
    h = a[:k + 1]; heapq.heapify(h); out = []
    for x in a[k + 1:]:
        out.append(heapq.heappushpop(h, x))
    while h: out.append(heapq.heappop(h))
    return out
print(sort_k([3, 1, 2, 6, 4, 5, 9, 7, 8], 2))
What is printed?
  1. A. [1, 2, 3, 6, 4, 5, 7, 8, 9]
  2. B. [1, 3, 2, 4, 6, 5, 7, 9, 8]
  3. C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
  4. D. [3, 1, 2, 6, 4, 5, 9, 7, 8]

Correct answer: C. [1, 2, 3, 4, 5, 6, 7, 8, 9]

The smallest remaining element is always among the next k + 1 items, so a window heap of size k + 1 emits elements in order. heappushpop pushes the new value and pops the minimum in one O(log k) step. Total O(n log k), better than O(n log n) when k ≪ n.

More Coding Interview Problems questions

Exams that ask this topic