#2833

Furthest Point From Origin

Easy
StringCountingCountingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(2^n)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all combinations, we can directly calculate the furthest distance by counting the occurrences of 'L', 'R', and '_' in the string. We replace all '_' with the character that occurs the most to maximize the distance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the occurrences of 'L', 'R', and '_' in the string.
  2. 2Step 2: Determine the maximum distance by replacing all '_' with the character that occurs the most.
  3. 3Step 3: Calculate the final distance from the origin.
solution.py6 lines
1def furthestDistance(moves):
2    count_L = moves.count('L')
3    count_R = moves.count('R')
4    count_Underscore = moves.count('_')
5    max_distance = abs(count_L - (count_R + count_Underscore))
6    return max_distance

Complexity note: The time complexity is O(n) because we traverse the string once to count the characters. The space complexity is O(1) since we only use a fixed amount of extra space for counters.

  • 1Replacing '_' with the most frequent character maximizes distance.
  • 2Count-based approach is more efficient than generating combinations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.