Implement the detectCircularRouteSimple method that checks whether the given movement sequence returns to the starting point.

The input contains a string moves. Each character represents one movement from the current position: U for up, D for down, L for left, and R for right.

Your task is to check whether following all moves brings the route back to the starting point.

For example, UDLR returns to the starting position because up is cancelled by down, and left is cancelled by right.

Example 1

Input
moves (string) = UDLR
Returns (boolean) true

Example 2

Input
moves (string) = UD
Returns (boolean) true

Example 3

Input
moves (string) = UUD
Returns (boolean) false

Track the current position using two coordinates.

Start from (0, 0). Increase or decrease the vertical coordinate for U and D, and increase or decrease the horizontal coordinate for R and L.

After all moves are processed, the route is circular only if both coordinates are again 0.

Pseudocode:

function detectCircularRouteSimple(moves):
    x = 0
    y = 0
    for each move in moves:
        if move == U:
            y++
        else if move == D:
            y--
        else if move == R:
            x++
        else if move == L:
            x--
    return x == 0 and y == 0
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.