Magicsheet logo

Find the Number of Ways to Place People II

Hard
25%
Updated 8/1/2025

Find the Number of Ways to Place People II

1. What is this problem about?

The Find the Number of Ways to Place People II interview question is the more advanced version of the previous task. The rules remain the same: find pairs (A,B)(A, B) forming a rectangle where AA is top-left, BB is bottom-right, and no one else is inside. However, the constraints are much larger (NN up to 1000 or more), requiring a highly optimized approach. You need to ensure the solution stays within O(N2)O(N^2) or O(NlogN)O(N \log N).

2. Why is this asked in interviews?

Uber and Google ask the Find the Number of Ways to Place People II coding problem to see if a candidate can optimize a spatial search beyond simple iteration. It requires a clever use of Monotonicity or efficient data structures to prune the search space. It evaluates your ability to maintain state while scanning points, a core skill for high-performance engineering.

3. Algorithmic pattern used

This problem follows the Sorting and Optimized Scanning pattern.

  • Primary Sort: xx ascending, yy descending.
  • Scanning: For each fixed ii, as you move jj from i+1i+1 to n1n-1:
    • A point jj is a valid bottom-right if yjyiy_j \leq y_i AND yjy_j is the largest Y-coordinate seen so far among all points kk where xixkxjx_i \leq x_k \leq x_j.
    • By maintaining a variable max_y_seen, you can validate each jj in O(1)O(1) during the inner loop.
    • This ensures the inner check doesn't need to look at all previous points, keeping the complexity at O(N2)O(N^2).

4. Example explanation

Points: P1(0, 10), P2(1, 5), P3(2, 7).

  • Sort: P1, P2, P3.
  • Fix i=P1i=P1.
  • j=P2j=P2: y2=510y_2=5 \leq 10. max_y_seen was -\infty. 5>5 > -\infty, so P1P2P1-P2 is valid. max_y_seen = 5.
  • j=P3j=P3: y3=710y_3=7 \leq 10. max_y_seen is 5. 7>57 > 5, so P1P3P1-P3 is valid. max_y_seen = 7.
  • If a point P4(1.5, 6) existed, when checking P3, max_y_seen would have been 6. Since 7>67 > 6, it would still be valid? No, because P4P4 would be inside the P1P3P1-P3 rectangle. The max_y_seen logic prevents this.

5. Common mistakes candidates make

  • Using Segment Trees unnecessarily: While a Segment Tree can solve this, it is often over-engineering if a simple variable can track the required range property during a sorted scan.
  • Incorrect Boundary handling: Forgetting that points on the edge of the rectangle also count as being "inside."
  • Sorting confusion: Not handling the case where multiple points have the same X-coordinate.

6. Interview preparation tip

When optimizing O(N2)O(N^2) grid problems, look for "prefix" or "running" properties. If you can update your validity condition as you move your pointer, you can avoid an extra nested loop. This is a vital Enumeration interview pattern.

Similar Questions