Grid Walker: Did the Drone Return to Base?
StringsAuto-graded · 24 test casesLast 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:
| Command | Effect |
|---|---|
U | one unit up (north) |
D | one unit down (south) |
L | one unit left (west) |
R | one 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^4flight_planmay 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the drone's location as a pair of integer displacements (x, y), both starting at zero. Scan the flight plan once. For each command, nudge the relevant counter up or down by one. Anything that isn't a recognized command leaves both counters unchanged. After the scan, the drone is back at its starting point if and only if both counters are exactly zero.
Why this is correct
Every command is a unit vector on a 2D integer grid:
| Command | Δx | Δy |
|---|---|---|
| U | 0 | +1 |
| D | 0 | −1 |
| R | +1 | 0 |
| L | −1 | 0 |
The final position is the vector sum of all those unit vectors. Vector addition is commutative and associative, so the final position depends only on how many times each direction appears, not on their order. The net displacement is:
x = count('R') − count('L')y = count('U') − count('D')
The drone is home when both components are zero. The two axes are independent — a balanced vertical axis does not compensate for an unbalanced horizontal one (e.g., "UL" gives x = -1, y = +1, which is not the origin even though x + y = 0).
Unrecognized characters contribute the zero vector, so ignoring them is mathematically exact, not a special case.
Edge cases
- Empty string: both counters stay at zero, returns
True. - Single command: one axis gets displaced by 1, returns
False. - Unbalanced on one axis only (e.g.,
"UDL"):y = 0butx = -1, returnsFalse. - Non-letter characters (e.g.,
"U1D"): the'1'is skipped;yends at zero, returnsTrue. - Lowercase letters (e.g.,
"ud"): not equal to'U'or'D', so ignored; returnsTrue.
Complexity
- Time: O(n) — each character in the flight plan is visited exactly once with O(1) work per character.
- Space: O(1) — only two integer counters are maintained regardless of input length.
This is optimal: any correct solution must inspect every character, since a single unread command could change the answer.
An alternative that is asymptotically equivalent and often faster in CPython due to C-level string scanning:
return (flight_plan.count('U') == flight_plan.count('D') and
flight_plan.count('L') == flight_plan.count('R'))
This makes four passes instead of one, but the constant factor is smaller in practice. Both approaches produce identical results, including correct handling of unrecognized characters.
Full solution
def drone_returned_to_base(flight_plan: str) -> bool:
"""
Determine whether a drone executing a sequence of movement commands
ends at the same position it started from.
Parameters
----------
flight_plan : str
A string of commands. 'U', 'D', 'L', 'R' each move the drone
one unit in the corresponding cardinal direction. All other
characters are ignored.
Returns
-------
bool
True if the drone's final position is its starting position,
False otherwise.
"""
x = 0 # horizontal displacement: R -> +1, L -> -1
y = 0 # vertical displacement: U -> +1, D -> -1
for cmd in flight_plan:
if cmd == 'U':
y += 1
elif cmd == 'D':
y -= 1
elif cmd == 'R':
x += 1
elif cmd == 'L':
x -= 1
# any other character: no effect
return x == 0 and y == 0