Teaching Kids Programming: Videos on Data Structures and 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 ‘_’.
Furthest Point From Origin (Hash Map)
We can perform three linear searches to count the number of L, R and underscores, and then the answer is abs(L-R)+X where X is the number of underscores.
The L and R sequences do no matter, so we can compute the position after performing all L and R instructions, and then we will further increase the distance to origin by adding up the X.
1 2 3 4 5 6 | class Solution: def furthestDistanceFromOrigin(self, s: str) -> int: L = s.count("L") R = s.count("R") X = s.count("_") return abs(L - R) + X |
class Solution: def furthestDistanceFromOrigin(self, s: str) -> int: L = s.count("L") R = s.count("R") X = s.count("_") return abs(L - R) + X
The time complexity is O(N), and the space complexity is O(1) constant. However the string.count needs to be performed three times.
We can use a Counter (aka Hash Map) to count the characters once, and then retrieve the value via O(1) time. The time and space complexity is O(N). However, performance-wise, the following approach will be 3 times faster (as only one pass is required).
1 2 3 4 5 6 7 | class Solution: def furthestDistanceFromOrigin(self, s: str) -> int: C = Counter(s) L = C['L'] R = C['R'] X = C['_'] return abs(L - R) + X |
class Solution: def furthestDistanceFromOrigin(self, s: str) -> int: C = Counter(s) L = C['L'] R = C['R'] X = C['_'] return abs(L - R) + X
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Two Algorithms to Find All Numbers Disappeared in an Array (Hash Set)
Next Post: What is the Concept of "Cloud Native"?