Simulate robot on grid with obstacles
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: Simulate robot on grid with obstacles evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(commands) <= 1e5
- commands contains only the characters 'U', 'D', 'L', 'R'
- 0 <= len(obstacles) <= 1e5
- Each obstacle is a pair [x, y] of integers; the origin (0, 0) is never an obstacle
- Coordinates fit comfortably in a 64-bit integer; the squared distance can exceed 2^31, so use a 64-bit return type in Java/C++ if commands push far in one direction
Examples
Input: ("RRUU", [])
Expected Output: 8
Explanation: No obstacles. Path: (1,0)->(2,0)->(2,1)->(2,2). Final (2,2) gives 2^2+2^2 = 8, the maximum.
Input: ("RRUU", [[2, 0]])
Expected Output: 5
Explanation: Cell (2,0) is blocked. First R reaches (1,0); second R targets (2,0) -> blocked, stay at (1,0). Then U->(1,1), U->(1,2). Max is at (1,2): 1+4 = 5.
Hints
- Store obstacles in a hash set keyed by the (x, y) pair so you can test 'is this cell blocked?' in O(1).
- Walk the commands one at a time, keeping the current (x, y). Compute the destination; if it is in the blocked set, skip the move entirely and keep the old position.
- Track the maximum of x*x + y*y after every successful move (not just at the end) — the farthest point can be an intermediate position the robot later moves away from.
- The origin contributes distance 0, so initialize the best answer to 0; that also handles the empty-command and never-moves cases.