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?- A. [1, 2, 3, 6, 4, 5, 7, 8, 9]
- B. [1, 3, 2, 4, 6, 5, 7, 9, 8]
- C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
- 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
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…