Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the k points closest to the origin (ties broken by smaller index).
Problem: Return the k points closest to the origin (ties broken by smaller index).
import heapq pts = [(3, 3), (5, -1), (-2, 4), (1, 1), (0, -2)] print(heapq.nsmallest(3, range(len(pts)), key=lambda i: pts[i][0]**2 + pts[i][1]**2))What is printed?
- A. [3, 4, 2]
- B. [4, 3, 0]
- C. [3, 4, 0]
- D. [0, 3, 4]
Correct answer: C. [3, 4, 0]
Squared distances: 18, 26, 20, 2, 4 → the three smallest are index 3 (2), index 4 (4) and index 0 (18); (−2, 4) at 20 just misses. Comparing squared distances avoids sqrt and floating error. nsmallest keeps a size-k heap: O(n log k); quickselect gives O(n) average.
More Coding Interview Problems questions
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…
- Problem: Merge overlapping booking intervals. python def merge(iv): iv.sort(); out = [] for s, e in iv: if out and s <= out[-1][1]…
- Problem: Remove the fewest meetings so that the rest do not overlap (meetings that only touch at an endpoint are fine). python def…
- Problem: Find the minimum number of meeting rooms needed for a list of meetings [start, end). python import heapq def rooms(iv)…
- Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs…
- Problem: Each child must get at least one sweet, and a child with a higher rating than a neighbour must get more than that neighbour. Find…