Back to course home
0% completed
Vote For New Content
Would a one function solution be better?
azaankhan14678
Dec 6, 2023
So I wrote out the following:
class Solution: def searchTriplets(self, arr, target): arr.sort() count = 0 for i in range(len(arr)-2): left = i+1 right = len(arr)-1 while left < right: curr = arr[i] + arr[left] + arr[right] if curr < target: count += right - left left +=1 else: right -= 1 return count
I essentially took the gist of what we did in the previous problem(Triplet Sum Close to Target) and created a solution using one function. My question is that is this soultion just as good or better, or worse than the actual solution if it is utilizing only one function rather than creating and calling upon a second one?
2
0
Comments
Comments
Hussain Zaidi2 years ago
Yes I like the one function solution better because it's easier to expand for 4Sum or 4 triplets since we can simply add another for loop. Also, it's more understandable to write arr[i] + arr[left] + arr[right]
On this page
Problem Statement
Try it yourself