January 18, 2025 |6.5K Views

3 Sum – Triplet Sum Closest to Target

Explore Courseexplore course icon
Description
Discussion

To find the triplet in an array whose sum is closest to a given target, two approaches can be utilized. The naive approach involves exploring all subsets of size three and calculating their sums to determine the closest to the target. Though straightforward, this method has a time complexity of O(n^3), making it less efficient for large arrays.

The optimized approach employs sorting and the two-pointer technique. After sorting the array, the first element of the triplet is fixed, and two pointers are used to find the other two elements. This method ensures O(n^2) time complexity while maintaining O(1) space complexity, making it efficient for practical applications. If multiple triplets have sums equally close to the target, the maximum sum is selected.

For more details, please go through - 3 Sum – Triplet Sum Closest to Target