Javascript O(n) solution


  • 0
    O

    This solution maps the moves on the x and y axis via a switch statement, and returns a new position each move.

    At the end, we check if we our coordinates are { x: 0, y: 0 }

    /**
     * @param {string} moves
     * @return {boolean}
     */
    const judgeCircle = function(moves) {
        let currPos = { x: 0, y: 0 };
    
        moves.split("").forEach(move => {
            currPos = getNewPosition(currPos, move);
        });
        
        return currPos.y === 0 && currPos.x === 0 ? true : false;
    };
    
    const getNewPosition = (position, move) => {
      switch (move) {
            case "U":
              position.y++;
              break;
            case "D":
              position.y--;
              break;
            case "R":
              position.x++;
              break;
            case "L":
              position.x--;
              break;
      }
        
        return position;
    };
    
    

Log in to reply
 

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