Java | Sort and Loop through arrays| Explained with Comments
\nclass Solution {\n    public int[] closestRoom(int[][] rooms, int[][] queries) {\n        //If you do not sort then we will have to scan all romes. Best is to
```\nclass Solution {\n    public int[] closestRoom(int[][] rooms, int[][] queries) {\n        //If you do not sort then we will have to scan all romes. Best is to sort. so we can break loop early when we hit values that wont satisfy the min space.\n        //If did not do this at first place and hit TLE\n        Arrays.sort(rooms, (r1,r2) -> Integer.compare(r2[1], r1[1]));\n        \n        int[] result = new int[queries.length];\n        \n        int resultIndex = 0;\n        //For each query\n        for(int[] query : queries) {\n            int minId = -1;\n            int minIdDiff = Integer.MAX_VALUE;\n            //Loop through all rooms\n            for(int roomIndex = 0; roomIndex < rooms.length; roomIndex++) {\n                //if the space satisfies\n                if(query[1] <= rooms[roomIndex][1]) {\n                    //Find the difference in id\n                    int iDdiff = Math.abs(query[0] - rooms[roomIndex][0]);\n                    if(iDdiff < minIdDiff) {\n                        //If this diff is less than previus then use it\n                        minIdDiff = iDdiff;\n                        minId = rooms[roomIndex][0];\n                    } else if(iDdiff == minIdDiff) {\n                        //If this diff is equal than find if this is less than previous id. THis is the tie problem was talking about.\n                        //NOTE: You can merge some if-else conditions as you need. Seperated for readability.\n                        if(minId > rooms[roomIndex][0]) {\n                            minId = rooms[roomIndex][0];\n                        }\n                    }\n                } else { //if space does not satisfy then none to right satisfies and we can break the loop\n                    break;\n                }\n            }\n            //Assign the so far min id found. if not found it will be -1\n            result[resultIndex++] = minId;\n        }\n        //return the result array\n        return result;\n    }\n}\n```
[]