i was doing leetcode problem #553 (just studying) and i was stuck with time limit exceptions. i gave my code to the chatgpt to tell me how can i 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;
}
and 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 testcase with nums = [5,0,0,0]
and k = 3
ive got wrong answer (false instead of true).
after a several attempts i decided to replace && back with nested if statement and that was working fine for some reason.
so my question is, whats the difference between “&&” condition checking and nested if statement? isnt it working by short circuit?
Tentes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
If it weren’t for the else
branch, your refactoring would have been correct, but the existence of the else
changes things.
In the original code, the condition sums.ContainsKey(remain)
is evaluated first. If it is false
, the else
branch is executed.
After changing the nested if
s to a composite condition with &&
, the meaning changes – sums.ContainsKey(remain)
is first evaluated. If it is false
, the else
block is executed – so far so good. However, if it is true
, the i - sums[remain] > 1
condition is evaluated, and if it is false
, the entire compound expression is also false
, so once again the else
branch gets executed.