algoadvance

Leetcode 2833. Furthest Point From Origin

Problem Statement

You’re given a string moves consisting of characters 'L', 'R', and '_'. Each character represents a move along a straight line:

Your task is to determine the maximum possible distance from the origin after all the moves in the string moves.

Clarifying Questions

  1. Can the string be empty?
    • No, the problem guarantees the string moves contains at least one character.
  2. What are the constraints on the length of the string moves?
    • Typically in such problems, constraints could be up to 10^5 characters, but this will be coded in a generic way without assuming a specific limit.
  3. Does the order of moves matter?
    • Yes, the characters in the string moves are sequential moves to be followed accordingly.

Strategy

  1. Initial Definitions:
    • left_moves: Count of movements to the left 'L'.
    • right_moves: Count of movements to the right 'R'.
    • neutral_moves: Count of movements which can be either 'L' or 'R' denoted by '_'.
  2. Distance Calculation:
    • If all neutral moves are considered as moves to the left, the resultant distance from origin is left_moves + neutral_moves - right_moves.
    • If all neutral moves are considered as moves to the right, the resultant distance from origin is right_moves + neutral_moves - left_moves.
    • The maximum distance is the greater of these two scenarios.
  3. Implementation Steps:
    • Loop through the string to count left_moves, right_moves, and neutral_moves.
    • Calculate the potential maximum distance by considering all neutral moves as either left or right and take the maximum of these potential distances.

Code

#include <iostream>
#include <string>
#include <cmath>

int furthestPointFromOrigin(const std::string &moves) {
    int left_moves = 0, right_moves = 0, neutral_moves = 0;
    
    for (char move : moves) {
        if (move == 'L') left_moves++;
        else if (move == 'R') right_moves++;
        else if (move == '_') neutral_moves++;
    }
    
    int max_distance = std::max(left_moves + neutral_moves - right_moves, right_moves + neutral_moves - left_moves);
    return max_distance;
}

int main() {
    std::string moves = "L__R_RL";
    std::cout << "Furthest Point From Origin: " << furthestPointFromOrigin(moves) << std::endl;
    return 0;
}

Time Complexity

This approach effectively counts the different types of moves and computes the maximum possible distance from the origin by considering all possible choices for neutral moves.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI