#1333
Filter Restaurants by Vegan-Friendly, Price and Distance
MediumArraySortingSortingFilteringArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a single pass to filter the restaurants and then sorts the filtered results. This is more efficient as it reduces the number of times we loop through the data.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty list to store the filtered restaurant IDs.
- 2Step 2: Loop through each restaurant and check if it meets the filtering criteria.
- 3Step 3: If it meets the criteria, add a tuple of (rating, id) to the result list.
- 4Step 4: Sort the result list by rating (descending) and then by ID (descending).
- 5Step 5: Extract and return only the IDs from the sorted list.
solution.py7 lines
1def filterRestaurants(restaurants, veganFriendly, maxPrice, maxDistance):
2 filtered = []
3 for r in restaurants:
4 if (veganFriendly == 0 or r[2] == 1) and r[3] <= maxPrice and r[4] <= maxDistance:
5 filtered.append((r[1], r[0]))
6 filtered.sort(key=lambda x: (-x[0], -x[1]))
7 return [id for _, id in filtered]ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step after filtering, while the filtering itself is O(n). The space complexity is O(n) because we store the filtered results before sorting.
- 1Filtering is crucial before sorting to reduce unnecessary computations.
- 2Sorting can be done efficiently using built-in functions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.