Skip to content

2146. K Highest Ranked Items Within a Price Range

  • Time: $O(\texttt{sort}(mn))$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
 public:
  vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid,
                                          vector<int>& pricing,
                                          vector<int>& start, int k) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = grid.size();
    const int n = grid[0].size();
    const int low = pricing[0];
    const int high = pricing[1];
    const int row = start[0];
    const int col = start[1];
    vector<vector<int>> ans;

    if (low <= grid[row][col] && grid[row][col] <= high) {
      ans.push_back({row, col});
      if (k == 1)
        return ans;
    }

    queue<pair<int, int>> q{{{row, col}}};
    vector<vector<bool>> seen(m, vector<bool>(n));
    seen[row][col] = true;  // Mark as visited.

    while (!q.empty()) {
      vector<vector<int>> neighbors;
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [i, j] = q.front();
        q.pop();
        for (const auto& [dx, dy] : dirs) {
          const int x = i + dx;
          const int y = j + dy;
          if (x < 0 || x == m || y < 0 || y == n)
            continue;
          if (!grid[x][y] || seen[x][y])
            continue;
          if (low <= grid[x][y] && grid[x][y] <= high)
            neighbors.push_back({x, y});
          q.emplace(x, y);
          seen[x][y] = true;
        }
      }
      ranges::sort(neighbors, [&](const vector<int>& a, const vector<int>& b) {
        const int x1 = a[0];
        const int y1 = a[1];
        const int x2 = b[0];
        const int y2 = b[1];
        if (grid[x1][y1] != grid[x2][y2])
          return grid[x1][y1] < grid[x2][y2];
        return x1 == x2 ? y1 < y2 : x1 < x2;
      });
      for (const vector<int>& neighbor : neighbors) {
        if (ans.size() < k)
          ans.push_back(neighbor);
        if (ans.size() == k)
          return ans;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
  public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int m = grid.length;
    final int n = grid[0].length;
    final int low = pricing[0];
    final int high = pricing[1];
    final int row = start[0];
    final int col = start[1];
    List<List<Integer>> ans = new ArrayList<>();

    if (low <= grid[row][col] && grid[row][col] <= high) {
      ans.add(Arrays.asList(row, col));
      if (k == 1)
        return ans;
    }

    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(row, col)));
    boolean[][] seen = new boolean[m][n];
    seen[row][col] = true; // Mark as visited.

    while (!q.isEmpty()) {
      List<List<Integer>> neighbors = new ArrayList<>();
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.peek().getKey();
        final int j = q.poll().getValue();
        for (int[] dir : dirs) {
          final int x = i + dir[0];
          final int y = j + dir[1];
          if (x < 0 || x == m || y < 0 || y == n)
            continue;
          if (grid[x][y] == 0 || seen[x][y])
            continue;
          if (low <= grid[x][y] && grid[x][y] <= high)
            neighbors.add(Arrays.asList(x, y));
          q.offer(new Pair<>(x, y));
          seen[x][y] = true;
        }
      }
      Collections.sort(neighbors, new Comparator<List<Integer>>() {
        @Override
        public int compare(List<Integer> a, List<Integer> b) {
          final int x1 = a.get(0);
          final int y1 = a.get(1);
          final int x2 = b.get(0);
          final int y2 = b.get(1);
          if (grid[x1][y1] != grid[x2][y2])
            return grid[x1][y1] - grid[x2][y2];
          return x1 == x2 ? y1 - y2 : x1 - x2;
        }
      });
      for (List<Integer> neighbor : neighbors) {
        if (ans.size() < k)
          ans.add(neighbor);
        if (ans.size() == k)
          return ans;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution:
  def highestRankedKItems(self, grid: list[list[int]],
                          pricing: list[int],
                          start: list[int],
                          k: int) -> list[list[int]]:
    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    m = len(grid)
    n = len(grid[0])
    low, high = pricing
    row, col = start
    ans = []

    if low <= grid[row][col] <= high:
      ans.append([row, col])
      if k == 1:
        return ans

    q = collections.deque([(row, col)])
    seen = {(row, col)}  # Mark as visited.

    while q:
      neighbors = []
      for _ in range(len(q)):
        i, j = q.popleft()
        for t in range(4):
          x = i + dirs[t]
          y = j + dirs[t + 1]
          if x < 0 or x == m or y < 0 or y == n:
            continue
          if not grid[x][y] or (x, y) in seen:
            continue
          if low <= grid[x][y] <= high:
            neighbors.append([x, y])
          q.append((x, y))
          seen.add((x, y))
      neighbors.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1]))
      for neighbor in neighbors:
        if len(ans) < k:
          ans.append(neighbor)
        if len(ans) == k:
          return ans

    return ans