Filter Restaurants by Vegan-Friendly, Price and Distance - Problem
You're building a restaurant discovery app and need to implement a smart filtering system! ๐ด
Given an array of restaurants where each restaurants[i] = [id, rating, veganFriendly, price, distance], your task is to filter restaurants based on three criteria:
- Vegan Filter: If
veganFriendly = 1, only include vegan restaurants. IfveganFriendly = 0, include all restaurants - Price Filter: Only include restaurants where
price โค maxPrice - Distance Filter: Only include restaurants where
distance โค maxDistance
Goal: Return the restaurant IDs after filtering, sorted by:
- Rating (highest first) ๐
- For same ratings: ID (highest first) ๐ข
Note: veganFriendly values are 1 for true and 0 for false.
Input & Output
example_1.py โ Basic Filtering
$
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]]
veganFriendly = 1, maxPrice = 50, maxDistance = 10
โบ
Output:
[3,1,5]
๐ก Note:
Filtering for vegan restaurants (veganFriendly=1): restaurants 1,3,5 pass. After sorting by rating desc, then ID desc: restaurant 3 (rating 8), restaurant 1 (rating 4), restaurant 5 (rating 1).
example_2.py โ No Vegan Filter
$
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]]
veganFriendly = 0, maxPrice = 50, maxDistance = 10
โบ
Output:
[4,3,2,1,5]
๐ก Note:
No vegan filter (veganFriendly=0): all restaurants within price/distance limits pass. Sorted by rating: 4(10), 3(8), 2(8), 1(4), 5(1). For same rating 8, ID 3>2.
example_3.py โ Strict Distance Filter
$
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]]
veganFriendly = 0, maxPrice = 30, maxDistance = 3
โบ
Output:
[4,5]
๐ก Note:
Strict filters: only restaurants 4 (price=10, distance=3) and 5 (price=15, distance=1) qualify. Sorted by rating: 4(10), 5(1).
Constraints
- 1 โค restaurants.length โค 104
- restaurants[i].length == 5
- 1 โค idi, ratingi, pricei, distancei โค 105
- 1 โค maxPrice, maxDistance โค 105
- veganFriendlyi and veganFriendly are 0 or 1
- All values are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Apply Filters
Check each restaurant against vegan, price, and distance criteria in a single pass
2
Collect Results
Gather all restaurants that meet the filtering criteria
3
Smart Sorting
Sort by rating (best first), then by ID (highest first) for ties
4
Return IDs
Extract and return only the restaurant IDs in the final ranked order
Key Takeaway
๐ฏ Key Insight: This problem combines filtering with custom sorting. The optimal approach uses single-pass filtering (O(n)) followed by efficient sorting (O(n log n)), making it perfect for real-world recommendation systems that need to quickly process user preferences and return ranked results.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code