Robot Return to Origin | String Problem | LeetCode 657

4 years ago Lalit Bhagtani 0

Problem Statement

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

The sequence of moves is represented by a string, and the character at i index 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.

Example 

Robot Return to Origin

Input :- M = "RLUD" 
Output :- true
Input :- M = "UDR"
Output :- false

Solution

This problem can be solved in following steps :-

  1. Create the character array from the input String M.
  2. Create two variables U and R with initial value Zero.
  3. Traverse the character array from start (index 0) to end (n-1, where n is the length of an array). and at each iteration execute 4 and 5 step.
  4. If character is ‘U’, then increase value of variable U by 1 and if character is ‘D’, then decrease the value of variable U by 1.
  5. If character is ‘R’, then increase value of variable R by 1 and if character is ‘L’, then decrease the value of variable R by 1.
  6. If value of both U and R variable is zero, then return true, otherwise return false.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		boolean result = main.judgeCircle("RLUD");
		System.out.println(result);
	}
	
	/* Solution */
	public boolean judgeCircle(String moves) {
        
        char[] array = moves.toCharArray();
        int U = 0;
        int R = 0;
        for(int i=0; i<array.length; i++){
            
            if(array[i] == 'U'){
                U++;
            }else if(array[i] == 'D'){
                U--;
            }else if(array[i] == 'R'){
                R++;
            }else if(array[i] == 'L'){
                R--;
            }
        }        
        if(U == 0 && R == 0){
            return true;
        }
        return false;        
    }
}

Result

true 

Similar Post

  1. Rotated Digits
  2. Ransom Note
  3. Single Row Keyboard

That’s all for Robot Return to Origin in Java, If you liked it, please share your thoughts in a comments section and share it with others too.