2833. Furthest Point From Origin
- String
- Greedy
TIME
O(n)
SPACE
O(1)
Intuition
To maximize distance from origin, use all '_' moves in the same direction that extends the furthest.
Solution
- Count
L,R, and_characters - Fixed displacement =
|L_count - R_count| - Use all
_to extend in the dominant direction
return abs(L_count - R_count) + underscore_countWhy This Works
- L's and R's have fixed directions, giving net displacement
|L - R| - All underscores should move in whichever direction is already dominant (or either if tied)
- This maximizes the absolute distance from origin
Complexity
- Time: O(n)
- Space: O(1)
Edge Cases
- All underscores → distance = n
- No underscores → distance = |L - R|
- Equal L and R → distance = underscore_count
Code
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
"""
2833. Furthest Point From Origin
Time: O(n)
Space: O(1)
"""
left = moves.count('L')
right = moves.count('R')
underscore = moves.count('_')
return abs(left - right) + underscore/**
* 2833. Furthest Point From Origin
* Time: O(n)
* Space: O(1)
*/
class Solution {
public int furthestDistanceFromOrigin(String moves) {
int left = 0, right = 0, underscore = 0;
for (char c : moves.toCharArray()) {
if (c == 'L') left++;
else if (c == 'R') right++;
else underscore++;
}
return Math.abs(left - right) + underscore;
}
}