r/dailyprogrammer • u/jnazario 2 0 • Jul 10 '17
[2017-07-10] Challenge #323 [Easy] 3SUM
Description
In computational complexity theory, the 3SUM problem asks if a given set of n real numbers contains three elements that sum to zero. A naive solution works in O(N2) time, and research efforts have been exploring the lower complexity bound for some time now.
Input Example
You will be given a list of integers, one set per line. Example:
9 -6 -5 9 8 3 -4 8 1 7 -4 9 -9 1 9 -9 9 4 -6 -8
Output Example
Your program should emit triplets of numbers that sum to 0. Example:
-9 1 8
-8 1 7
-5 -4 9
-5 1 4
-4 1 3
-4 -4 8
Challenge Input
4 5 -1 -2 -7 2 -5 -3 -7 -3 1
-1 -6 -3 -7 5 -8 2 -8 1
-5 -1 -4 2 9 -9 -6 -1 -7
Challenge Output
-7 2 5
-5 1 4
-3 -2 5
-3 -1 4
-3 1 2
-7 2 5
-6 1 5
-3 1 2
-5 -4 9
-1 -1 2
96
Upvotes
33
u/[deleted] Jul 10 '17 edited Jul 10 '17
Dead simple (and naïve) Python 3:
I <3 list comprehensions
9
u/pastmidnight14 Jul 10 '17
C++ implementation of the O(n2 ) algorithm shown on wikipedia here.
The algorithm reduces the complexity from C(3,2) to n2 by searching from each end of the array until meeting in the middle. Because the array is sorted, cases which contain only positive or only negative numbers are thrown out, for example.
6
u/olzd Jul 10 '17 edited Jul 10 '17
Dyalog APL:
8
u/[deleted] Jul 10 '17
I'd like to suggest bigger challenge outputs be provided with challenges like this so we can compare efficiencies and where brute-force solutions are unreasonable. Sure, I can come up with my own lengthier inputs but I feel a standard one coming from the official challenge would be best.
As for my solution: brute-force, easy to prototype, low effort Python 3:
Output:
4
u/cheers- Jul 10 '17 edited Jul 10 '17
Javascript
sum3 uses an hashtable and 2 nested loops(quadratic).
removeDup removes duplicates using Sets.
output:
4
u/morganga Jul 11 '17
Java code. This is not brute force O(n2), it's probably closer to O(n * ln(v)) where v is the size of each value.
I construct a binary digit tree of all numbers with the same sign and for each number n, with an opposite sign, I recursively search the binary tree for all possible add with carry operations that satisfy the long addition to n. I restrict the search to produce combinations instead of permutations.
4
u/enchantingtim Aug 03 '17
Quick Java implementation
1
u/rlmflores Jul 11 '17
Clojure
I've assumed that the description wasn't correct: On the input description, it is mentioned that
You will be given a list of integers, one set per line, so it shouldn't contain duplicated numbers (as sets contain only distinct numbers, right ?).3
u/AirieFenix Jul 10 '17 edited Jul 10 '17
Python 3:
There's no itertools, no checking for repetition so in long inputs there are repeated results. I know is bad but I can't figure it out how to make it better. Here it goes.
Output
Feedback for a total rookie would be hugesly (?) appreciated. Thanks!
EDIT: indentation.
3
u/Zambito1 Jul 11 '17 edited Jul 11 '17
Scala
3
u/Infinitylsx Jul 11 '17
Python 3 Basic and brute forced - but it's the first challenge I've done without looking at anyone else's code! If anyone has any tips for improvement please let me know!
Is it possible to do this using list comprehension?
1
u/jnazario 2 0 Jul 10 '17
FSharp Solution
1
u/Working-M4n Jul 10 '17
In the first challenge input, there are repeat numbers. Should they be counted as a separate triplets if the {-7, 2, 5} combination uses a different index for -7? The output would indicate that duplicates should be removed.
2
u/Zetickus Jul 10 '17 edited Jul 10 '17
Python 3
Currently learning Python, been doing java for the past year. This code is mostly to teach myself python stuff, like file reading. Hence why I use file reading to only read one line. I already played around with the input feature, so I figured I'd look at file reading, even though this is a bad way to use it. Nonetheless Python is a cool language.
edit: updated 'i[0] + i[1] + i[2] == 0' to sum(i). inspired by /u/_oats's brilliant solution
3sumvalues.txt:
2
u/Executable_ Jul 10 '17 edited Jul 10 '17
pyhon3
+/u/CompileBot python3
2
u/alge4 Jul 10 '17
Hey all, slightly slow, but i had to go out for a meal this evening. Would love any input on this, been practicing python 3.5 for about a week now. Having had several cracks at c++ but never really getting anywhere probably why i stick to for loops i dont really understand the next stages. More efficient code would be really interesting to learn about, I'll get there one or two bit are clearly are looked up but i try and take in the lessons and comment where i dont fully understand yet. Cheers peeps.
2
u/mattwentvegan Jul 26 '17 edited Jul 26 '17
Python 3: (I'm very new to programming; glad I did it by myself).
This is probably the most basic solution ever... (i.e. using the simplest of python knowledge) (but I don't mean the shortest code)
Certainly could be more efficient, but does the task.
2
u/shift_or_die Jul 26 '17
Perl brutal force
3
u/svgwrk Jul 10 '17
Here's my solution in Rust. Eliminating duplicates and invalid answers resulting from counting the same number twice proved to be a pain in the butt. That's where most of the complexity comes from here, I suppose.
3
u/puddingpopshamster Jul 10 '17
Ruby
Just started learning Ruby, so I just did the standard hash-map solution.
Output:
2
u/skeeto -9 8 Jul 10 '17
C. Since it's always a sum of 3, I hard-coded the nested loops and used min() and max() as a fast sort. To avoid printing repeats, the discovered triples are tracked in a 32,768 entry table by sorting the triple (canonicalization) and giving each number 5 bits in a 15-bit index (e.g. a poor man's set). This means the input digits are limited to -16 to 15.
Even with 1,024 input numbers, 1024 choose 3 is a mere ~178 million, so it's perfectly reasonable to brute-force search that space.
2
u/[deleted] Jul 10 '17 edited Jul 10 '17
Clojure first submission on this sub... i'm still pretty new to Clojure
Output:
1
u/joesacher Jul 10 '17 edited Jul 10 '17
Python (3.x for print)
Sorting the list seemed to be the easiest way of dealing with duplicates sets with different orders on output. Adding three values tuple to solution set to eliminate duplicates with same values in same order. This seemed like it would perform better than the itertools route.
1
u/MattieShoes Jul 10 '17
First time mucking about in Go. I didn't remove duplicates, as that means you could use the same number twice. Nor did I remove duplicate answers because they were obtained using different items. There aren't order-based duplicates though.
Output
1
u/gabyjunior 1 2 Jul 10 '17 edited Jul 11 '17
C
Generalized to NSUM problem and any target sum.
Input is
<number of value> <values> <target sum> <number of choices>
Values are sorted prior to the search to avoid duplicates and reduce search space by computing min/max sum to check if target is still reachable.
1
u/Ikor_Genorio Jul 10 '17
C very naive solution for the input example. This is my first time posting here, I will try to find a better solution.
Output: (first three numbers are the places of the corresponding number in the input sequence)
1
u/xCDx69 Jul 10 '17 edited Jul 10 '17
C#. First Submission Here. Feedback is Welcome.
edit: formating
1
u/ff8c00 Jul 10 '17
C# Gist
1
u/sultry_somnambulist Jul 10 '17 edited Jul 10 '17
Haskell
1
u/g4m3c0d3r Jul 10 '17
First submission to this sub. This isn't at all efficient, I was just trying to use as much as I could from the STL algorithms collection as practice.
C++:
Outputs:
1
u/JeremyBowyer Jul 10 '17
Python 3 w/ Itertools
1
u/ChazR Jul 10 '17
Haskell
Needed a bit of thinking to get the correct set of unique triples, but the rest of this is simple brute force.
1
u/Godspiral 3 3 Jul 11 '17
in J,
1
u/olu_ajoku Jul 11 '17
A quick and dirty brute force implementation.
Python 2.7
1
u/mr_smartypants537 Jul 11 '17
C++, only gets first triplet it finds for each row:
1
u/allenguo Jul 11 '17
Python 3 quadratic-time one-liner:
But it doesn't handle duplicates correctly—it fails the last test case.
Here's the runner code:
1
u/cbarrick Jul 11 '17
Prolog
v1.0
The obvious solution of guessing and checking is fairly elegant in Prolog. We do three nested loops, each selecting a number at a different index. In the inner loop, we check if our guess is a solution, and yield it when it is. The data is sorted and deduped first to avoid duplicate solutions.
v1.1
A simple improvement can be made: each scan need only consider the values to the right of the previously selected number.
v1.2
The previous versions are cubic time. The quadratic time version is essentially the same as v1.1, except the outermost scan adds to a hash-set, and the innermost scan is replaced by a lookup in that hash-set.
Because data is immutable in pure Prolog, hash-tables are actually a bad idea. Most Prolog dialects do not even ship with a hash-set. So I have left this as an exercise for the reader.
1
u/[deleted] Jul 11 '17
Python 3.6
Implemented and tested both using nested loops and using itertools for combinations to see the speed difference. Since the nested loops help eliminate some combinations from being checked twice, I went in to this assuming the nested loops would be faster than the itertools (someone more python-savvy can correct my code if I wrote the functions unfairly). For comparisons, I tested a list of 1000 random ints between -1000 and 1000.
Code
Results
In multiple tests, I found itertools to be significantly slower than nested looping(over 60% slower). But itertools gives the warm bubbly feeling of solving a coding challenge in one line of python, so I call it a tie.
1
u/[deleted] Jul 11 '17
Python 3 in one line (not including imports)
1
u/joesacher Jul 11 '17 edited Jul 11 '17
Rust
I learned a bunch in rust on this one. One cool trick is to use tuples in a vector. Once sorted with .sort(), you can call .dedup() to remove the duplicates. This was the cleanest way of dealing with this. Not sure if there is a set like object for rust, as I used in Python.
I still don't full understand my code for reading in the file, as I found it somewhere.
Output for test_data.txt
Output for test_data_large.txt
Eliminated output of solution, because it is large.
This compares to in the 140 ms range for my quadratic solution in Python 3.
1
u/mattcantright Jul 11 '17 edited Jul 13 '17
C++ as usual, a little crude yes as it just brute forces every option, sorts the answer into numerical order and then saves it so that it can easily be compared to other options that are the same and only output one, https://youtu.be/H-CngM56qbM , anyways here it is:
Input:
4 5 -1 -2 -7 2 -5 -3 -7 -3 1
-1 -6 -3 -7 5 -8 2 -8 1
-5 -1 -4 2 9 -9 -6 -1 -7
Output:
-7 2 5
-5 1 4
-3 -2 5
-3 -1 4
-3 1 2
-7 2 5
-6 1 5
-3 1 2
-5 -4 9
-1 -1 2
1
u/alkorith Jul 11 '17
I did it in both Java and C++. They work somewhat similarly in that it finds all the 3-sum triplets and removes duplicates it finds. Below is a gist link to the source code. If you see anything that I can improve on, let me know!
Gist
1
u/IPV4clone Jul 11 '17
Took the simple way out. I don't know much about how to create combinations rather than permutations so I'm gonna do a bit of reasearch, especially on the 3Sum Quadratic Equation Wiki.
C#
+/u/CompileBot C#
Input:
1
u/ASpueW Jul 11 '17 edited Jul 12 '17
Rust:
Output:
1
u/Scroph 0 0 Jul 11 '17 edited Jul 11 '17
Naive solution in C++. Hey this is the easy challenge amirite.
I'm using the same algorithm as the one used by /u/pastmidnight14. Instead of sorting the array of integers, I abused the STL to shove them into a multiset and then back into a vector. I also used a set to store the triplets otherwise there are duplicates.
+/u/CompileBot C++
Input:
1
u/macgillebride Jul 11 '17
Haskell O(n2) solution:
1
u/jibe77 Jul 11 '17 edited Jul 11 '17
Here is my solution in Java, (it's using brute force) :
And the unit tests :
1
u/Sud0nim Jul 12 '17 edited Jul 12 '17
Nim
I couldn't unsee the wiki solution, so I went with that with additional checking for duplicates:
Input:
Output:
1
u/MisterMikeM Jul 12 '17
Go with concurrency
1
u/rebuked Jul 12 '17
First time posting, and I didn't do the challenge.
Java:
Output:
1
u/Elronnd Jul 12 '17
Pure-python, no stdlib:
settakes care of duplicates for me so I don't have to.1
u/gopnik3 Jul 12 '17 edited Jul 12 '17
This one took a while
Still new to java so feedback is nice
I also have this strange feeling that there might be a more efficient way to do this
Also are we supposed to use encapsulation because it seems like a massive hassle especially for arrays and arraylists
}
1
u/SweetScientist Jul 12 '17
I'm a bit late to the party, but I like warming up with these for work and I have yet to see a Perl solution, so I'll add one!
Typical of Perl, using a CPAN module to do the heavy work for me.
Feedback, of course, appreciated :)
1
u/IKLeX Jul 12 '17
In python. Took me about half an hour. The idea is quite simple. The longest time was formatting and eliminating duplicates.
1
u/ngk31 Jul 12 '17
Javascript
1
u/I-Hate-Hats Jul 12 '17
Haven't programmed all summer long and trying to get back into it before school starts. Pretty rough //and I'm not sure if I submitted correctly
// // main.cpp // Teste // // Created by Luke Cecil on 7/12/17. // Copyright © 2017 Luke Cecil. All rights reserved. //
include <iostream>
using namespace std;
void loadArray(int, int*);
int main() { int size;
}
void loadArray(int size, int* array) { int hold; for(int i = 0; i < size; i++) { cout << "Enter number " << i + 1 << " : "; cin >> hold; array[i] = hold; } }
1
u/chunes 1 2 Jul 13 '17
Factor
1
u/pdp3308 Jul 13 '17
Python3 - A quick attempt at having a console based solution
1
u/[deleted] Jul 14 '17
Here's a Python one liner:
1
u/tinyfrox Jul 14 '17
Python3
1
u/hesperocallis Jul 14 '17 edited Jul 14 '17
Language: R.
Feedback welcome!
Output:
1
u/[deleted] Jul 15 '17 edited Jul 15 '17
So, I'm just thinking aloud here...
If you have three non-zero numbers A,B,C such that A+B+C=0 then I'm fairly sure they must be either three even numbers, or two odd numbers and one even number (proof left as exercise to the reader...). So if we start with a pair of numbers, and they are both even or both odd, we are looking for a third even number. If they are one even and one odd, we are looking for a third odd number.
I'm imagining an algorithm where we split the input into two lists, odds and evens, and start by picking two numbers (A, B) such that if they are part of a zero-sum-triplet, removing that triplet will make the lists as close as possible to the same length*. Then we look for a third value (C) from the relevant list, where (A+B) = -C. If we can't find one, we backtrack and try again with a different initial pair.
If the lists are sorted, we can use a binary-search to find our C value.
This algorithm assumes that numbers are randomly distributed, so there are approximately equal numbers of odds and evens, and it assumes no zeros (but a more complex version might be able to take zeros into account, possibly by keeping a separate list (count) of zeros.)
I'm not sure it'd be a huge performance improvement, but I think it ought to at least be better than O(n2).
* So if evens is longer by 3 or more, we pick two evens, and then look for a third. Otherwise, we pick either two odds, or an odd and an even.
1
u/x1729 Jul 16 '17
Perl 6
Output
1
u/Tolexrules Jul 16 '17
New Programmer here. I was able to get my program to work on this challenge, although I do not understand how to get the input to work as one line. Feedback is appreciated! Java `import java.util.Scanner; import java.util.ArrayList; //importing arraylist and scanner public class ThreeSum {
}`
1
u/paulggardner Jul 16 '17
Delphi.
I removed duplicates by sorting the numbers first, since the order didn't seem to make a difference.
1
u/zacyzacy Jul 17 '17
C# Implementation of the wikipedia page. https://gist.github.com/zacyzacy/82acf19d896fa1a7646181025cb1dc77
1
u/defregga Jul 18 '17 edited Jul 18 '17
Learning Java and my "... for Dummies" book hasn't covered sets or flexible containers (sorry, 'collections' -.-) yet. Frankly, I can't be bothered with the duplicates, when the rest of the code was working after barely 30 minutes and the next 90 minutes were spent flailing around trying not to look up any solutions.
1
u/wicked7000 Jul 20 '17
My solution coded in C++ , its most likely O(n3) or worse and not the cleanest of stuff but does work.Feedback would be greatly appreciated! https://gist.github.com/Wicked7000/843da0379680030aab20bdc9fa07fdc9
1
u/spicy_indian Jul 20 '17
Learning Rust:
1
u/CraftersLP Jul 20 '17
PHP simple brute-force solution
1
u/Tetsumi- 1 0 Jul 20 '17
Racket
+/u/CompileBot racket
Input:
1
u/primaryobjects Jul 25 '17
R
Gist | Demo
Brute-force solution.
1
u/Mobichobael Jul 29 '17
Here is my clumsy solution using R. I would love any feedback to optimize something like this!
1
u/aod65 Jul 31 '17 edited Jul 31 '17
Ruby:
Output:
1
u/_czyzewski Jul 31 '17 edited Jul 31 '17
python3 +/u/CompileBot python3
output
1
u/[deleted] Aug 01 '17
C++11
Not sure how fast this one is, but it nice and compact. I kinda lazily created a hash out of the result in order to prevent printing it to screen multiple times.
1
u/[deleted] Aug 02 '17 edited Aug 02 '17
+/u/CompileBot python 3
Input
1
u/Herpuzderpuz Aug 09 '17
Javascript solution, bruteforce. Removes duplicates, not very pretty but it works :)
1
u/[deleted] Aug 12 '17 edited Aug 15 '17
Ruby
Edit: Forgot to include output
Edit #2: Made output prettier
Output:
1
u/j4yne Aug 16 '17
Ruby 2.4, comments welcome:
1
u/gravity_fox Aug 17 '17 edited Aug 17 '17
Java "optimized brute-force" solution. It splits input numbers by factors - odd/even/positive/negative and uses 2 facts: that the sum of 2 odd/even numbers is even and the sum of 1 odd and 1 even numbers is odd; and the fact that the components of the sum must be either 1 negative and 2 positive or 2 negative and 1 positive numbers. And it also handles the duplications in input. I didn't do the precise calculation of the complexity in average case but it seems to me that it should be faster than the pure brute-force. Any comments and feedback are welcome. [source on gist] (https://gist.github.com/nucleusfox/521cf0f917690c2cf146dca6620c6883)
+/u/CompileBot Java --time --date
Input:
Output:
[UPDATED] It seems to me that the bot is dead for a while, so I added the output instead of him
1
u/InSs4444nE Sep 20 '17
JavaScript
quick crappy solution to refresh my js
it lets dupes through because i'm short on time
1
u/JakDrako Jul 10 '17
C#
Output:
0
u/Working-M4n Jul 10 '17
VB.NET
0
u/[deleted] Jul 10 '17
[deleted] — view deleted comment
0
u/[deleted] Jul 10 '17
[deleted] — view deleted comment
0
u/[deleted] Jul 10 '17
[deleted] — view deleted comment