Leetcode #2503: Maximum Number of Points From Grid Queries
In this guide, we solve Leetcode #2503 Maximum Number of Points From Grid Queries in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an m x n integer matrix grid and an array queries of size k. Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process: If queries[i] is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4 directions: up, down, left, and right.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Breadth-First Search, Union Find, Array, Two Pointers, Matrix, Sorting, Heap (Priority Queue)
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]
Output: [5,8,1]
Explanation: The diagrams above show which cells we visit to get points for each query.
Python Solution
class Solution:
def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:
m, n = len(grid), len(grid[0])
qs = sorted((v, i) for i, v in enumerate(queries))
ans = [0] * len(qs)
q = [(grid[0][0], 0, 0)]
cnt = 0
vis = [[False] * n for _ in range(m)]
vis[0][0] = True
for v, k in qs:
while q and q[0][0] < v:
_, i, j = heappop(q)
cnt += 1
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and not vis[x][y]:
heappush(q, (grid[x][y], x, y))
vis[x][y] = True
ans[k] = cnt
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.