1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| # Helper function for binary search
def binary_search(arr, x):
left = 0
right = len(arr) - 1
answer_till_now = len(arr)
while left <= right:
mid = left + (right - left) // 2
if arr[mid] >= x:
answer_till_now = mid
right = mid - 1
else:
left = mid + 1
return answer_till_now
class Solution:
def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:
# Create a dictionary to map heights to the corresponding lengths of rectangles with that height
height_to_lengths = defaultdict(list)
for length, height in rectangles:
height_to_lengths[height].append(length)
# Sort the containers to apply binary search
for height, lengths in height_to_lengths.items():
lengths.sort()
answer = []
for point in points:
x, y = point
count = 0
# Iterate through the range of possible heights
for height in range(y, 101):
if height in height_to_lengths:
# Binary search returns the index in the array from which the values are >= x
# Subtract from the size of the array to get the number of rectangles that contain the point
count += len(height_to_lengths[height]) - binary_search(height_to_lengths[height], x)
answer.append(count)
return answer
|