Skip to content

Commit 2439892

Browse files
solutions and notes for problem 1380
1 parent 4c94d5b commit 2439892

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

problems/1380/paxtonfitzpatrick.md

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,54 @@
22

33
## Initial thoughts (stream-of-consciousness)
44

5+
- Yay, finally a non-tree problem! This seems pretty straightforward
6+
- Native solution: find the min of each row, find the max of each column, return values in both
7+
- But we don't actually have to process every column, just the ones that contain a row min.
8+
- This would take some additional logic to write, so it may not actually end up being faster
9+
- If we wanted to add even more logic to further optimize this, we could choose whether to constrain rows based on columns or columns based on rows, depending on which there are more of (the one with fewer is the one we should process each of then use to constrain the other)
10+
- I'll try implementing each of these 3 solutions to see whether the tradeoffs are worth it
11+
512
## Refining the problem, round 2 thoughts
613

714
## Attempted solution(s)
15+
16+
### naive solution
17+
818
```python
9-
class Solution: # paste your code here!
10-
...
19+
class Solution:
20+
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
21+
row_mins = {min(row) for row in matrix}
22+
col_maxes = {max(col) for col in zip(*matrix)}
23+
return list(row_mins & col_maxes)
24+
1125
```
26+
27+
![](https://github.com/user-attachments/assets/4964fc30-5772-41a0-83b1-d2cceb52f6fb)
28+
29+
Huh, didn't expect that to be that fast.
30+
31+
**Update:** this was a low runtime/high memory outlier. I ran it 4 more times and the mean runtime over 5 runs was **107.8 ms, 16.79 MB memory**.
32+
33+
### optimized solution 1
34+
35+
```python
36+
class Solution:
37+
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
38+
n_cols = len(matrix[0])
39+
row_mins = set()
40+
row_min_ixs = set()
41+
for row_ix, row in enumerate(matrix):
42+
row_min_ix = min(range(n_cols), key=row.__getitem__)
43+
row_min_ixs.add(row_min_ix)
44+
row_mins.add(row[row_min_ix])
45+
result = []
46+
for col_ix in row_min_ixs:
47+
col_max = max([row[col_ix] for row in matrix])
48+
if col_max in row_mins:
49+
result.append(col_max)
50+
return result
51+
```
52+
53+
![](https://github.com/user-attachments/assets/478db6d7-02b7-498f-abed-e9fc38d59ce3)
54+
55+
Mean over 5 runs: **107.4 ms, 16.90 MB memory**. So really no appreciable difference. Given that, I'm not gonna bother with the third version.

0 commit comments

Comments
 (0)