You are given a string moves
of length n
representing the moves of an object in the coordinate plane. The object starts at the origin (0, 0)
, and each character in the string represents a move:
You need to determine the Manhattan distance of the object’s furthest point from the origin after performing all the moves.
The Manhattan distance between two points (x1, y1)
and (x2, y2)
is |x1 - x2| + |y1 - y2|
.
moves
always be non-empty?
moves
?
moves
is within a reasonable limit for computation in a coding interview setting.x
and y
to 0
representing the starting coordinates.(x, y)
accordingly:
|x| + |y|
.def furthest_point_from_origin(moves: str) -> int:
x, y = 0, 0
for move in moves:
if move == 'L':
x -= 1
elif move == 'R':
x += 1
elif move == 'U':
y += 1
elif move == 'D':
y -= 1
return abs(x) + abs(y)
# Example usage:
moves = "LURDURD"
print(furthest_point_from_origin(moves)) # Output calculation based on the moves
n
is the length of the string moves
. This is because we iterate through each character in the string once.x
and y
.Feel free to test this function with different inputs to verify its correctness!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?