Keep the robot's position (x, y) and the direction it faces as a step (dx, dy), starting at the origin facing north (0, 1). A move adds the direction to the position. A quarter turn rotates the direction: left is (dx, dy) → (-dy, dx), right is (dx, dy) → (dy, -dx). That replaces a table of compass names and any if north … else if east … chain. At the end, "distance" needs a question back to the interviewer: the path length travelled, the grid distance from the start |x| + |y|, or the straight-line distance Math.hypot(x, y). With obstacles, move one step at a time and look up the next square in a Set of "x,y" strings before stepping.
LeetCode-style: calculate the distance a robot has moved given a sequence of instructions.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Facing north is the step (0, 1). Turning left swaps the two numbers and negates the new x: north (0, 1) becomes west (-1, 0), then south (0, -1), then east (1, 0). Turning right is the opposite rotation. Destructuring assignment does the swap without a temporary variable. The answer is the Manhattan distance from the start. The last check shows the cost of the simple loop: characters it does not know are skipped without a word.
// Reading of the question: the robot starts at (0, 0) facing north. 'G' moves one step forward,// 'L' and 'R' turn it a quarter turn on the spot. Return how far it ends from the start,// counted in grid steps (|x| + |y|, the Manhattan distance).function robotDistance(instructions) {let x = 0;let y = 0;let dx = 0; // the direction it faces, as a step: north is (0, 1)let dy = 1;for (const c of instructions) {if (c === 'G') {x += dx;y += dy;} else if (c === 'L') {[dx, dy] = [-dy, dx];} else if (c === 'R') {[dx, dy] = [dy, -dx];}}return Math.abs(x) + Math.abs(y);}
passes 7 checks run on every build, against the native method where there is one
- straight ahead
- a turn changes direction, not position
- a square brings it home
- left and right are opposite turns
- four turns is a full circle, three lefts is one right
- no instructions
- the weakness: unknown characters are skipped silently
A regular expression cuts the input into tokens of a letter with optional digits, plus any other single character so that it can be rejected by name. F10 moves ten steps in one multiplication. travelled adds up every step taken, which is what an odometer shows; manhattan and straight measure from the start to the end. F5 B5 makes the difference visible: 10 travelled, 0 from the start. Turn counts are reduced with % 4, since four quarter turns is no turn.
// Instructions with counts: F10 (forward 10), B2 (back 2), L and R (quarter turns, L2 turns// around). "Distance moved" has more than one meaning, so return them all: the path length// travelled, and the distance from the start in grid steps and in a straight line.function robot(instructions) {const tokens = instructions.match(/[A-Za-z]\d*|\S/g) ?? [];let x = 0;let y = 0;let dx = 0;let dy = 1;let travelled = 0;for (const token of tokens) {const m = /^([FBLR])(\d*)$/.exec(token.toUpperCase());if (!m) throw new SyntaxError(`unknown instruction "${token}"`);const n = m[2] === '' ? 1 : Number(m[2]);if (m[1] === 'F') {x += dx * n;y += dy * n;travelled += n;} else if (m[1] === 'B') {x -= dx * n;y -= dy * n;travelled += n;} else {for (let turn = 0; turn < n % 4; turn++) {[dx, dy] = m[1] === 'L' ? [-dy, dx] : [dy, -dx];}}}return { x, y, travelled, manhattan: Math.abs(x) + Math.abs(y), straight: Math.hypot(x, y) };}
passes 8 checks run on every build, against the native method where there is one
- forward with a count, then a turn
- a 3-4-5 triangle: three different distances
- back undoes forward, but the path was still walked
- turn counts
- no count means one, F0 moves nothing
- lower case and no spaces
- a square of side 12 comes home after 48 steps
- anything else throws SyntaxError, naming it
With obstacles a move can't be one multiplication: the robot advances one square at a time and stops in front of a blocked square, then carries on with the next command. Obstacles go into a Set keyed by the string "x,y", because two arrays with the same numbers are different objects and a Set of arrays would never find a match. The result is the largest squared distance reached at any moment, so it is updated after every step, not once at the end.
// The well-known harder version ("walking robot simulation"): commands are numbers. -2 turns// left, -1 turns right, 1 to 9 moves that many steps forward, one step at a time, stopping in// front of an obstacle. Return the largest squared straight-line distance from the start that// the robot reaches at any moment.function robotSim(commands, obstacles) {const blocked = new Set(obstacles.map(([ox, oy]) => `${ox},${oy}`));let x = 0;let y = 0;let dx = 0;let dy = 1;let farthest = 0;for (const command of commands) {if (command === -2) {[dx, dy] = [-dy, dx];} else if (command === -1) {[dx, dy] = [dy, -dx];} else {for (let step = 0; step < command; step++) {if (blocked.has(`${x + dx},${y + dy}`)) break;x += dx;y += dy;farthest = Math.max(farthest, x * x + y * y);}}}return farthest;}
passes 8 checks run on every build, against the native method where there is one
- no obstacles: forward 4, right, forward 3
- an obstacle stops it one square short
- the farthest point counts, not where it ends
- blocked from the first step
- an obstacle on the start square does not stop it leaving, only coming back
- negative coordinates
- turning on the spot, and no commands
- many obstacles and many commands
Grid movement in games and editors
Snake, Tetris pieces, a cursor in a spreadsheet and a character on a tile map are all a position plus a direction step. Rotating the step vector is the same 90° rotation used here.
Objects as Set keys
A Set compares objects by identity, so new Set([[1, 2]]).has([1, 2]) is false. Coordinates are stored as a string key, or as one number such as x * width + y on a bounded grid.
Straight-line distance
Math.hypot(x, y) returns the square root of the sum of squares and avoids the overflow that Math.sqrt(x * x + y * y) can hit with very large values.
Not asking which distance is meant: travelled, grid steps from the start, or straight line.
Mixing up the two rotations, so left and right are swapped.
Writing a four-way
ifon direction names for every move instead of rotating one vector.Using a
Setorincludeson coordinate arrays, which compares references and never matches.Jumping the whole distance at once when there are obstacles in the way.
Measuring only the final position when the question asks for the farthest point reached.
What is the complexity?
The first two stages are O(n) in the number of instructions and O(1) memory. With obstacles it is O(total steps + obstacles): each step is one Set lookup, and building the set is one pass over the obstacles.
If the instructions repeat forever, does the robot stay in a bounded area?
Run the instructions once. The robot stays bounded if it is back at the origin, or if it is facing any direction other than north: then after two or four repetitions the displacements cancel. Only "moved and still facing north" drifts away forever.
How would you support 45° turns or free angles?
Keep an angle instead of a step vector and move by (cos, sin) of it. Positions become floating-point numbers, so compare distances with a tolerance.
How would you make the obstacle key cheaper?
On a grid with known bounds, encode the pair as one number, for example (x + OFFSET) * SIZE + (y + OFFSET), which avoids building a string for every step.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring#swapping_variables
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#value_equality
- en.wikipedia.org/wiki/Taxicab_geometry
- en.wikipedia.org/wiki/Rotation_matrix#Common_2D_rotations