#3027
Find the Number of Ways to Place People II
HardArrayMathGeometrySortingEnumerationSortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the points and using a single loop, we can efficiently count valid pairs without needing to check every combination. This reduces the time complexity significantly.
⚙️
Algorithm
6 steps- 1Step 1: Sort the points by x-coordinate in non-decreasing order and by y-coordinate in non-increasing order.
- 2Step 2: Initialize a count variable to 0.
- 3Step 3: Use a nested loop to iterate through pairs of points (i, j) where i < j.
- 4Step 4: For each pair, check if points[i][0] <= points[j][0] and points[i][1] >= points[j][1].
- 5Step 5: If valid, increment the count.
- 6Step 6: Return the count.
solution.py12 lines
1# Full working Python code
2
3def count_valid_pairs(points):
4 points.sort(key=lambda p: (p[0], -p[1]))
5 count = 0
6 n = len(points)
7 for i in range(n):
8 for j in range(i + 1, n):
9 if points[i][0] <= points[j][0] and points[i][1] >= points[j][1]:
10 count += 1
11 return count
12ℹ
Complexity note: The sorting step takes O(n log n) time, and the nested loop runs in O(n²) in the worst case, but the sorting helps us reduce unnecessary checks.
- 1Sorting the points helps in efficiently determining valid pairs.
- 2The conditions for valid pairs are based on the relative positions of the points in the sorted order.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.