Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The fixed left and right moves produce displacement rightCount - leftCount. Every unspecified move can extend the distance in whichever direction already has the advantage, increasing the absolute displacement by one. If the fixed moves balance, either direction works.
Approach
Count L, R, and unspecified moves. Return the number of unspecified moves plus abs(leftCount - rightCount). Assigning all unspecified moves consistently in the favorable direction achieves this bound; no single move can increase distance by more than one, so a mixed assignment cannot do better. Only the final position matters, not the order of the steps.
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
l, r = 0, 0
res = 0
for m in moves:
if m == 'L':
l += 1
elif m == 'R':
r += 1
else:
res += 1
return res + abs(l - r)Complexity analysis
Let n = moves.length. Time: O(n). Auxiliary space: O(1).
