Skip to content

The Grid That Wraps Around

A robot starts at row 0, column 0 of an r by c grid. It repeats a command string over and over, executing exactly steps commands in total, and the grid WRAPS: stepping off any edge brings it back on the opposite edge.

U row - 1 D row + 1 L column - 1 R column + 1

Print the final row and column.

r = 3, c = 3, steps = 4, commands "RRDD" -> 2 2 r = 2, c = 2, steps = 1, commands "U" -> 1 0 wrapped off the top

If steps exceeds the length of the command string the string repeats, so command i is character i mod length.

## The two places this goes wrong

Wrapping upwards and leftwards. Moving U from row 0 must land on row r - 1. Written as (row - 1) % r this is correct in Python, where -1 % 3 is 2, and WRONG in C, C++, Java and JavaScript, where -1 % 3 is -1 and the next array access reads out of bounds.

Two correct forms: add the modulus before reducing, (row - 1 + r) % r, or test explicitly, if (row < 0) row = r - 1. The reference solutions use the second so the behaviour is visible rather than implied, and the oracle checks the two against each other.

Repeating the commands. With steps larger than the string, command i is character i mod length. Reading past the end instead, or stopping at the end of the string, both produce a plausible wrong answer rather than a crash.

## Why a single grid of 1 is worth testing

With r = 1, every U and D wraps immediately back to row 0, so the row never changes. A solution that special-cases "already at the edge" rather than applying the wrap uniformly tends to get this one wrong.

## Why you cannot shortcut the repetition

It is tempting to count how many of each command the string holds, multiply by the number of full repetitions, and apply the total. That works here BECAUSE every move is unconditional: nothing blocks the robot and the moves commute. Add one obstacle and it collapses, which is worth knowing as the boundary of the trick rather than as a rule. The references simulate honestly, since steps is at most 10^6.

## Cost

O(steps), one pass with O(1) memory.

Constraints - `1 ≤ r, c ≤ 1000` - `0 ≤ steps ≤ 1000000` - `1 ≤ length of the command string ≤ 1000` - every character is one of `U`, `D`, `L`, `R` - the grid wraps on all four edges