Count Artifacts That Can Be Extracted Problem
Description
LeetCode Problem 2201.
There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1_i, c1_i, r2_i, c2_i] denotes that the i^th artifact is buried in the subgrid where:
(r1_i, c1_i)is the coordinate of the top-left cell of thei^thartifact and(r2_i, c2_i)is the coordinate of the bottom-right cell of thei^thartifact.
You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it.
Given a 0-indexed 2D integer array dig where dig[i] = [r_i, c_i] indicates that you will excavate the cell (r_i, c_i), return the number of artifacts that you can extract.
The test cases are generated such that:
- No two artifacts overlap.
- Each artifact only covers at most
4cells. - The entries of
digare unique.
Example 1:

Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]
Output: 1
Explanation:
The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.
There is 1 artifact that can be extracted, namely the red artifact.
The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.
Thus, we return 1.
Example 2:

Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]
Output: 2
Explanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2.
Constraints:
1 <= n <= 10001 <= artifacts.length, dig.length <= min(n^2, 10^5)artifacts[i].length == 4dig[i].length == 20 <= r1_i, c1_i, r2_i, c2_i, r_i, c_i <= n - 1r1_i <= r2_ic1_i <= c2_i- No two artifacts will overlap.
- The number of cells covered by an artifact is at most
4. - The entries of
digare unique.
Solution
Approach: Hash table
Put every dug cell in a hash set. Then check each artifact: it can be extracted exactly when all of its cells are in the set. Count those artifacts. An artifact covers at most four cells, so each check is constant work.
Complexity: O(m + k) time and O(k) space, where m is the number of artifacts and k the number of dug cells.
class Solution:
def digArtifacts(
self, n: int, artifacts: List[List[int]], dig: List[List[int]]
) -> int:
def check(a: List[int]) -> bool:
x1, y1, x2, y2 = a
return all(
(x, y) in s for x in range(x1, x2 + 1) for y in range(y1, y2 + 1)
)
s = {(i, j) for i, j in dig}
return sum(check(a) for a in artifacts)