2 pointer approach is awesome. But sir can we do it with DP...? I spent 3 hours in it....I even took 4D DP array but but didn't get correct solution. It was easily done with the help of (coin change) recursion.
Hi Won' t the logic you explained for 2-SUM change the indices post sorting? In order to use the left-right logic, we need to sort the array. Once sorted, the indices will get updated. So the i and j will reflect indices of sorted array not the original array. Can you please clarify?
Just one doubt: In python code - Line 17 - i had written 'if' instead of 'elif' and one tc was failing. What diff it will make? because all 3 conditions are different right i.e summ == 0, summ < 0 and summ > 0 so anyway only either of these should execute. (btw we've to use summ not sum as var name - bcoz sum is keyword in python)
Thanks, This is the strategy I used as well, though I couldn't do better than 43% on the time. Maybe because I did the 2sum part as a separate function and in JS. Anyhoo, here's a possible optimization (right after line 9 in the C++ code): if(nums[i] > 0) break; ehilr
It's just like mentioned in the solution. He made the two while loops to avoid duplicate solutions for the fixed first number. So , he incremented the (j) pointer if the next element in the sorted array is equal to the the current one (which will lead to the same current solution) and the same goes for the (k) pointer but with decrementing.
If(sum == 0) means nums[j] + nums[k] = 0. So here we have to make sure that one of these or both numbers do not repeat, as we will get duplicate answer in that, but........other if conditions do not require these while conditions as it's working the same without them.