Problem Description
Given an array of restaurants where each restaurant is represented as [id, rating, veganFriendly, price, distance], filter the restaurants based on three criteria: vegan-friendly flag, maximum price, and maximum distance. After filtering, return the list of restaurant IDs sorted by rating in descending order, and for restaurants with the same rating, sort by id in descending order.
Key Insights
- Filter restaurants using the veganFriendly flag (if set to 1, only include those with a veganFriendly flag of 1).
- Use the maxPrice and maxDistance to limit the selection.
- After filtering, sort the results first by rating (highest to lowest) and then by id (highest to lowest) when ratings are identical.
- Iterating over the list for filtering and then sorting leads to a time complexity of O(n log n).
Space and Time Complexity
Time Complexity: O(n log n) – Filtering takes O(n) and sorting takes O(n log n). Space Complexity: O(n) – In worst-case scenario, all restaurants meet the filter criteria.
Solution
To solve the problem, first traverse the list of restaurants and select only those restaurants that meet the criteria:
- If veganFriendly is set to 1, only restaurants with a veganFriendly value of 1 are accepted.
- The restaurant's price should be less than or equal to maxPrice.
- The restaurant's distance should be less than or equal to maxDistance. After filtering, sort the remaining restaurants by rating (in descending order) and then by id (in descending order in case of a tie in ratings). Finally, extract the id from each sorted restaurant and return the resulting list.