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 i<sup>th</sup>
move, you can choose one of the following directions:
moves[i] = 'L'
or moves[i] = '_'
moves[i] = 'R'
or moves[i] = '_'
Return the distance from the origin of the furthest point you can get to after n
moves.
Example 1:
Input: moves = "L_RL__R"
Output: 3
Explanation: The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves "LLRLLLR".
Example 2:
Input: moves = "_R__LL_"
Output: 5
Explanation: The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves "LRLLLLL".
Example 3:
Input: moves = "_______"
Output: 7
Explanation: The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves "RRRRRRR".
What is the most efficient way to calculate this distance, and what is the time and space complexity of your solution?
Let's analyze the problem. We are given a string of moves, and we can move left or right. The goal is to find the furthest distance from the origin we can reach. When we encounter a '_'
, we have a choice to go left or right. We want to maximize the absolute value of our final position. A naive solution is to try all possible combinations of moves when we encounter a '_'
. This would involve recursion or backtracking.
We can explore all possible move sequences using recursion. At each underscore, we branch into two possibilities: moving left or moving right. We keep track of the current position and update the maximum distance from the origin found so far.
def furthest_distance_brute_force(moves):
def solve(index, current_position):
nonlocal max_distance
if index == len(moves):
max_distance = max(max_distance, abs(current_position))
return
if moves[index] == 'L':
solve(index + 1, current_position - 1)
elif moves[index] == 'R':
solve(index + 1, current_position + 1)
else:
solve(index + 1, current_position - 1)
solve(index + 1, current_position + 1)
max_distance = 0
solve(0, 0)
return max_distance
Big O analysis
A more efficient approach is to consider the leftmost and rightmost possible positions. We calculate the maximum possible rightward distance and the maximum possible leftward distance. The underscores are converted to moves in the direction that maximizes these distances.
R
moves and underscores. Let this be right_moves
.L
moves. Let this be left_moves
.right_moves
. This is achieved by treating every underscore as a right move.left_moves + number of underscores
. But this approach is wrong because each underscore can be either R or L, we want to find the furthest distance from the origin.def furthest_distance(moves):
right_moves = 0
left_moves = 0
for move in moves:
if move == 'R' or move == '_':
right_moves += 1
elif move == 'L':
left_moves += 1
return right_moves - left_moves
Big O analysis
Edge Cases: