Burak Dede's Blog

Judge Circle Problem - Leetcode


This is my approach to the solution of judge circle problem from Leetcode. https://leetcode.com/problems/judge-route-circle/description/

Solution #1

In order to reach to the same position where it started left and right moves should cancel each out, same for the up and down movements. So in the end we are looking equal number of left and right with equal number of up and down.

public boolean judgeCircle(String moves) {
    int left = 0, right = 0, up = 0, down = 0;
    for(int i = 0; i < moves.length(); i++) {
        char c = moves.charAt(i);
        if(c == 'U') up++;
        else if(c == 'D') down++;
        else if(c == 'L') left++;
        else if(c == 'R') right++;

    return up == down && right == left;

This solution take O(n) time and only uses constant amount of space.