Furthest Point From Origin - Problem

You are given a string moves of length n consisting only of characters 'L', 'R', and '_'. The string represents your movement on a number line starting from the origin 0.

In the ith move, you can choose one of the following directions:

  • move to the left if moves[i] = 'L' or moves[i] = '_'
  • move to the right if moves[i] = 'R' or moves[i] = '_'

Return the distance from the origin of the furthest point you can get to after n moves.

Input & Output

Example 1 — Basic Case
$ Input: moves = "L_RL__R"
Output: 3
💡 Note: We have L=1, R=2, _=3. Net from fixed moves: 2-1=1. Add all _ to right: 1+3=4. But we can do better by going left: |1-3|=2. Wait, let me recalculate: if we assign all _ as R: LRRLRRR gives position -1+1+1-1+1+1+1=3. If all _ as L: LRRLLLR gives position -1+1+1-1-1-1+1=-1, distance=1. So maximum is 3.
Example 2 — All Flexible
$ Input: moves = "___"
Output: 3
💡 Note: All moves are flexible. Assign all to same direction (e.g., all R) gives distance 3.
Example 3 — No Flexible Moves
$ Input: moves = "LLR"
Output: 1
💡 Note: No flexible moves. Final position: -1-1+1=-1, distance is 1.

Constraints

  • 1 ≤ moves.length ≤ 2000
  • moves[i] is either 'L', 'R', or '_'

Visualization

Tap to expand
Furthest Point From Origin: "L_R_"Number LineOrigin (0)L_R_Count: L=1, R=1, _=2Optimal: Assign both _ as R → LRRR+2Maximum Distance: 2
Understanding the Visualization
1
Input
String with L, R, and _ characters
2
Strategy
Count characters and assign _ optimally
3
Output
Maximum possible distance from origin
Key Takeaway
🎯 Key Insight: All flexible moves should go in the same direction to maximize distance from origin
Asked in
Google 15 Meta 12 Amazon 8
25.0K Views
Medium Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen