educative.io

Educative

Line 16 of the solution

I don’t get why we have this condition in the code

(abs(target_diff) == abs(smallest_difference) and target_diff > smallest_difference):

removing the above line from the code doesn’t fail the tests.
what is it trying to compare?

3 Likes

Here is my understanding of that logic, If the absolute difference is same, meaning if the absolute difference between sum of the triplets and the target sum is same like diff = -1 (target- sum_of_triplets), min= +1 OR diff = -2 & min =+2, in that case, we want to take the smallest sum of the triplets. If diff is negative (-1), sum of triplets will be greater, since adding the sum to a negative value to get to the target will reduce the sum by diff amount . If diff is positive, (diff + sum_of_triplets = target) , sum of triplets has to be small by the amount of diff to get to the target

The code is there to satisfy this constraint “If there are more than one such triplet, return the sum of the triplet with the smallest sum.”
Look at example [0, 0, 0, 4], target=2
Without the constraint, either 0 or 4 would be the closest sum to the target (both triplets have abs(diff) == 2).
However, due to the constraint, we must return 0. And in order to do that, we will favor positive diff over negative diff. diff = target - triplets_sum. Positive diff -> smaller triplets_sum.

2 Likes