|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
4 | 4 |
|
| 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 | + |
5 | 14 | ## Refining the problem
|
6 | 15 |
|
| 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 | + |
7 | 20 | ## 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 | + |
| 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 | + |
0 commit comments