You are given a set of rectangles, each defined by its width and height . You are also given a set of points. For each point , you need to count how many rectangles cover it. A rectangle covers a point if and .
This problem is asked by Meta and Amazon to test a candidate's ability to use sorting and binary search to optimize a multi-dimensional search problem. The key insight is that the height is typically constrained to a small range (e.g., 1 to 100), while the width and number of points can be large. This constraint allows for a hybrid approach.
This is a Binary Search and Sorting problem.
bisect_left or lower_bound) to find how many widths are .Rectangles: (5, 2), (10, 2), (10, 5). Point: (6, 2).
The most common mistake is treating it as a pure 2D geometry problem and trying to use a 2D Segment Tree or Fenwick Tree, which is overkill and hard to implement. Another mistake is ignoring the height constraint and trying to sort everything by width, which doesn't simplify the height check. Failing to sort the widths for binary search is also a frequent bug.
Look for small constraints! If one dimension of a 2D problem is very small (like height ), you can often use a simple loop over that dimension and optimize the other dimension with a standard 1D algorithm like binary search.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Fair Candy Swap | Easy | Solve | |
| Longest Square Streak in an Array | Medium | Solve | |
| Maximize the Profit as the Salesman | Medium | Solve | |
| Maximum Number of Integers to Choose From a Range I | Medium | Solve | |
| K-diff Pairs in an Array | Medium | Solve |