Currently, I am working on solving some leetcode problems and stumbled upon an interesting issue in my code for the problem at . However, I am having trouble understanding how it actually functions.
The problem with this code lies in the fact that the return statement in hasSimularArray does not exit from the function when called within the threeSum function. It seems like hasSimularArray keeps running as if it is a recursive function even though it's not. Thus, when it reaches the line "return true;" in hasSimularArray, it should stop executing the code within the function.
function threeSum(nums: number[]): number[][] {
const tripletsResult = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length - 2; i++) {
let j = i + 1;
let k = nums.length - 1;
while (j < k) {
const possibleResultEl = [nums[i], nums[j], nums[k]];
const threeNumsSum = nums[i] + nums[j] + nums[k];
if (threeNumsSum === 0) {
const hasVal = hasSimularArray(tripletsResult, possibleResultEl);
if (!hasVal) {
tripletsResult.push(possibleResultEl);
}
} else if (threeNumsSum < 0) {
j++;
} else {
k--;
}
}
}
return tripletsResult;
}
function hasSimularArray(mainArr: number[][], searchedArr: number[]) {
if (mainArr.length === 0) {
return false;
}
const searchArrayStr = JSON.stringify([...searchedArr].sort());
for (let el of mainArr) {
const elArrayStr = JSON.stringify([...el].sort());
if (elArrayStr === searchArrayStr) {
return true;
}
}
return false;
}
console.log(threeSum([0, 3, 0, 1, 1, -1, -5, -5, 3, -3, -3, 0]));
Previously, I encountered a similar issue but with a slightly different code structure and the same return logic in a nested function. Surprisingly, the return statement not only exited from the nested function but also from the parent one.
I attempted to debug the code to understand what was happening behind the scenes, but unfortunately, it did not provide any clear insights.
In another scenario, when I tested hasSimularArray independently without the parent function using the same values, it worked correctly.
Could anyone shed some light on what is going wrong here?