Furthest Point From Origin — LeetCode 2833 Python Solution

EasyStringCounting
Problem
#2833
Pattern
Hash Map
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def furthestDistanceFromOrigin(self, moves: str) -> int:
        return abs(moves.count("L") - moves.count("R")) + moves.count("_")

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2833. Furthest Point From Origin is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2833. Furthest Point From Origin?
LeetCode 2833. Furthest Point From Origin is rated Easy on LeetCode.
What is the time complexity of LeetCode 2833. Furthest Point From Origin?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 2833. Furthest Point From Origin?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2833. Furthest Point From Origin cover?
LeetCode 2833. Furthest Point From Origin is tagged String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview