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

0% completed

Vote For New Content
 sealess
My solution

sealess

Mar 7, 2024

import math class Solution: def searchTriplet(self, arr, target_sum): # TODO: Write your code here arr.sort() curr = arr[0] + arr[1] +arr[2] gap = abs(curr - target_sum) for i in range(len(arr)): l, r = i+1, len(arr)-1 while l < r: newcurr = arr[i] + arr[l] + arr[r] newgap = abs(newcurr - target_sum) if newgap<gap: gap= newgap curr = newcurr elif newgap == gap and newcurr < curr: gap= newgap curr = newcurr if newcurr > target_sum: r-=1 elif newcurr < target_sum: l +=1 else: return target_sum return curr

0

0

Comments
Comments

On this page

Problem Statement

Try it yourself