3Sum: All Unique Triplets
Northgate Clearing ends every day with a list of ledger adjustments, some positive and some negative. Before the books close, an auditor has to report each set of three adjustments that wipes each other out — three amounts adding up to nothing at all. Two findings built from the same three amounts are one finding, however those amounts were written down.
Task: Print every distinct trio of amounts that adds up to 0.
Input
A single line holding up to 500 integers separated by single spaces. Values may repeat and may be negative. An amount can be used only as often as it appears, so a line carrying one 0 cannot produce the trio 0 0 0.
Output
One trio per line: three integers separated by single spaces, written smallest first. Order the lines by their first number, and where two share a first number, by their second. A trio holding the same three amounts as an earlier line must not print again. If no trio adds up to 0, print nothing at all.
Example:
Input:
-1 0 1 2 -1 -4
Output:
-1 -1 2
-1 0 1
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in