#2503

Maximum Number of Points From Grid Queries

Hard
ArrayTwo PointersBreadth-First SearchUnion-FindSortingHeap (Priority Queue)MatrixSortingBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n log(m * n) + k log k)
Space
O(m * n)
O(m * n)
💡

Intuition

Time O(m * n log(m * n) + k log k)Space O(m * n)

In the optimal solution, we will sort the queries and use a priority queue to efficiently explore the grid. By processing the queries in ascending order, we can avoid redundant calculations and only explore cells that are relevant to the current query.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of all cells in the grid with their values and sort them.
  2. 2Step 2: Sort the queries and keep track of their original indices.
  3. 3Step 3: Use a priority queue to process cells in ascending order of their values, while keeping track of the number of points for each query based on the cells that have been processed.
solution.py28 lines
1# Full working Python code
2from collections import deque
3import heapq
4
5def maxPointsOptimal(grid, queries):
6    m, n = len(grid), len(grid[0])
7    cells = [(grid[i][j], i, j) for i in range(m) for j in range(n)]
8    cells.sort()
9    sorted_queries = sorted((q, i) for i, q in enumerate(queries))
10    results = [0] * len(queries)
11    visited = set()
12    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
13    points = 0
14    queue = deque([(0, 0)])
15
16    for query, original_index in sorted_queries:
17        while queue and grid[0][0] < query:
18            x, y = queue.popleft()
19            if (x, y) in visited:
20                continue
21            visited.add((x, y))
22            points += 1
23            for dx, dy in directions:
24                nx, ny = x + dx, y + dy
25                if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and grid[nx][ny] < query:
26                    queue.append((nx, ny))
27        results[original_index] = points
28    return results

Complexity note: The time complexity is O(m * n log(m * n)) for sorting the cells and O(k log k) for sorting the queries. The space complexity is O(m * n) for storing the visited cells.

  • 1Sorting the cells allows us to efficiently determine which cells can be visited for each query.
  • 2Using a visited set prevents counting the same cell multiple times, optimizing the point calculation.

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