MediumNo. 1333

Filter Restaurants by Vegan-Friendly, Price and Distance — LeetCode 1333 Python Solution

Pattern
Sorting
Topics
Array, Sorting
Reading time
3 min

The problem

Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.

Example

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]
Explanation
The restaurants are:

Python solution

PythonSolution
class Solution:
    def filterRestaurants(
        self,
        restaurants: List[List[int]],
        veganFriendly: int,
        maxPrice: int,
        maxDistance: int,
    ) -> List[int]:
        restaurants.sort(key=lambda x: (-x[1], -x[0]))
        ans = []
        for idx, _, vegan, price, dist in restaurants:
            if vegan >= veganFriendly and price <= maxPrice and dist <= maxDistance:
                ans.append(idx)
        return ans

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1329Sort the Matrix DiagonallyMedium
0056Merge IntervalsMedium
0164Maximum GapMedium
0274H-IndexMedium
0406Queue Reconstruction by HeightMedium
0414Third Maximum NumberEasy

Frequently asked questions

How hard is LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance?

LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance is rated Medium on LeetCode.

What topics does LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance cover?

LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.