Count Artifacts That Can Be Extracted — LeetCode 2201 Python Solution

MediumArrayHash TableSimulation
Problem
#2201
Pattern
Hash Map
Reading time
3 min

The problem

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] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried in the subgrid where: (r1i, c1i) is the coordinate of the top-left cell of the ith artifact and (r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact.

Example

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.

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(m + k)
SpaceO(k) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2201. Count Artifacts That Can Be Extracted is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2201. Count Artifacts That Can Be Extracted?
LeetCode 2201. Count Artifacts That Can Be Extracted is rated Medium on LeetCode.
What is the time complexity of LeetCode 2201. Count Artifacts That Can Be Extracted?
The Python solution on this page runs in O(m + k).
What is the space complexity of LeetCode 2201. Count Artifacts That Can Be Extracted?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 2201. Count Artifacts That Can Be Extracted cover?
LeetCode 2201. Count Artifacts That Can Be Extracted is tagged Array, Hash Table and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview