#2146

K Highest Ranked Items Within a Price Range

Medium
ArrayBreadth-First SearchSortingHeap (Priority Queue)MatrixBreadth-First SearchSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using BFS allows us to efficiently explore the grid while keeping track of distances and prices. We can prioritize items based on distance and price without needing to check every cell multiple times.

⚙️

Algorithm

4 steps
  1. 1Step 1: Perform a BFS from the starting position to find all reachable cells and their distances.
  2. 2Step 2: Filter the reachable items based on the price range [low, high].
  3. 3Step 3: Sort the items based on the ranking criteria: distance, price, row, and column.
  4. 4Step 4: Return the top k items.
solution.py22 lines
1from collections import deque
2
3def highestRankedItems(grid, pricing, start, k):
4    m, n = len(grid), len(grid[0])
5    low, high = pricing
6    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
7    queue = deque([start])
8    visited = set([tuple(start)])
9    items = []
10
11    while queue:
12        x, y = queue.popleft()
13        if grid[x][y] != 0 and low <= grid[x][y] <= high:
14            items.append((grid[x][y], x, y))
15        for dx, dy in directions:
16            nx, ny = x + dx, y + dy
17            if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and grid[nx][ny] != 0:
18                visited.add((nx, ny))
19                queue.append((nx, ny))
20
21    items.sort(key=lambda item: (item[1], item[2], item[0]))
22    return items[:k]

Complexity note: The time complexity is O(n log n) due to the sorting step after collecting items. The space complexity is O(n) because we store all reachable items in a list.

  • 1Using BFS allows us to explore the grid efficiently while keeping track of distances.
  • 2Sorting based on multiple criteria can be done using custom sort functions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.