Taro Logo

Furthest Point From Origin

Easy
Asked by:
Profile picture
6 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 data type of the points? Are they represented as integers or floating-point numbers, and what is the range of their possible values?
  2. Can the coordinates of the points be negative, zero, or only positive?
  3. If multiple points are the furthest from the origin, which one should I return?
  4. If the input array is empty or null, what should I return? Is there a specific point that should be returned in that case, or an error value?
  5. How is the 'furthest' point defined? Should I use Euclidean distance (straight-line distance) or another distance metric like Manhattan distance?

Brute Force Solution

Approach

The brute force approach is like trying every single possible path to find the furthest point. We will calculate the distance of every point from the origin. Then we will pick the point with the largest distance.

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

  1. For each point, calculate its distance from the origin (the point (0, 0)).
  2. Keep track of the largest distance you've seen so far, and the point associated with that distance.
  3. After checking every point, the point with the largest distance is the furthest point from the origin.

Code Implementation

def find_furthest_point_brute_force(points):
    furthest_distance = 0
    furthest_point = None

    for point in points:
        # Calculate the distance from the origin.
        distance_from_origin = (point[0]**2 + point[1]**2)**0.5

        # Update furthest_distance if current point is further.
        if distance_from_origin > furthest_distance:

            furthest_distance = distance_from_origin

            furthest_point = point

    return furthest_point

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through each of the n points in the input array once. For each point, it calculates the distance from the origin, which takes constant time O(1). It also keeps track of the maximum distance seen so far, which also takes O(1) time. Therefore, the overall time complexity is dominated by the single iteration through the n points, resulting in O(n) time complexity.
Space Complexity
O(1)The algorithm keeps track of only the largest distance seen so far and the corresponding point. This requires storing a constant number of variables, regardless of the number of points (N). No additional data structures like arrays or hash maps are created to store intermediate results. Therefore, the auxiliary space used is constant.

Optimal Solution

Approach

The goal is to find the point furthest from the origin. The clever idea is to only focus on the extreme values of the inputs since distance increases as the absolute values increase. We need to identify the largest possible x and y values, considering both positive and negative.

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

  1. Find the largest value among all the 'x' values, and also find the smallest (most negative) 'x' value.
  2. Find the largest value among all the 'y' values, and also find the smallest (most negative) 'y' value.
  3. Now, calculate the distance of the point using the largest 'x' and largest 'y' values from the origin.
  4. Also, calculate the distance of the point using the largest 'x' and smallest 'y' values from the origin.
  5. Also, calculate the distance of the point using the smallest 'x' and largest 'y' values from the origin.
  6. Also, calculate the distance of the point using the smallest 'x' and smallest 'y' values from the origin.
  7. Compare the four distances calculated and return the largest distance. This represents the furthest point from the origin.

Code Implementation

def furthest_point_from_origin(points):
    max_x_value = float('-inf')
    min_x_value = float('inf')
    max_y_value = float('-inf')
    min_y_value = float('inf')

    for point in points:
        x_coordinate, y_coordinate = point
        max_x_value = max(max_x_value, x_coordinate)
        min_x_value = min(min_x_value, x_coordinate)
        max_y_value = max(max_y_value, y_coordinate)
        min_y_value = min(min_y_value, y_coordinate)

    # Calculate the distances from the origin for all combinations
    distance_1 = (max_x_value**2 + max_y_value**2)**0.5
    distance_2 = (max_x_value**2 + min_y_value**2)**0.5
    distance_3 = (min_x_value**2 + max_y_value**2)**0.5
    distance_4 = (min_x_value**2 + min_y_value**2)**0.5

    # Compare distances and get the largest distance
    max_distance = max(distance_1, distance_2, distance_3, distance_4)

    return max_distance

def main():
    points_list = [[1, 2], [-1, -2], [3, 4], [-5, -6]]
    
    #Find the coordinate farthest from the origin
    max_distance_point = furthest_point_from_origin(points_list)

    print(f'{max_distance_point=}')

if __name__ == "__main__":
    main()

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the x and y values once to find the maximum and minimum x values, and again to find the maximum and minimum y values. Finding the maximum and minimum values each takes O(n) time where n is the number of points (or the number of x and y coordinates since they are proportional). Calculating the four distances takes constant time. Therefore the overall time complexity is O(n) + O(n) + O(1), which simplifies to O(n).
Space Complexity
O(1)The algorithm only uses a fixed number of variables: to store the largest x, smallest x, largest y, smallest y, and the four calculated distances. The amount of extra memory required does not depend on the number of input points N. Therefore, the space complexity is constant.

Edge Cases

Empty input list
How to Handle:
Return 0, indicating the origin (0,0) is the furthest point since no other points exist.
List contains only the origin (0,0)
How to Handle:
Return 0, as the furthest point is still the origin itself.
List contains very large positive and negative numbers
How to Handle:
Use appropriate data types (e.g., long or double) to prevent integer overflow when calculating distance from origin.
List contains duplicate points
How to Handle:
The algorithm should correctly calculate the distance for each unique point, treating duplicates as separate occurrences for distance calculation.
All points are equidistant from the origin
How to Handle:
Return any one of the points since they are all equally furthest.
List contains only one point
How to Handle:
Return the distance of that single point from origin.
Input list is null
How to Handle:
Throw an IllegalArgumentException or return 0, depending on the specified error handling policy.
List contains floating-point numbers with limited precision
How to Handle:
Be aware that floating-point comparisons can be imprecise, and consider using a small tolerance when comparing distances to avoid errors.