KatInterview

Grid Walker: Did the Drone Return to Base?

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringssimulationmath-bits

Last updated

Tests whether a candidate can simulate 2D movement on a grid and determine if a sequence of directional steps nets zero displacement.

Grid Walker: Did the Drone Return to Base?

A delivery drone starts at the center of an infinite 2D grid. It receives a flight plan as a string of single-character step commands. Each command moves the drone exactly one unit in a cardinal direction:

CommandEffect
Uone unit up (north)
Done unit down (south)
Lone unit left (west)
Rone unit right (east)

Any character that is not one of those four is a no-op: the drone stays put and moves on to the next command.

After executing every command in the flight plan, determine whether the drone has returned to its starting position.

Constraints

  • 0 <= len(flight_plan) <= 2 * 10^4
  • flight_plan may contain uppercase letters, lowercase letters, digits, spaces, or any printable ASCII character.
  • Only 'U', 'D', 'L', 'R' (uppercase) affect position; everything else is silently ignored.
  • An empty flight plan means the drone never moved, so it is considered to have returned.
  • Directions are absolute (compass directions), not relative to the drone's facing. 'L' always means west.
  • Only the final position matters — the path taken to get there is irrelevant.

Examples

Example 1

Input: drone_returned_to_base('UD')

Output: True

Example 2

Input: drone_returned_to_base('LL')

Output: False

Example 3

Input: drone_returned_to_base('URDL')

Output: True

Example 4

Input: drone_returned_to_base('')

Output: True

Hints

Hint 1

Track two independent counters: one for vertical displacement and one for horizontal. Each relevant command increments or decrements the appropriate counter by 1.

Hint 2

The order of the commands doesn't change the final position — only the total count of each direction does. The drone is home when up/down cancel out AND left/right cancel out. One condition alone is not enough.

Hint 3

Handle the boundaries naturally: an empty string starts and ends at zero displacement, and unrecognized characters simply don't update either counter.