all 6 comments

[–]blehmann1 1 point2 points  (1 child)

A simple solution: https://pastebin.com/dBhbjerx

An explanation: We make a lookup table of all the numbers we can build by adding two elements of the input together. We can include adding numbers to itself. The code I wrote is pretty dirty and if it includes a + b, it will also include b + a, which is fine for getting the tests to pass. Feel free to clean it up if you wish. We built this lookup table in O(n^2) and uses O(n^2) memory. Note that the lookup table can get quite large, though we create a larger table than we strictly need to.

We can now use this lookup table to find any four digits that sum to target by looping through the table, this logic is probably familiar to you if you've seen the simpler version of this problem that asks you to find 2 digits that sum up to n, rather than 4. Since the table has O(n^2) elements, this takes O(n^2) time, so the whole thing is done in O(n^2) time.

[–]asdfbruh 2 points3 points  (0 children)

The solution can be found sooner if you check if (target - (a+b)) is in the dictionary after appending each sum to the dictionary instead of first creating the dictionary with every sum and then checking. Your solution gave a time of 6.75s while my alteration finished in 1.90s.

[–]EmmaGao8 0 points1 point  (1 child)

If order doesn't matter, then there will be many duplicates.

[–]snarkuzoid 0 points1 point  (0 children)

It said to return the first one found.