Python coding

Tightest range around each point

You get a list of closed integer ranges [start, end] with start <= end, and a list of integer points. The size of a range is how many integers it holds, end - start + 1. For each point, return the size of the smallest range that contains it (start <= point <= end), or -1 if no range does. Answers follow the order of points, which may repeat.

Both lists can be long, so checking every range for every point, O(n·q), is too slow: aim for O(n log n + q log q).

Besides the tests, one large input (5,000 ranges and 5,000 points) with a ~450 ms limit (scaled to your device's speed): brute force won't pass.

  • tightest_sizes([[1,8],[3,5],[4,4],[7,12]], [4,6,2,10,13]) → [1,8,8,6,-1]
  • tightest_sizes([[5,10],[6,7]], [7,8,7]) → [2,6,2]
  • tightest_sizes([[1,2],[1,10]], [2,5,1]) → [2,10,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Answer the points offline, in increasing order, remembering each one's original index. Sort the ranges by start too, so they become relevant one by one.

Hint 2

For each point, push every range that starts at or before it into a min-heap keyed by size. The top is the smallest candidate, if it still reaches the point.

Hint 3

Pop the top while its range ends before the point. That is safe for good: later points are larger, so an ended range never helps again.

Solution and why it works
pythonO(n log n + q log q) · O(n + q)
import heapq


def tightest_sizes(ranges: list[list[int]], points: list[int]) -> list[int]:
    ranges = sorted(ranges)
    answer = [-1] * len(points)
    heap = []                                # (size, end) of ranges that have started
    i = 0
    for k in sorted(range(len(points)), key=points.__getitem__):
        p = points[k]
        while i < len(ranges) and ranges[i][0] <= p:
            start, end = ranges[i]
            heapq.heappush(heap, (end - start + 1, end))
            i += 1
        while heap and heap[0][1] < p:       # ended before p, so before every later point
            heapq.heappop(heap)
        if heap:
            answer[k] = heap[0][0]
    return answer

Sorting both lists turns the question into a sweep: as points grow, ranges start (push them into a min-heap by size) and end (pop them once they end before the point). Lazy removal is enough: an ended range below the top only matters when it reaches the top, and then it is popped. Each range is pushed and popped once: O(n log n + q log q). The trap is answering points in input order: a range popped for a large point may still contain a smaller one.