Skip to content

Commit 641b950

Browse files
solutions and notes for problem 2582
1 parent 54d9be0 commit 641b950

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

problems/2582/paxtonfitzpatrick.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,38 @@
22

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

5+
- seems pretty straightforward
6+
- definitely going to be using modulo operator
7+
- both for figuring out how many people from one end or the other who has the pillow and figuring out whether the current direction is forwards or backwards
8+
- actually, it's probably not optimal, but `itertools.cycle` could do this pretty easily
9+
- let's try that approach first as a baseline
10+
- trick here is to start with an iterable of `n` elements, but then extend it with items at indices `n-2` backwards through `1` so we don't repeat the first and last elements
11+
- I think I can use `itertools.chain` to extend the iterable with a reversed partial copy like this without ever actually constructing it in memory.
12+
- Also, `n` and/or `time` are really large, it might be better to use `itertools.islice` rather than acutally running the loop `time` times...
13+
514
## Refining the problem
615

16+
- Let's try the non-`itertools` way now.
17+
- first figure out how many people from one end or the other the pillow will be at time `time`
18+
- then figure out whether we're currently going in the forward or backward direction
19+
720
## Attempted solution(s)
21+
22+
```python
23+
from itertools import chain, cycle, islice
24+
25+
class Solution:
26+
def passThePillow(self, n: int, time: int) -> int:
27+
return next(islice(cycle(chain(range(1, n + 1), reversed(range(2, n)))), time, None))
28+
```
29+
30+
![](https://github.com/paxtonfitzpatrick/leetcode-solutions/assets/26118297/07156d7a-fa66-49a7-b6fb-389acaf66907)
31+
32+
```python
33+
class Solution:
34+
def passThePillow(self, n: int, time: int) -> int:
35+
offset = time % (n - 1)
36+
return (n - offset) if time // (n - 1) % 2 else (offset + 1)
37+
```
38+
39+
![](https://github.com/paxtonfitzpatrick/leetcode-solutions/assets/26118297/a96a6dc1-0852-4d3b-8c60-d1c997aea142)

0 commit comments

Comments
 (0)