educative.io

Educative

Given Solutions Make Bad Assumption

All of the recommended solutions for this problem have roughly the same faulty line:
return targetSum - smallestDifference;

This assumes that the closest sum is LESS than the target. But what if the closest sum was GREATER than the target? Then this line would be returning the wrong sum. I know the prompt asks us to return the smallest closest sum, but I think that’s only if there’s a tie with a larger one. Am I crazy or did anyone else notice this?


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Triplet Sum Close to Target (medium) - Grokking the Coding Interview: Patterns for Coding Questions

Crap, I see it now. smallestDifference is NOT the absolute value distance from the target. So it will either be positive or negative when it is applied to the target in the return statement in question.


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Triplet Sum Close to Target (medium) - Grokking the Coding Interview: Patterns for Coding Questions