The three sacks
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- sorting
- loops
Problem
Genaro sells seed by the sack at the market and he does not open any of them: whatever the sack weighs, it weighs. An order comes in for an exact number of kilos that has to be filled with three of the sacks he has on the stand, and he wants to know which three.
Write a function that takes sacks, a list of positive whole numbers with the kilos of each sack (it may bring sacks of the same weight and it may be empty), and goal, a positive whole number: the kilos of the order. Return a list with the weights of the three sacks that add up to the goal, from lightest to heaviest. They are three different sacks from the stand, so none of them counts twice, even if two of them weigh the same. If no trio adds up to the goal, return an empty list.
With sacks of 2, 7, 4, 9, 5, 1 and 3 kilos and an order of 6 kilos, the trio is 1, 2 and 3.
If several trios add up to the goal, return the one that starts with the lightest sack; if they also tie there, the one that goes on with the lightest. With sacks of 1, 2, 3, 4, 5 and 6 and an order of 9 three trios work: 1 with 2 and 6, 1 with 3 and 5, and 2 with 3 and 4. The one returned is 1, 2 and 6.
There are stands with up to 20 sacks.
Examples
The example
[2, 7, 4, 9, 5, 1, 3], 6 → [1, 2, 3]
Several trios work
[1, 2, 3, 4, 5, 6], 9 → [1, 2, 6]
No trio reaches the goal
[1, 4, 5, 6, 7, 8, 5, 9], 6 → []
With sacks of the same weight
[4, 4, 8, 4], 16 → [4, 4, 8]
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def three_sacks(sacks, goal):
passJavaScript
function threeSacks(sacks, goal) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.