Furthest Point From Origin (LeetCode 2833): Solution and Explanation

Easy
String
Counting

Given moves of 'L', 'R' and free '_' steps on a number line, find the furthest distance from 0 you can end at.

Intuition

Where you end up is just the sum of your steps, so the order of the moves does not matter. Only three counts matter: forced lefts, forced rights and free blanks.

The forced moves alone leave you at R - L. To get as far from 0 as possible, every blank should push in the same direction you are already leaning. When the forced moves cancel, either direction works.

Approach: Count the three kinds of move

  1. Count left, right and blank in one pass.
  2. The forced moves leave you at distance |left - right| from 0.
  3. Each blank adds one more step away from 0, so return |left - right| + blank.

Step-by-step example

moves = "L_RL__R"
  1. Forced moves: two L and two R, so they leave the token at 0.
  2. There are three blanks saved as wildcards.
  3. The forced moves cancel, so send all three blanks the same way, for example left.
  4. The token ends at -3, so the answer is |2 - 2| + 3 = 3.

Code: Python, Java, C++

1class Solution:
2    def furthestDistanceFromOrigin(self, moves: str) -> int:
3        left = right = blank = 0
4        for m in moves:
5            if m == 'L':
6                left += 1
7            elif m == 'R':
8                right += 1
9            else:
10                blank += 1
11        return abs(left - right) + blank
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the moves to count them.

Space

O(1)

Three counters.

Other approaches

Try both directions (time O(n), space O(1))

Simulate twice: once with every blank as 'L' and once with every blank as 'R', and return the larger absolute end position. Same result, twice the work.

Common mistakes

  • Deciding each blank greedily by the current position during the scan. A later run of forced moves can change which side is farther, so decide after counting.
  • Returning left - right + blank without the absolute value, which fails when the forced moves lean left.
  • Splitting blanks between both directions; they should all go the same way.

Frequently asked questions

Why does the order of the moves not matter?

Each move adds -1 or +1 to the position, and addition does not depend on order. Only the final sum counts.

What if L and R are equal?

Then the forced moves cancel at 0, and the answer is just the number of blanks, sent in either direction.

Is the answer ever larger than n?

No. Each move changes the position by exactly one, so after n moves you are at most n away.