1019. Closest Suitable Room

A parking garage has n bays. Bay rooms[i] = [id, size] has a unique number id and a capacity size. Drivers send requests queries[j] = [preferred, minSize]: they would like the bay whose number is as close as possible to preferred, but it must have capacity at least minSize.

For each request, return the number of the best bay. The best bay minimises the absolute difference between its number and preferred; if two bays are equally close, take the one with the smaller number. If no bay is large enough, return -1. Requests are independent (nothing is reserved), and the answer array is in the order of queries.

Example 1

Input:
rooms = [[12,40],[30,25],[21,60],[5,10]]queries = [[20,30],[6,5],[100,61],[26,20]]
Output:
[21,5,-1,30]
Explanation:

For [20,30] only bays 12 and 21 are big enough and 21 is closer; for [6,5] bay 5 (distance 1) wins; no bay holds 61, so -1; for [26,20] bay 21 is 5 away and bay 30 is 4 away, so bay 30 wins.

Example 2

Input:
rooms = [[10,8],[20,8]], queries = [[15,8],[15,9]]
Output:
[10,-1]
Explanation:

Bays 10 and 20 are both 5 from 15 and both big enough, so the smaller id 10 is chosen; nothing holds size 9.

Example 3

Input:
rooms = [[7,3]], queries = [[1,1],[7,3],[9,4]]
Output:
[7,7,-1]
Explanation:

With one bay, it answers any request it can hold: sizes 1 and 3 fit, size 4 does not.

Constraints

  • 1 ≤ rooms.length ≤ 105
  • 1 ≤ queries.length ≤ 105
  • All bay numbers are distinct; 1 ≤ id, size ≤ 107
  • 1 ≤ preferred, minSize ≤ 107

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O((n + q) log n)
Space
O(n + q)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…