Ctrl K

The Narrowest Range Around Each Point

Hard
You are given a list of ranges ranges, where ranges[i] = [lo, hi] stands for every integer from lo to hi inclusive. The length of a range is how many integers it holds, hi - lo + 1. You are also given a list of points points. For each point, find the shortest range that contains it and record its length. If no range contains the point, record -1. Return the answers in the order of the points.
Example 1
ranges=[[3, 9], [5, 6], [8, 8], [1, 4]], points=[5, 8, 2, 12] → [2, 1, 4, -1]

Point 5 lies in [3, 9] and [5, 6]; the latter is narrower, length 2. Point 8 is covered by [8, 8] of length 1. Point 2 only by [1, 4], length 4. Nothing covers 12.

Example 2
ranges=[[10, 20]], points=[20, 21, 10] → [11, -1, 11]

Ends are included, so 20 and 10 are covered (length 11), but 21 is not.

Constraints
  • 1 ≤ len(ranges) ≤ 10⁵
  • 1 ≤ len(points) ≤ 10⁵
  • 1 ≤ lo ≤ hi ≤ 10⁷
  • 1 ≤ points[j] ≤ 10⁷
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSecond Larger to the Right HardK-th Smallest in a Sorted Grid MediumNearest k Values MediumRanked Prime Ratios MediumTop Three While Typing Medium
loading Python…
Input
ranges=[[3, 9], [5, 6], [8, 8], [1, 4]], points=[5, 8, 2, 12]
Expected
[2, 1, 4, -1]

Run checks the first 3 tests in your browser. Submit checks all 105 tests on the server, hidden ones included.