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

0% completed

Vote For New Content
Durgance Gaur
Python Easy to Understand Solution , by taking score and checking.... LeetCode Beats ~93%

Durgance Gaur

Nov 26, 2025

<p>```python import math class Solution: def searchTriplet(self, arr, target_sum): # TODO: Write your code here arr.sort() score = float('inf') for i in range(len(arr)): target = arr[i] left = i+1 right = len(arr)-1 while left= abs(target_sum-total): score = min(score,abs(target_sum-total)) ans = total left += 1 elif total &gt; target_sum: if score &gt; abs(target_sum-total): score = min(score,abs(target_sum-total)) ans = total right -= 1 else: return target_sum return ans ``` ## In the the approach.. I have used a score variable to check for the difference between the target_sum and total and then compared it with previous score and used = sign only in the case when the total is less then the target_sum so that we can update the ans variable even when the score is already the same as the score from previous triplet. &gt; Example : &gt; [-1,0,3] and [-1,2,3] will both have the same score of 1 but the logic will update the ans to 2 rather then keeping it at 4 for the target sum of 3. Other then that its the regular logic of if total is less increment left/ if total is greater decrement right. Thanks for Reading !! </p>

0

0

Comments
Comments

On this page

Problem Statement

Solution

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity