ProgrammingHardAmazon OA · Flipkart coding round
Dijkstra's algorithm with heapq has no decrease-key operation. Which approach is the standard one in Python?
- A. Push a new (distance, node) pair whenever a shorter distance is found, and skip popped pairs whose distance is larger than the best known one
- B. Call heapq.update(heap, node, newdist) so the existing entry moves up the heap
- C. Remove the old entry with list.remove and call heapify on the whole heap each time
- D. Store distances in a dict and rebuild the heap from scratch after every edge relaxation
Correct answer: A. Push a new (distance, node) pair whenever a shorter distance is found, and skip popped pairs whose distance is larger than the best known one
Lazy deletion: the heap may hold several stale entries for a node, and the first pop with the current best distance is used while the rest are discarded. This keeps each push and pop at O(log E).
More Python Programming questions
- A program inserts n = 200000 items one at a time with lst.insert(0, x) and never removes them. Which is the time complexity of the whole…
- A solution does if x not in seenlist for each of n = 2 10^5 values, where seenlist grows to n items. Which change gives the best speedup…
- What is printed? python import heapq print(heapq.nsmallest(0, [5, 1]), max([], default=-1), min([3, 1, 2], key=lambda x: -x))
- What is printed? python print(pow(2, -1, 10 9 + 7))
- What is printed? python import math n = 10 30 - 1 print(math.isqrt(n), int(n 0.5))
- What is printed? python print(2 53 + 1 == float(2 53 + 1))