Sorting + BinarySearch + Simple Code in JAVA
steps to follow:\n1. Sort the rooms array on the basis of capacity . So that we can do binary search and got the first room index which have size greater than m
**steps to follow:**\n1. Sort the rooms array on the basis of capacity . So that we can do binary search and got the first room index which have size greater than minsize for particular query. \n2. If we have found the start index . we know that array is sorted so all size in right are going to be greater than size So iterate and find the roomId where Math.abs(room_id-prefrence) is minimum.\n3. Have this point in mind if two rooms have value for Math.abs(room_id-preference) we have to select room with smaller id.\n4. Go through code you will understand rest things.\n\n**CODE:**\n```\nclass Solution {\n    public int[] closestRoom(int[][] rooms, int[][] queries) {\n        Arrays.sort(rooms,new Pair());\n        int[] ans=new int[queries.length];\n        \n        for(int i=0;i<ans.length;i++){\n            int size=queries[i][1];\n            int p=queries[i][0];\n            \n            int start=binarySearch(rooms,size);\n            if(start==-1){\n                ans[i]=-1;\n                continue;\n            }\n            \n            int index=find(rooms,start,p);\n            ans[i]=rooms[index][0];\n        }\n        return ans;\n    }\n    \n    private int find(int[][] rooms,int start,int p){\n        int ans=start;\n        int min=Math.abs(rooms[start][0]-p);\n        for(int i=start+1;i<rooms.length;i++){\n            int diff=Math.abs(rooms[i][0]-p);\n            if(diff<min){\n                min=diff;\n                ans=i;\n            }else if(diff==min){\n                if(rooms[i][0]<rooms[ans][0]){\n                    ans=i;\n                }\n            }\n        }\n        return ans;\n    }\n    \n    private int binarySearch(int[][] rooms,int size){\n        int lo=0 , hi=rooms.length-1;\n        int ans=-1;\n        while(lo<=hi){\n            int mid=lo + (hi-lo)/2;\n            \n            if(rooms[mid][1]<size){\n                lo=mid+1;\n            }else{\n                ans=mid;\n                hi=mid-1;\n            }\n        }\n        return ans;\n    }\n    \n    public class Pair implements Comparator<int[]>{\n        public int compare(int[] one,int[] two){\n            return one[1]-two[1];\n        }\n    }\n}\n```\n\n**Complexity:**\n`Time:O(nlogn + m* (logn + n) ) where n:rooms.length , m=queries.length`\n`Space:O(1) if not considered answer array which we have to return)`\n\nPlease **UPVOTE** if found it helpful and feel free to comment down or reach out to me if you have any doubt.
['Sorting', 'Binary Tree', 'Java']