- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 73 lines of Python from the credited upstream file 353.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class SnakeGame:2 def __init__(self, width: int, height: int, food: list[list[int]]):3 """4 Initialize your data structure here.5 @param width - screen width6 @param height - screen height7 @param food - A list of food positions8 E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].9 """10 self.width = width11 self.height = height12 self.food = food13 self.score = 014 self.k = 0 15 self.lookup = set([self.getId(0, 0)])16 self.body = collections.deque([self.getId(0, 0)]) 17 18 def move(self, direction: str) -> int:19 """20 Moves the snake.21 @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down22 @return The game's score after the move. Return -1 if game over.23 Game over when snake crosses the screen boundary or bites its body.24 """25 26 i = self.body[0] self.width27 j = self.body[0] % self.width28 29 30 if direction == "U":31 i -= 132 if i < 0:33 return -134 if direction == "L":35 j -= 136 if j < 0:37 return -138 if direction == "R":39 j += 140 if j == self.width:41 return -142 if direction == "D":43 i += 144 if i == self.height:45 return -146 47 newHead = self.getId(i, j)48 49 50 if self.k < len(self.food) and i == self.food[self.k][0] and j == self.food[self.k][1]:51 self.lookup.add(newHead)52 self.body.appendleft(newHead)53 self.k += 154 self.score += 155 return self.score56 57 58 if newHead != self.body[-1] and newHead in self.lookup:59 return -160 61 62 63 64 self.lookup.remove(self.body[-1])65 self.lookup.add(newHead)66 self.body.pop()67 self.body.appendleft(newHead)68 69 return self.score70 71 def getId(self, i: int, j: int) -> int:72 return i * self.width + j73