Search code examples
c#.netif-statement

unexpected behavior with nested if statements in c#


I was doing leetcode problem #553 (just studying) and I was stuck with time limit exceptions. I gave my code to ChatGPT to tell me how I can optimise it and it gave me this code:

public bool CheckSubArraySumV2(int[] nums, int k)
{
    if(nums.Length < 2) return false;

    Dictionary<int, int> sums = new()
    {
        [0] = -1
    };

    int sum = 0;

    for(int i = 0; i < nums.Length; i++)
    {
        sum += nums[i];
        int remain = sum % k;
        if(sums.ContainsKey(remain))
        {
            if(i - sums[remain] > 1)
            {
                return true;
            }
        }
        else{
            sums[remain] = i;
        }
    }

    return false;
}

After I understood this method I copied it all except this nested if statement:

if (sums.ContainsKey(remain))
{
    if (i - sums[remain] > 1)
    {
        return true;
    }
}

I changed it to this:

if(sums.ContainsKey(remain) && i - sums[remain] > 1)
{
    return true;
}

but for some reason in test case with nums = [5,0,0,0] and k = 3 I got the wrong answer (false instead of true).
After several attempts I decided to replace && back with a nested if statement and that was working fine for some reason.

My question is, what's the difference between "&&" condition checking and nested if statement? Isn't it working by short circuit?


Solution

  • If you carefully look at the code considering these cases with a wider view

    Case 1

    if(sums.ContainsKey(remain)) {
        if(i - sums[remain] > 1) {
            return true;
        }
    } else {
        sums[remain] = i;
    }
    

    Case 2

    if(sums.ContainsKey(remain) && i - sums[remain] > 1) {
        return true;
    } else {
        sums[remain] = i;
    }
    

    You will understand that in the first case the code will go to else block only if the below condition is true

    sums.ContainsKey(remain)

    In second case the code will still go in else condition if the above condition fails but due to the && condition if

    i - sums[remain] > 1

    results false then also the code will go to else condition, but if this condition fails in Case 1 nothing will happen