I have a problem in my life and it's name is Leetcode.
While trying to think of topics to write about on DEV, I kept reading all these posts from ...
For further actions, you may consider blocking this person and/or reporting abuse
There's actually a much simpler algorithm, which is also quadratic, that looks much more like the solution to "2SUM". It requires a lot less 'cleverness', and is more obviously correct:
Find all the solutions with only one distinct element (i.e.,
[0, 0, 0]
). This can be done in linear time (count how many0
s are in the input)Find all solutions with only two distinct elements (i.e.,
[x, x, -2*x]
). This can be done in linear time, and is basically the same as "2SUM".Find all solutions with three distinct elements.
for (let a = 0; a < nums.length; a++) { for (let b = a + 1; b < nums.length; b++) {
-(a + b)
is in the array (like "2SUM"), and-(a + b)
is biggernums[b]
. If so, we found a solutionI'd be curious how you'd write that. Seems like it would Timeout, but what do I know?
The algorithm takes time proportional to the square of
nums.length
, just like your solution. Most programming problems on sites allow a fairly generous constant multiple of the fastest possible solution because they are usually just trying to get you on the right algorithmic solution and don't care so much about fine details.On this particular problem, it looks like most solutions take around 160ms, but this one takes about 200ms.
Yeah, definitely runs a bit slower, but you know, lots of ways to open a banana.
I just think "more obviously correct" is a little off base, but you know, whatever works for you.
I loved your thorough explanation!
I did find an issue in your final code which you posted:
When you iterate over the array, you use this conditional here:
if (i !== j && num !== nums[i - 1])
This will instantly fail. On the first iteration,
i=0
, thereforenums[i-1]
is immediately OOB.You can use a proxy in JS to allow negative indices fwiw.
Also,
i
will never equalj
.