Skip to content

Commit 2093707

Browse files
solutions and notes for problem 2418
1 parent e000253 commit 2093707

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

problems/2418/paxtonfitzpatrick.md

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

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

5+
- great, this seems easy. I know there's a concise syntax for sorting one list by another in Python; let's see if I can remember it...
6+
- I very much doubt we'll be able to beat Python's built-in sorting algorithm with some creative approach here, since [`powersort`](https://docs.python.org/release/3.11.0/whatsnew/changelog.html#id100:~:text=bpo%2D34561%3A%20List,strategy%20did%20better.) is $O(n \log n)$, implemented in C, and heavily optimized
7+
58
## Refining the problem, round 2 thoughts
69

710
## Attempted solution(s)
11+
12+
```python
13+
class Solution:
14+
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
15+
return [name for _, name in sorted(zip(heights, names), reverse=True)]
16+
```
17+
18+
![](https://github.com/user-attachments/assets/8782eafa-49d9-4730-ac9d-34f2c7d2caa3)
19+
20+
Huh, I'm surprised that only beat ~50% of submissions. Someone must've found a faster way... let me try something real quick...
21+
822
```python
9-
class Solution: # paste your code here!
10-
...
23+
class Solution:
24+
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
25+
return (name for _, name in sorted(zip(heights, names), reverse=True))
1126
```
27+
28+
29+
![](https://github.com/user-attachments/assets/cc74f20d-e7f0-4f74-83df-7ad6656e02aa)
30+
31+
Aha -- whatever code Leetcode runs on the backend to evaluate submissions will accept a generator when the question calls for a list/array. That's a cheesy but kinda neat trick to remember for the future. Let's try one more thing just for curiosity's sake:
32+
33+
```python
34+
class Solution:
35+
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
36+
for _, name in sorted(zip(heights, names), reverse=True):
37+
yield name
38+
```
39+
40+
![](https://github.com/user-attachments/assets/40258f4e-e24c-49a9-8e0d-a9bcebd75945)
41+
42+
Cool, that's what I kinda expected would happen -- better memory performance since we now aren't even constructing the generator object in memory, but slightly slower runtime because the function itself is now a Python-level generator instead of a built-in/internally optimized generator expression.

0 commit comments

Comments
 (0)