Problem
Given the array restaurants
where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]
. You have to filter the restaurants using three filters.
The veganFriendly
filter will be either true (meaning you should only include restaurants with veganFriendlyi
set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice
and maxDistance
which are the maximum value for price and distance of restaurants you should consider respectively.
Return the array of restaurant IDs after filtering, ordered by
rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi
and
veganFriendly
take value 1 when it is true , and 0 when it is false.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= restaurants.length <= 10^4
restaurants[i].length == 5
1 <= idi, ratingi, pricei, distancei <= 10^5
1 <= maxPrice, maxDistance <= 10^5
veganFriendlyi
andveganFriendly
are 0 or 1.- All
idi
are distinct.
Solution
Method 1 – Filtering and Sorting
Intuition
We filter the restaurants based on the vegan, price, and distance constraints, then sort the filtered list by rating (descending) and id (descending).
Approach
- Filter the restaurants:
- If veganFriendly == 1, only include those with veganFriendlyi == 1.
- Only include those with pricei <= maxPrice and distancei <= maxDistance.
- Sort the filtered restaurants by rating (descending), then by id (descending).
- Return the list of ids in the sorted order.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, where n is the number of restaurants, due to sorting. - 🧺 Space complexity:
O(n)
, for storing the filtered list.