Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
On line 19 of Python solution, why is it overriding smallest_difference if the n...

hj3yoo

Feb 21, 2022

On line 19 of Python solution, why is it overriding smallest_difference if the new target_diff is BIGGER rather than smaller than the existing value?

If the target_sum = 2, smallest_difference = 1, target_diff = 3, shouldn't smallest_difference continue to be 1? The problem statement mentions to return the smallest sum for tie-breaker.

4

0

Comments
Comments
D
Daniel 3 years ago

The check of target_diff > smallest_difference only occurs when abs(target_diff) == abs(smallest_difference), aka only when there is a tie. When there is a tie, we want to pick the smaller sum. The smaller sum is the triplet with the bigger target_diff (since the bigger...

On this page

Problem Statement

Try it yourself