Crawling Worm Simulation: Track Length After Each Step
Data Structure DesignAuto-graded · 27 test casesLast updated
Tests precise deque-plus-set simulation of a growing worm on a grid, including the exact ordering of tail removal and collision detection.
Crawling Worm Simulation
A worm crawls around a rectangular grid of height rows and width columns. Rows and columns are both zero-indexed; the top-left cell is (0, 0). The worm begins as a single segment sitting on (0, 0) with a length score of 0.
Pellets appear on the grid one at a time, in the order given by food. Only the earliest uneaten pellet is present at any moment. The moment the worm consumes it, the next pellet in the list materialises. Once all pellets have been consumed, no new ones appear.
You are handed the complete list of moves up front. Simulate the worm's journey and return, for every move, either the current length score or -1 if the worm has already died.
Movement rules
Each character in moves shifts the worm's head one cell:
| Character | Direction |
|---|---|
U | row decreases by 1 |
D | row increases by 1 |
L | column decreases by 1 |
R | column increases by 1 |
All other segments slide forward: each one occupies the cell its predecessor just left.
For each move, apply the following steps in this exact order:
- Compute the destination cell for the head. If it falls outside the grid, the worm dies and the game ends.
- If the destination cell holds the current pellet, the worm eats it: the score increases by
1, the next pellet in the list (if any) becomes active, and the tail does not move (the worm grows by one segment). - If no pellet was eaten, the tail vacates its cell and the worm keeps its current length.
- If the destination cell is occupied by any segment that is still on the grid after step 2 or step 3, the worm has collided with itself and the game ends.
- Otherwise the head enters the destination cell and the move succeeds.
Important consequences of rule ordering
- Following your own tail is always legal on a non-eating move. Because the tail vacates its cell (step 3) before the collision check (step 4), the head may legally enter the cell the tail just left — even for a two-segment worm reversing direction.
- Eating onto the tail's cell is fatal. On an eating move the tail does not vacate (step 2 skips step 3), so that cell remains occupied and step 4 kills the worm.
- A pellet sitting beneath the worm's body is not consumed on arrival. Pellets are consumed only when the head moves onto their cell. A pellet that spawns under an existing body segment (including the head's own cell) simply waits there until the head steps onto it later.
Output
Return a list of exactly len(moves) integers:
- Entry
iequals the score after movei, if that move succeeded. - Entry
iequals-1if moveiends the game, or if the game had already ended before movei.
Constraints
1 <= width <= 10^41 <= height <= 10^40 <= len(food) <= 10^4- Each
food[i] = [r, c]satisfies0 <= r < heightand0 <= c < width. Pellet positions may repeat. 1 <= len(moves) <= 10^4- Every character in
movesis one ofU,D,L,R. - The score never exceeds
len(food), so every value in the output fits in a 32-bit signed integer.
Examples
Example 1
Input: worm_scores(4, 3, [[0, 2], [1, 2], [1, 1]], 'RRDLUL')
Output: [0, 1, 2, 3, 3, 3]
Example 2
Input: worm_scores(3, 3, [[0, 1], [0, 2], [1, 2], [1, 1]], 'RRDLUL')
Output: [1, 2, 3, 4, -1, -1]
Example 3
Input: worm_scores(2, 2, [[1, 1]], 'DRDU')
Output: [0, 1, -1, -1]
Hints
Hint 1
The tail removal and the collision check must happen in the right order. Ask yourself: on a non-eating move, should the tail cell be removed from your occupied set before or after you test whether the head's destination is free?
Hint 2
A deque handles the worm's body naturally — new head on the left, tail popped from the right, both in O(1). Pair it with a hash set of occupied cells so the self-collision check is also O(1) instead of a linear scan.
Hint 3
Avoid allocating a full height × width grid. With dimensions up to 10^4 each, that would be 10^8 cells. Store only the cells the worm actually occupies.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a direct simulation. The challenge is not the algorithm — it is choosing the right data structures and getting the rule ordering exactly right.
Data structures
Deque for the body. The worm's segments form a sequence where one end (the head) gains a cell and the other end (the tail) may lose one on every step. A deque supports both appendleft and pop in O(1), which is exactly the right fit.
Hash set for occupancy. To check whether the head's destination is already taken, scanning the deque would cost O(length). Instead, maintain a set occupied that always mirrors the cells in the deque. Membership tests on a set are O(1).
A single integer for the pellet queue. Only one pellet is active at a time, and pellets are consumed in order. An index fi into the food list is enough — no queue data structure needed.
Step-by-step logic per move
- Compute the destination cell
(nr, nc). If it is off the grid, mark the worm dead and append-1. - If
(nr, nc)matchesfood[fi], eat it: incrementscoreandfi, and leave the tail untouched. - Otherwise, pop the tail from the deque and remove it from
occupied. - If
(nr, nc)is now inoccupied, the worm collides with itself. Mark dead, append-1. - Otherwise, push
(nr, nc)onto the front of the deque and intooccupied, then append the currentscore.
Why the ordering is the whole problem
Steps 3 and 4 must happen in this order, not the reverse. If you tested for self-collision before removing the tail, a worm following its own tail would be wrongly killed — the tail's cell would still appear occupied. By removing the tail first (step 3) and checking afterward (step 4), the head is free to enter the cell the tail just vacated.
The eating case is the flip side: step 2 deliberately skips step 3, so the tail cell is never removed from occupied. If the head's destination happens to be the tail's cell on an eating move, step 4 correctly finds it occupied and ends the game.
A pellet that spawns beneath an existing body segment is harmless: pellets are only checked against the destination of the head, never against the current body. The pellet simply waits until the head steps onto its cell.
Why a plain set is safe
The invariant after every successful move is that all cells in body are distinct (no two segments share a cell). This holds because any move that would place the head on an occupied cell ends the game before the push. Because cells are always distinct, occupied.discard(tail) never accidentally removes a cell that another segment still needs.
Edge cases
- Immediate out-of-bounds (e.g. moving
UorLfrom(0, 0)): the first entry is-1and every subsequent entry is also-1. - 1×1 grid: every move leaves the board; the output is all
-1. - No food: the score stays
0; the worm just travels until it leaves the grid or hits itself. - Pellet at
(0, 0): it is under the starting head. The worm must leave and return to eat it. - Repeated pellet positions: no special handling needed.
fiadvances strictly forward, so each pellet is compared independently. - All pellets consumed early: the
fi < len(food)guard prevents an index-out-of-range error; remaining moves are plain travel steps.
Complexity
Time: O(len(moves)). Each move performs a constant number of deque and set operations.
Space: O(len(food) + len(moves)) for the body (grows by at most one segment per pellet) and the output list. The grid itself is never materialised, which matters because width × height can reach 10⁸.
Reference solution
from collections import deque
from typing import List
def worm_scores(width: int, height: int, food: List[List[int]], moves: str) -> List[int]:
body = deque([(0, 0)]) # head at body[0], tail at body[-1]
occupied = {(0, 0)} # mirror of body cells for O(1) collision checks
fi = 0 # index of the currently active pellet
score = 0
dead = False
out = []
delta = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
for ch in moves:
if dead:
out.append(-1)
continue
dr, dc = delta[ch]
hr, hc = body[0]
nr, nc = hr + dr, hc + dc
# Step 1: boundary check
if not (0 <= nr < height and 0 <= nc < width):
dead = True
out.append(-1)
continue
# Step 2 / Step 3: eat the pellet (tail stays) or vacate the tail
if fi < len(food) and food[fi][0] == nr and food[fi][1] == nc:
score += 1
fi += 1
# tail intentionally not removed — worm grows
else:
tail = body.pop()
occupied.discard(tail)
# Step 4: self-collision against whatever remains occupied
if (nr, nc) in occupied:
dead = True
out.append(-1)
continue
# Step 5: commit the new head
body.appendleft((nr, nc))
occupied.add((nr, nc))
out.append(score)
return out