Taro Logo

Furthest Point From Origin

#2 Most AskedEasy
3 views
Topics:
StringsGreedy Algorithms

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.

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".

Constraints:

  • 1 <= moves.length == n <= 50
  • moves consists only of characters 'L', 'R' and '_'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the string `s`, and are we guaranteed that it will only contain the characters 'L', 'R', and '_analogs'?
  2. Since the underscores ('_') can be independently chosen as either 'L' or 'R', does every underscore have to be resolved to the same direction, or can they be mixed?
  3. Are we calculating the maximum absolute distance from the origin (meaning a position of -5 has an absolute distance of 5), or do we care about the sign of the final position?
  4. Can the input string be empty, and if so, what should the expected return value be?
  5. Is there any restriction on memory usage, or can we assume the string fits entirely in memory?

Brute Force Solution

Approach

Imagine you are given a sequence of movement instructions where some directions are clear and others are blank, meaning they could be either left or right. The brute force approach tries every possible combination of replacing those blanks with actual directions and measures how far each combination ends up from the starting point.

Here's how the algorithm would work step-by-step:

  1. Look at the entire list of movement instructions you were given.
  2. Find all the positions where the direction is blank and not yet decided.
  3. Imagine every possible way those blanks could be filled, by testing every combination of turning left or turning right for each blank spot.
  4. For each specific combination you imagine, follow all the movement instructions from the starting point to see where you end up.
  5. Measure the physical distance between your final ending spot and your original starting spot for that specific combination.
  6. Repeat this measurement process for every single possible combination of choices.
  7. Compare all the distances you found and select the one that places you the furthest away from the start.

Code Implementation

def furthest_distance_from_origin(movement_instructions):
    # We need to find all blank slots so we can generate every possible combination of directions
    blank_positions = [index for index, direction in enumerate(movement_instructions) if direction == '_']
    
    maximum_distance = 0
    total_blanks = len(blank_positions)
    
    # Testing every binary combination of left and right for the blanks ensures we explore all paths
    for combination_index in range(1 << total_blanks):
        current_instructions = list(movement_instructions)
        for blank_index in range(total_blanks):
            if (combination_index & (1 << blank_index)):
                current_instructions[blank_positions[blank_index]] = 'L'
            else:
                current_instructions[blank_positions[blank_index]] = 'R'
        
        current_position = 0
        for movement in current_instructions:
            if movement == 'L':
                current_position -= 1
            else:
                current_position += 1
        
        maximum_distance = max(maximum_distance, abs(current_position))
        
    # Tracking the peak distance across all simulated paths guarantees we find the absolute maximum
    return maximum_distance

Big(O) Analysis

Time Complexity
O(2^k * n) – Let n be the total length of the movement string and k be the number of blank spaces. The brute force approach generates every possible combination of left and right choices for the k blanks, resulting in 2^k distinct movement paths to evaluate. For each of these 2^k combinations, we must iterate through the length n instruction string to simulate the movement and calculate the final distance. Multiplying the number of combinations by the cost of evaluating each path yields approximately 2^k * n total operations. In the worst case where all characters are blanks, k equals n, making the time complexity exponential at O(2^n * n).
Space Complexity
O(2^n) – The brute force approach requires generating and tracking every possible combination of movement choices for the blank instructions. Since each blank spot can be resolved in two ways, exploring all combinations simultaneously or keeping track of the recursion states creates a maximum depth and branching factor proportional to the number of blanks, which we define as N. This generates exponential storage demands for the intermediate recursive stack frames and path evaluations. Ultimately, the extra memory required grows exponentially with respect to the input size N, simplifying to O(2^n) auxiliary space.

Optimal Solution

Approach

To find the furthest possible distance from the starting point after following a sequence of directions, the optimal strategy simply counts how many moves pull you to the left, how many pull you to the right, and how many are completely wildcards. Since the wildcard moves can be turned into whichever direction helps you travel the furthest, you can just boost your total count in whichever direction you are already leaning.

Here's how the algorithm would work step-by-step:

  1. Count every instruction that tells you to move in the first direction.
  2. Count every instruction that tells you to move in the opposite direction.
  3. Count every instruction that can be used as a wildcard in any direction you choose.
  4. Compare the totals of your first two counts to see which side you are currently leaning toward.
  5. Take all of your wildcard moves and add them directly to the side you are already leaning toward to maximize your stretch.
  6. Finally, calculate the distance between your final position and the starting point by taking the difference between your two main directional totals.

Code Implementation

def furthest_distance_from_origin(movement_moves):    # Count specific directional and wildcard moves to understand our current trajectory.    left_move_count = movement_moves.count('L')    right_move_count = movement_moves.count('R')    wildcard_count = movement_moves.count('_')    # Assign all wildcards to whichever direction we are already naturally leaning.    if left_move_count >= right_move_count:        left_move_count += wildcard_count    else:        right_move_count += wildcard_count    # Calculate the net displacement from the origin by finding the absolute difference.    return abs(left_move_count - right_move_count)

Big(O) Analysis

Time Complexity
O(n) – The algorithm iterates through the input string of moves of size n exactly once to count the occurrences of the first direction, the opposite direction, and the wildcard moves. After completing this single pass, it performs a few constant-time arithmetic operations to calculate the final distance. These operations approximate a total of n steps without any nested loops or repeated passes. Consequently, the linear growth leads directly to a time complexity of O(n).
Space Complexity
O(1) – To determine the furthest distance from the origin, the algorithm only needs a few primitive integer variables to maintain the counts for left movements, right movements, and wildcards. These constant number of scalar variables do not scale with the input length, meaning no auxiliary data structures grow with N. As the input string size N increases, the extra memory required remains entirely fixed. Therefore, the auxiliary space complexity is constant, denoted as O(1).

Edge Cases

String consists entirely of underscores
How to Handle:
Counting the absolute difference between L and R is zero, so the number of underscores acts as the maximum possible distance.
String contains no underscores
How to Handle:
The result simply evaluates the net absolute displacement of the fixed L and R moves.
Single character input like L, R, or underscore
How to Handle:
The length of the string is one, and the logic correctly evaluates to a distance of one.
String with extremely large length up to the constraints limit
How to Handle:
A single linear scan processes the string in O(N) time and O(1) space, easily scaling for large inputs.
Skewed distribution favoring only left or right moves along with underscores
How to Handle:
Greedily turning all underscores into the dominant direction maximizes the absolute distance from the origin.
0/18 completed