Skip to content

Commit a5d3c4f

Browse files
committed
add optimised method
1 parent bbed1a1 commit a5d3c4f

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
File renamed without changes.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def numberOfPairs(self, points: List[List[int]]) -> int:
3+
points.sort(key=lambda x: (x[0], -x[1]))
4+
5+
output = 0
6+
# Top left
7+
for i, (_, y1) in enumerate(points) :
8+
# top right
9+
min_y = -inf
10+
for j, (_, y2) in enumerate(points[i + 1:], i + 1) :
11+
if min_y < y2 <= y1 :
12+
output += 1
13+
min_y = y2
14+
if y1 == min_y :
15+
break
16+
17+
return output

my-submissions/m3025.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,58 @@
1+
## V1
2+
13
Points sorted by $x$ then $-y$ since minimizing $x$ gives us the "leftmost" points and $-y$ gives us a secondary sorting based on the largest $y$ values. This lets us iterate and only check points right of a point in the list since any others are either left or above meaning the pairing has already been checked.
24

35
Since the points are sorted in such a manner, when comparing two points the only points that could be "between" are those between the two in the points[] array since values that are between $x$-wise will be sorted between them first and $y$-wise as a secondary case.
6+
7+
It basically allows us to auto-ignore any points found in quadrant-1 relative to the current top-left point (see below).
8+
9+
```
10+
For (A, B)
11+
12+
||xxxxxxx|
13+
||xxxxxxx|
14+
||xxxxxxx|
15+
||xxxxxxx|
16+
||xxxxxxx|
17+
||-------A------------------
18+
|| | |
19+
|| |--------B
20+
|| |
21+
|| |
22+
====||========================
23+
||
24+
||
25+
```
26+
27+
Given the sorting, we can ignore the xxx section.
28+
29+
## V2
30+
31+
To optimize from V1, we can remove the check for $x$ since we've already sorted the array based on $x$.
32+
33+
We can also remove the iteration of `all(...)` since the sorted list means that points will be checked left to right, top to bottom. This means that any next point will expand rightwards or be equal rightwards (if equal, lower... meaning that it fails the empty space condition). The only farther right cases that are valid as you iterate are those that close the vertical gap since it prevents overlap. For instance, see the below:
34+
35+
```
36+
For (A, B)
37+
38+
|| |
39+
|| |
40+
|| |
41+
|| |
42+
|| |
43+
||-------a-------------------------------
44+
|| | | | | |
45+
|| | | | |--------------d
46+
|| | | | |
47+
|| | | |-----c
48+
|| | | |
49+
|| | | |
50+
|| | |---c
51+
|| | |
52+
|| |-----b
53+
|| |
54+
|| |
55+
====||======================================
56+
||
57+
||
58+
```

0 commit comments

Comments
 (0)