#2201

Count Artifacts That Can Be Extracted

Medium
ArrayHash TableSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal solution, we can utilize a set to quickly check if all parts of an artifact have been excavated. This reduces the need for nested loops and improves efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set of excavated cells from the dig array.
  2. 2Step 2: For each artifact, use a single loop to check if all its coordinates are in the excavated set.
  3. 3Step 3: Count the number of artifacts that can be extracted.
solution.py3 lines
1def countArtifacts(n, artifacts, dig):
2    excavated = set(tuple(d) for d in dig)
3    return sum(1 for r1, c1, r2, c2 in artifacts if all((r, c) in excavated for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)))

Complexity note: The time complexity is O(n) because we efficiently check each artifact against the excavated cells using a set. The space complexity remains O(n) for storing the excavated cells.

  • 1Using a set for quick lookups significantly reduces the time complexity.
  • 2Understanding the problem constraints helps in choosing the right data structures.

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