#BlackLivesMatter Support An Initiative
Leetcode – Robot Return To Origin Problem: Solution in Javascript and PHP

Robot Return To Origin Problem: Solution in Javascript and PHP

 

Question

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is “facing” is irrelevant. “R” will always make the robot move to the right once, “L” will always make it move left, etc. Also, assume that the magnitude of the robot’s movement is the same for each move.

https://leetcode.com/problems/robot-return-to-origin

Example 1:

Example 2:

Solution

When I saw this question, I immediately thought of the Cartesian coordinate system, the x and y plane, illustrated below.

image source: http://www.montereyinstitute.org

The origin (0, 0) on the plane represents x = 0 and y = 0. From the origin (or anywhere on) the x-axis, when we move to the right, the value of x increases, and when we move to the left, the value of x decreases.

It’s the same on the y-axis. When we move up, the value of y increases, and when we move down, the value of y decreases.

Using this concept of moving vertically and horizontally on the plane, I came up with a solution to the above problem.

First off, let’s define an array/object map for Up, Down, Left and Right. We could actually just code it directly when needed, but I think the map makes it cleaner and easier to read.

Next, we define x and y and set the values to 0, since they start at the origin.

Now, we can loop through each character in the moves string, and check what action we need to perform. If the character is a left or right action, we will add or subtract on the x-plane and if the character is an up or down, we will do same on the y-axis.

Since we have defined a map, we will always use the addition operation on the plane, +(-) = - and +(+) = +.

Finally, we check if the value of x and y are 0. We return true if that’s the case, and false otherwise.

Full Code in Javascript

Full Code in PHP

I hope this was a helpful read. Feel free to share recommendations for different approaches in the comments.

Video explanation

Cheers!

Leave a Comment

Your email address will not be published. Required fields are marked *