Typescript with Clean Code! using Sort and Binary Search
Approach\n - Sort the rooms to be able to binary seach\n - Binary search to get the first room with size equals or greated then the min size\n - Then search for
# Approach\n - Sort the rooms to be able to binary seach\n - Binary search to get the first room with size equals or greated then the min size\n - Then search for the one with the min abs, if none answer is -1\n - Repeat for every query\n\n# Complexity\n- Time complexity:  $$O(m * (log n + n))$$, where m is the number of queries, and n is the number of rooms.\n\n- Space complexity: $$O(1)$$ ignoring the space required to answer\n\n# Code\n```\nfunction closestRoom(rooms: number[][], queries: number[][]): number[] {\n  const results: number[] = [];\n\n  rooms.sort((r1, r2) => r1[1] - r2[1]);\n\n  for (let i = 0; i < queries.length; i++) {\n    const [preferred, minSize] = queries[i];\n    let response = -1;\n\n    // Find the first room with size >= minSize\n    let start = binarySearch(rooms, minSize);\n\n    if (start !== -1) {\n      // If there is a room with size >= minSize find the closest room to preferred\n      let index = findClosestRoom(rooms, start, preferred);\n      response = rooms[index][0];\n    }\n\n    results.push(response)\n  }\n\n  return results;\n};\n\nfunction binarySearch(rooms: number[][], size: number): number {\n  let low = 0;\n  let high = rooms.length - 1;\n  let answer = -1;\n\n  while (low <= high) {\n    const mid = low + Math.floor((high - low) / 2);\n\n    if (rooms[mid][1] < size) {\n      low = mid + 1;\n    } else {\n      answer = mid;\n      high = mid - 1;\n    }\n  }\n\n  return answer;\n}\n\nfunction findClosestRoom(rooms: number[][], start: number, preferred: number): number {\n  let answer = start;\n  let minAbs = Math.abs(rooms[start][0] - preferred);\n\n  for (let i = start; i < rooms.length; i++) {\n    const abs = Math.abs(rooms[i][0] - preferred);\n\n    if (abs < minAbs || (abs === minAbs && rooms[i][0] < rooms[answer][0])) {\n      minAbs = abs;\n      answer = i;\n    }\n  }\n\n  return answer;\n}\n```
['Binary Search', 'Sorting', 'TypeScript']