Robot Return to Origin - Complete Solution Guide
Robot Return to Origin is LeetCode problem 657, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
There is a robot starting at the 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. You are given a string moves that represents the move sequence of the robot where moves[i] represents its i th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise . Note : The way that the robot is "f
Detailed Explanation
The problem asks us to determine if a robot, starting at coordinates (0, 0), returns to its origin after a sequence of moves. The robot can move 'U' (up), 'D' (down), 'L' (left), and 'R' (right). We are given a string `moves` representing the robot's move sequence, and we need to return `true` if the robot ends up at (0, 0) after all moves, and `false` otherwise.
Solution Approach
The solution involves iterating through the `moves` string and updating the robot's x and y coordinates based on each move. We initialize x and y to 0. For each character in the string, we check if it is 'U', 'D', 'L', or 'R', and update the corresponding coordinate accordingly. Finally, we check if both x and y are 0. If they are, we return `true`; otherwise, we return `false`.
Step-by-Step Algorithm
- Step 1: Initialize two integer variables, `x` and `y`, to 0. These represent the robot's coordinates.
- Step 2: Iterate through the input string `moves` character by character.
- Step 3: For each character `move` in `moves`:
- - If `move` is 'U', increment `y` by 1.
- - If `move` is 'D', decrement `y` by 1.
- - If `move` is 'L', decrement `x` by 1.
- - If `move` is 'R', increment `x` by 1.
- Step 4: After iterating through all moves, check if `x` and `y` are both 0.
- Step 5: Return `true` if `x == 0` and `y == 0`, and `false` otherwise.
Key Insights
- Insight 1: The problem can be solved by tracking the robot's x and y coordinates as it moves through the sequence.
- Insight 2: Each move simply increments or decrements either the x or y coordinate. 'U' increments y, 'D' decrements y, 'L' decrements x, and 'R' increments x.
- Insight 3: The robot returns to the origin if and only if the final x and y coordinates are both 0.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: String, Simulation.
Companies
Asked at: Yandex.