Semi-Fast C# solution foreach and LINQ

  • 0

    So this solution below put me above the 75 percentile among the fastest (126ms). Originally I submitted a one-liner using LINQ which resulted in poor performance (160ms +/-).

    The LINQ solution:

    return moves.Count(u => u == 'U') == moves.Count(d => d == 'D') &&
           moves.Count(r => r == 'R') == moves.Count(l => l == 'L');

    The faster solution:

    public bool JudgeCircle(string moves)
            int horizontal = 0;
            int vertical = 0;
            foreach (char c in moves) 
                if (c == 'U') vertical++;
                if (c == 'D') vertical--;
                if (c == 'L') horizontal++;
                if (c == 'R') horizontal--;
            return horizontal == 0 && vertical == 0;

    I don't know if it's just me but it seems like when I run the code locally or in the editor, it's much faster. When I submit it, it's usually off by 30-50 ms. I know it's not a big deal but I just thought it was odd.

Log in to reply

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