K Highest Ranked Items Within a Price Range - Problem
You are given a 0-indexed 2D integer array grid of size m × n that represents a map of items in a shop. The integers in the grid represent:
0represents a wall that you cannot pass through1represents an empty cell that you can freely move to and from- All other positive integers represent the price of an item in that cell
It takes 1 step to travel between adjacent grid cells (up, down, left, right).
You are given integer arrays pricing = [low, high] and start = [row, col] indicating your starting position and price range of interest. You are also given an integer k.
Find the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first differing criteria:
- Distance: shorter distance from start has higher rank
- Price: lower price has higher rank (within price range)
- Row number: smaller row number has higher rank
- Column number: smaller column number has higher rank
Return the k highest-ranked items within the price range sorted by rank. If fewer than k items exist, return all of them.
Input & Output
Example 1 — Basic Case
$
Input:
grid = [[1,2,3,1],[1,2,3,1],[1,2,3,1]], pricing = [2,3], start = [0,1], k = 3
›
Output:
[[0,1],[0,2],[1,1]]
💡 Note:
Start at [0,1] with price=2 (dist=0). Next closest are [0,2] price=3 (dist=1) and [1,1] price=2 (dist=1). Since [1,1] has lower price, it ranks higher than [0,2].
Example 2 — Different Start Position
$
Input:
grid = [[1,2,3,1],[1,2,3,1],[1,2,3,1]], pricing = [2,3], start = [2,1], k = 2
›
Output:
[[2,1],[1,1]]
💡 Note:
Start at [2,1] with price=2. Closest item with same distance and price is [1,1] price=2. Both have distance 0 and 1 respectively.
Example 3 — Limited Items in Range
$
Input:
grid = [[1,5,7,1],[1,2,3,1]], pricing = [2,3], start = [0,1], k = 5
›
Output:
[[1,1],[1,2]]
💡 Note:
Only 2 items are in price range [2,3]: [1,1] with price=2 and [1,2] with price=3. Return all available items even though k=5.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 105
- 1 ≤ m × n ≤ 105
- 0 ≤ grid[i][j] ≤ 105
- pricing.length == 2
- 2 ≤ low ≤ high ≤ 105
- start.length == 2
- 0 ≤ row ≤ m - 1
- 0 ≤ col ≤ n - 1
- grid[row][col] > 0
- 1 ≤ k ≤ m × n
Visualization
Tap to expand
Understanding the Visualization
1
Input
Grid with items, start position [0,1], price range [2,3], k=3
2
BFS + Filter
Find all reachable items within price range with distances
3
Sort + Select
Sort by ranking criteria and return top k items
Key Takeaway
🎯 Key Insight: BFS naturally provides distances, then multi-criteria sorting gives us the k highest-ranked items
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code