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

0% completed

Vote For New Content
Landon Brown
I feel just keeping up with the sum rather than calculating the difference right away makes things easier to read and comprehend when updating smallest_diff

Landon Brown

Jan 14, 2024

import math class Solution: def searchTriplet(self, arr, target_sum): # TODO: Write your code here arr.sort() smallest_diff = math.inf closest_sum = math.inf l = 0 while l < len(arr): m = l + 1 r = len(arr)-1 while m < r: val_sum = arr[l] + arr[m] + arr[r] if val_sum == target_sum: return val_sum if abs(target_sum-val_sum) < abs(smallest_diff) or val_sum < closest_sum: smallest_diff = target_sum-val_sum closest_sum = val_sum if val_sum > target_sum: r -= 1 else: m += 1 l += 1 return target_sum-smallest_diff

4

0

Comments
Comments
 Sri
Sri2 years ago

How are you using the closest_sum that you are updating?

On this page

Problem Statement

Try it yourself