Java solution with explanation - O(n)

  • 0

    We have to check if the net displacement is 0. This is true only if the distance traversed up equals that of down
    and traversed left equals that of right.

    public class Solution {
        public boolean judgeCircle(String moves) {
            int ls = 0, rs = 0, ups = 0, downs = 0;
            for(int i = 0; i < moves.length(); i++) {
                switch(moves.charAt(i)) {
                    case 'U':
                    case 'D':
                    case 'L':
                    case 'R':
            return ls == rs && ups == downs;

  • 0

    Thanks for the solution. If the robot has the moves RRRR or LLLL then also its going to reach its starting point. But the code returns false. What do you say on this?

  • 0

    @nitishleet If the robot has moves RRRR OR LLLL then it wouldnt reach the start. Otherwise, if it has RRRR AND LLLL it will reach the start.

  • 0

    @nitishleet I know what you mean. For example, R means “Take one step to the right direction", not means "Turn right and take a step". The robot always faces to the front direction and will never change.
    My English is not good. Wish you can know what I say.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.