<p>There is a hotel with <code>n</code> rooms. The rooms are represented by a 2D integer array <code>rooms</code> where <code>rooms[i] = [roomId<sub>i</sub>, size<sub>i</sub>]</code> denotes that there is a room with room number <code>roomId<sub>i</sub></code> and size equal to <code>size<sub>i</sub></code>. Each <code>roomId<sub>i</sub></code> is guaranteed to be <strong>unique</strong>.</p>

<p>You are also given <code>k</code> queries in a 2D array <code>queries</code> where <code>queries[j] = [preferred<sub>j</sub>, minSize<sub>j</sub>]</code>. The answer to the <code>j<sup>th</sup></code> query is the room number <code>id</code> of a room such that:</p>

<ul>
	<li>The room has a size of <strong>at least</strong> <code>minSize<sub>j</sub></code>, and</li>
	<li><code>abs(id - preferred<sub>j</sub>)</code> is <strong>minimized</strong>, where <code>abs(x)</code> is the absolute value of <code>x</code>.</li>
</ul>

<p>If there is a <strong>tie</strong> in the absolute difference, then use the room with the <strong>smallest</strong> such <code>id</code>. If there is <strong>no such room</strong>, the answer is <code>-1</code>.</p>

<p>Return <em>an array </em><code>answer</code><em> of length </em><code>k</code><em> where </em><code>answer[j]</code><em> contains the answer to the </em><code>j<sup>th</sup></code><em> query</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
<strong>Output:</strong> [3,-1,3]
<strong>Explanation: </strong>The answers to the queries are as follows:
Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.
Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
<strong>Output:</strong> [2,1,3]
<strong>Explanation: </strong>The answers to the queries are as follows:
Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == rooms.length</code></li>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>k == queries.length</code></li>
	<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= roomId<sub>i</sub>, preferred<sub>j</sub> &lt;= 10<sup>7</sup></code></li>
	<li><code>1 &lt;= size<sub>i</sub>, minSize<sub>j</sub> &lt;= 10<sup>7</sup></code></li>
</ul>

from sortedcontainers import SortedList
import bisect

ID,SIZE=0,1

def closest(target, a, b):
    if not a and not b: return -1
    if a and not b: return a
    if not a and b: return b
    da,db = abs(a-target), abs(b-target)
    if da == db:
        return a if a < b else b
    return a if da < db else b

CHUNK = 300
class OnTheFly:
    def __init__(self, rooms: List[List[int]]):
        rooms.sort(key = lambda x: x[1])
        self.chunks = SortedList()
        for c in [rooms[i:i+CHUNK] for i in range(0,len(rooms),CHUNK)]:
            minSize = c[0][SIZE]
            self.chunks.add((minSize, c, sorted(r[0] for r in c)))

    def closest(self, pid, S):
        cs = self.chunks
        six = cs.bisect_left((S,[]))

        def update(result, candidate):
            if result == -1: return candidate
            if candidate is not None:
                c,r = abs(candidate - pid), abs(result - pid)
                if c < r or (c == r and candidate < result): return candidate
            return result

        res = -1
        # full chunks
        for i in range(six,len(cs)):
            ids = cs[i][2]
            ix = bisect.bisect_right(ids, pid)
            if ix < len(ids): res = update(res, ids[ix])
            if ix > 0: res = update(res, ids[ix-1])
        
        # partial chunk
        if six > 0:
            for rid,s in cs[six-1][1]:
                if s >= S:
                    res = update(res, rid)

        return res


class Solution:
    def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:
        # return normal_solution(rooms, queries)
        otf = OnTheFly(rooms)
        return [otf.closest(pid,s) for pid,s in queries]

    def normal_solution(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:
        qs = [(s,p,i) for i,(p,s) in enumerate(queries)]
        qs.sort(reverse=True)
        rooms.sort(key = lambda x: x[1],reverse=True)
        sl = SortedList()
        result = []
        k, n = 0,len(rooms)
        for s,pid,_ in qs:
            while k < n and rooms[k][SIZE] >= s:
                item = rooms[k][ID]
                sl.add(item)
                k += 1
            ix = sl.bisect_right(pid)
            r1 = r2 = None
            if ix < len(sl): r2 = sl[ix]
            if ix > 0: r1 = sl[ix-1]
            result.append(closest(pid, r1, r2))
        return [a for a,b in sorted(zip(result,qs), key=lambda x: x[1][2])]
        
68400