Problem Statement in English
You’re given a string moves that represents the moves of a robot on a 2D plane. The robot starts at the origin (0, 0) and can move in four directions:
‘L’ (left): moves the robot one unit to the left (x decreases by 1).
‘R’ (right): moves the robot one unit to the right (x increases by 1).
‘_’ (wildcard): moves the robot one unit in any one direction that you choose.
Return the maximum distance from the origin that the robot can be after performing all the moves in the string moves. The distance from the origin is calculated using the formula: distance = |x| + |y|, where (x, y) is the final position of the robot.
Approach
You can count the number of ‘L’, ‘R’, and _ moves. The robot can use the _ moves to maximize the distance from the origin by moving in the direction that has more moves. If there are more L moves than R moves, you can use the _ moves to move farther left, and vice versa.
Remeber to subtract the fewer moves from the greater count to get the distance from the origin.
Solution in Python
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
c = Counter(moves)
b = c["_"]
l = c["L"]
r = c["R"]
if l > r:
return (l + b) - r
return (r + b) - l
Complexity
Time: $O(n)$
Since we need to count the moves in the string.Space: $O(1)$
Since we only need a constant amount of space to store the counts.
Mistakes I Made
I was about to brute force this 🤦♂️
And we are done.