#3025

Find the Number of Ways to Place People I

Medium
ArrayMathGeometrySortingEnumerationSortingSetTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the points and using a data structure to track the points we've seen, we can efficiently count valid pairs without checking every rectangle.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the points based on x-coordinates, and then by y-coordinates.
  2. 2Step 2: Use a data structure (like a set) to keep track of y-coordinates of points we've seen.
  3. 3Step 3: For each point, count how many points in the set have a y-coordinate greater than the current point's y-coordinate.
solution.py8 lines
1def countPairs(points):
2    points.sort()  # Sort by x, then by y
3    count = 0
4    seen = set()
5    for x, y in points:
6        count += sum(1 for s in seen if s > y)
7        seen.add(y)
8    return count

Complexity note: The sorting step takes O(n log n), and maintaining the set takes O(n) in the worst case.

  • 1Sorting helps to systematically check pairs.
  • 2Using a set allows for efficient counting of valid y-coordinates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.