#2250
Count Number of Rectangles Containing Each Point
MediumArrayHash TableBinary SearchBinary Indexed TreeSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n + m)Space O(1)
We can optimize the solution by sorting rectangles by their lengths and using a frequency array for heights to quickly count how many rectangles contain a given point's height.
⚙️
Algorithm
5 steps- 1Step 1: Create a frequency array for heights (0 to 100) initialized to zero.
- 2Step 2: Sort rectangles by their lengths.
- 3Step 3: For each rectangle, update the frequency array for heights up to the rectangle's height.
- 4Step 4: For each point, count how many rectangles can contain it using the frequency array.
- 5Step 5: Return the result list.
solution.py9 lines
1def countRectangles(rectangles, points):
2 height_count = [0] * 101
3 for l, h in rectangles:
4 for i in range(h + 1):
5 height_count[i] += 1
6 result = []
7 for px, py in points:
8 result.append(height_count[py] if px <= 100 else 0)
9 return resultℹ
Complexity note: The time complexity is O(n + m) because we process all rectangles once and then all points once, making it linear with respect to the input sizes.
- 1Height frequency can be used to quickly count rectangles for points.
- 2Sorting rectangles by length helps in efficiently managing point checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.