Count Number of Rectangles Containing Each Point — LeetCode 2250 Python Solution

MediumBinary Indexed TreeArrayHash TableBinary SearchSorting
Problem
#2250
Reading time
3 min

The problem

You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).

Example

Input
rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]
Output
[2,1]
Explanation
The first rectangle contains no points.

Python solution

Python
class Solution:
    def countRectangles(
        self, rectangles: List[List[int]], points: List[List[int]]
    ) -> List[int]:
        d = defaultdict(list)
        for x, y in rectangles:
            d[y].append(x)
        for y in d.keys():
            d[y].sort()
        ans = []
        for x, y in points:
            cnt = 0
            for h in range(y, 101):
                xs = d[h]
                cnt += len(xs) - bisect_left(xs, x)
            ans.append(cnt)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 2250. Count Number of Rectangles Containing Each Point is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2250. Count Number of Rectangles Containing Each Point?
LeetCode 2250. Count Number of Rectangles Containing Each Point is rated Medium on LeetCode.
What is the time complexity of LeetCode 2250. Count Number of Rectangles Containing Each Point?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2250. Count Number of Rectangles Containing Each Point?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2250. Count Number of Rectangles Containing Each Point cover?
LeetCode 2250. Count Number of Rectangles Containing Each Point is tagged Binary Indexed Tree, Array, Hash Table, Binary Search and Sorting 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