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=2, R=2, _=3. Net from fixed moves: 2-2=0. Since net is 0, we can add all flexible moves in either direction to get maximum distance: 0+3=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 INPUT Origin (0) L R moves = "L_RL__R" L _ R L _ _ R L = Left only R = Right only _ = Choice (L or R) Input Values: n = 7 (string length) moves = "L_RL__R" ALGORITHM STEPS 1 Count Characters L=2, R=2, _=3 2 Calculate Net Move net = |L - R| = |2 - 2| = 0 3 Maximize with '_' All '_' go same direction 4 Compute Result result = net + count('_') Calculation: L count = 2 R count = 2 _ count = 3 |2-2| + 3 = 0 + 3 = 3 FINAL RESULT -3 -2 -1 0 1 2 Furthest Distance = 3 Optimal Path: L: go left (pos: -1) _: go left (pos: -2) R: go right (pos: -1) L,_,_,R: net -2 more = -3 OUTPUT 3 Key Insight: The greedy approach maximizes distance by moving all wildcards ('_') in the same direction. Formula: result = |count('L') - count('R')| + count('_') Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Furthest Point From Origin | Greedy - Count and Maximize
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