Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
2 Sum - Pair Sum Closest to Target using Binary Search
Next article icon

3 Sum – Triplet Sum Closest to Target

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of n integers and an integer target, the task is to find the sum of triplets such that the sum is closest to target. Note: If there are multiple sums closest to target, print the maximum one.

Examples:

Input: arr[] = [-1, 2, 2, 4], target = 4
Output: 5
Explanation: All possible triplets

  • [-1, 2, 2], sum = (-1) + 2 + 2 = 3
  • [-1, 2, 4], sum = (-1) + 2 + 4 = 5
  • [-1, 2, 4], sum = (-1) + 2 + 4 = 5
  • [2, 2, 4], sum = 2 + 2 + 4 = 8

Triplet [-1, 2, 2], [-1, 2, 4] and [-1, 2, 4] have sum closest to target, so return the maximum one, that is 5.

Input: arr[] = [1, 10, 4, 5], target = 10
Output: 10
Explanation: All possible triplets

  • [1, 10, 4], sum = (1 + 10 + 4) = 15
  • [1, 10, 5], sum = (1 + 10 + 5) = 16
  • [1, 4, 5], sum = (1 + 4 + 5) = 10
  • [10, 4, 5], sum = (10 + 4 + 5) = 19

Triplet [1, 4, 5] has sum = 10 which is closest to target.

Table of Content

  • [Naive Approach] Explore all Subsets of Size 3 – O(n^3) Time and O(1) Space
  • [Expected Approach] Sorting and Two Pointers – O(n^2) Time and O(1) Space

[Naive Approach] Explore all Subsets of Size 3 – O(n^3) Time and O(1) Space

The naive approach is to explore all subsets of size three and keep a track of the difference between target and the sum of the subset. Then, return the sum which is closest to target.

C++
// C++ program to find triplet sum closest to target by // exploring all triplets  #include <iostream> #include <limits.h> #include <vector> using namespace std;  int closest3Sum(vector<int> &arr, int target) {     int n = arr.size();     int minDiff = INT_MAX;     int res = 0;      // Generating all possible triplets     for (int i = 0; i < n - 2; i++) {         for (int j = i + 1; j < n - 1; j++) {             for (int k = j + 1; k < n; k++) {                 int currSum = arr[i] + arr[j] + arr[k];                 int currDiff = abs(currSum - target);                  // if currentDiff is less than minDiff, it indicates                 // that this triplet is closer to the target                 if (currDiff < minDiff) {                     res = currSum;                     minDiff = currDiff;                 }                 // If multiple sums are closest, take maximum one                 else if(currDiff == minDiff) {                 	res = max(res, currSum);                 }             }         }     }      return res; }  int main() {     vector<int> arr = {-1, 2, 2, 4};     int target = 4;     cout << closest3Sum(arr, target);     return 0; } 
C
// C program to find triplet sum closest to target by // exploring all triplets  #include <stdio.h> #include <limits.h> #include <stdlib.h>  int closest3Sum(int arr[], int n, int target) {     int minDiff = INT_MAX;     int res = 0;      // Generating all possible triplets     for (int i = 0; i < n - 2; i++) {         for (int j = i + 1; j < n - 1; j++) {             for (int k = j + 1; k < n; k++) {                 int currSum = arr[i] + arr[j] + arr[k];                 int currDiff = abs(currSum - target);                  // if currentDiff is less than minDiff, it indicates                 // that this triplet is closer to the target                 if (currDiff < minDiff) {                     res = currSum;                     minDiff = currDiff;                 }                 // If multiple sums are closest, take maximum one                 else if(currDiff == minDiff && res < currSum) {                 	res = currSum;                 }             }         }     }      return res; }  int main() {     int arr[] = {-1, 2, 2, 4};     int target = 4;     int n = sizeof(arr) / sizeof(arr[0]);     printf("%d", closest3Sum(arr, n, target));     return 0; } 
Java
// Java program to find triplet sum closest to target by // exploring all triplets  import java.util.*;  class GfG {     static int closest3Sum(int[] arr, int target) {         int n = arr.length;         int minDiff = Integer.MAX_VALUE;         int res = 0;          // Generating all possible triplets         for (int i = 0; i < n - 2; i++) {             for (int j = i + 1; j < n - 1; j++) {                 for (int k = j + 1; k < n; k++) {                     int currSum = arr[i] + arr[j] + arr[k];                     int currDiff = Math.abs(currSum - target);                      // if currentDiff is less than minDiff, it indicates                     // that this triplet is closer to the target                     if (currDiff < minDiff) {                         res = currSum;                         minDiff = currDiff;                     }                     // If multiple sums are closest, take maximum one                 	else if(currDiff == minDiff) {                 		res = Math.max(res, currSum);                 	}                 }             }         }          return res;     }      public static void main(String[] args) {         int[] arr = {-1, 2, 2, 4};         int target = 4;         System.out.println(closest3Sum(arr, target));     } } 
Python
# Python program to find triplet sum closest to target by # exploring all triplets  def closest3Sum(arr, target):     n = len(arr)     minDiff = float('inf')     res = 0      # Generating all possible triplets     for i in range(n - 2):         for j in range(i + 1, n - 1):             for k in range(j + 1, n):                 currSum = arr[i] + arr[j] + arr[k]                 currDiff = abs(currSum - target)                  # if currentDiff is less than minDiff, it indicates                 # that this triplet is closer to the target                 if currDiff < minDiff:                     res = currSum                     minDiff = currDiff                 # If multiple sums are closest, take maximum one                 elif currDiff == minDiff:                 	res = max(res, currSum)      return res  if __name__ == "__main__": 	arr = [-1, 2, 2, 4] 	target = 4 	print(closest3Sum(arr, target)) 
C#
// C# program to find triplet sum closest to target by exploring  // all triplets  using System;  class GfG {     static int closest3Sum(int[] arr, int target) {         int n = arr.Length;         int minDiff = int.MaxValue;         int res = 0;          // Generating all possible triplets         for (int i = 0; i < n - 2; i++) {             for (int j = i + 1; j < n - 1; j++) {                 for (int k = j + 1; k < n; k++) {                     int currSum = arr[i] + arr[j] + arr[k];                     int currDiff = Math.Abs(currSum - target);                      // if currentDiff is less than minDiff, it indicates                     // that this triplet is closer to the target                     if (currDiff < minDiff) {                         res = currSum;                         minDiff = currDiff;                     }                     // If multiple sums are closest, take maximum one                 	else if(currDiff == minDiff) {                 		res = Math.Max(res, currSum);                 	}                 }             }         }          return res;     }      static void Main() {         int[] arr = {-1, 2, 2, 4};         int target = 4;         Console.WriteLine(closest3Sum(arr, target));     } } 
JavaScript
// JavaScript program to find triplet sum closest to target by // exploring all triplets  function closest3Sum(arr, target) {     let n = arr.length;     let minDiff = Number.MAX_VALUE;     let res = 0;      // Generating all possible triplets     for (let i = 0; i < n - 2; i++) {         for (let j = i + 1; j < n - 1; j++) {             for (let k = j + 1; k < n; k++) {                 let currSum = arr[i] + arr[j] + arr[k];                 let currDiff = Math.abs(currSum - target);                  // if currentDiff is less than minDiff, it indicates                 // that this triplet is closer to the target                 if (currDiff < minDiff) {                     res = currSum;                     minDiff = currDiff;                 }                 // If multiple sums are closest, take maximum one                 else if(currDiff == minDiff) {                 	res = Math.max(res, currSum);                 }             }         }     }      return res; }  // Driver Code let arr = [-1, 2, 2, 4]; let target = 4; console.log(closest3Sum(arr, target)); 

Output
5

[Expected Approach] Sorting and Two Pointers – O(n^2) Time and O(1) Space

Initially, we sort the input array so that we can apply two pointers technique. Then, we iterate over the array fixing the first element of the triplet and then use two pointers technique to find the remaining two elements. Set one pointer at the beginning (left) and another at the end (right) of the remaining array. We then find the absolute difference between the sum of triplet and target and store the triplet having minimum absolute difference.

  • If sum < target, move left pointer towards right to increase the sum.
  • If sum > target, move right pointer towards left to decrease the sum.
  • If sum == target, we’ve found the triplet with sum = target, therefore this is the triplet with closest sum.
C++
// C++ program to find triplet sum closest to target using // sorting and two pointers  #include <iostream> #include <vector> #include <algorithm> #include <limits.h> using namespace std;  int closest3Sum(vector<int> &arr, int target) {     int n = arr.size();   	sort(arr.begin(), arr.end());     int res = 0;     int minDiff = INT_MAX; 	     for (int i = 0; i < n - 2; i++) {                // Initialize the left and right pointers       	int l = i + 1, r = n - 1;          while (l < r) {             int currSum = arr[i] + arr[l] + arr[r];                      	// If |currSum - target| < minDiff, then we have              // found a triplet which is closer to target             if (abs(currSum - target) < minDiff) {                 minDiff = abs(currSum - target);                 res = currSum;             }             // If multiple sums are closest, take maximum one             else if(abs(currSum - target) == minDiff) {             	res = max(res, currSum);             } 			           	// If currSum > target then we will decrease the              // right pointer to move closer to target             if (currSum > target)                 r--;                      	// If currSum >= target then we will increase the              // left pointer to move closer to target             else                 l++;         }     }      return res; }  int main() {     vector<int> arr = {-1, 2, 2, 4};     int target = 4;     cout << closest3Sum(arr, target);      return 0; } 
C
// C program to find triplet sum closest to target using // sorting and two pointers  #include <stdio.h> #include <stdlib.h> #include <limits.h>  // Function to compare integers for qsort int compare(const void *a, const void *b) {     return (*(int*)a - *(int*)b); }  int closest3Sum(int arr[], int n, int target) {     qsort(arr, n, sizeof(int), compare);     int res = 0;     int minDiff = INT_MAX;      for (int i = 0; i < n - 2; i++) {         int l = i + 1, r = n - 1;          while (l < r) {             int currSum = arr[i] + arr[l] + arr[r];              // If |currSum - target| < minDiff, then we have              // found a triplet which is closer to target             if (abs(currSum - target) < minDiff) {                 minDiff = abs(currSum - target);                 res = currSum;             }             // If multiple sums are closest, take maximum one             else if(abs(currSum - target) == minDiff) {                 if(res < currSum)                     res = currSum;             }              // If currSum > target then we will decrease the              // right pointer to move closer to target             if (currSum > target)                 r--;              // If currSum <= target then we will increase the              // left pointer to move closer to target             else                 l++;         }     }      return res; }  int main() {     int arr[] = {-1, 2, 2, 4};     int target = 4;     int n = sizeof(arr) / sizeof(arr[0]);     printf("%d", closest3Sum(arr, n, target));      return 0; } 
Java
// Java program to find triplet sum closest to target using // sorting and two pointers  import java.util.*;  class GfG {     static int closest3Sum(int[] arr, int target) {         int n = arr.length;         Arrays.sort(arr);         int res = 0;         int minDiff = Integer.MAX_VALUE;          for (int i = 0; i < n - 2; i++) {                          // Initialize the left and right pointers             int l = i + 1, r = n - 1;              while (l < r) {                 int currSum = arr[i] + arr[l] + arr[r];                  // If |currSum - target| < minDiff, then we have                  // found a triplet which is closer to target                 if (Math.abs(currSum - target) < minDiff) {                     minDiff = Math.abs(currSum - target);                     res = currSum;                 }                 // If multiple sums are closest, take maximum one                 else if(Math.abs(currSum - target) == minDiff) {                     res = Math.max(res, currSum);                 }                  // If currSum > target then we will decrease the                  // right pointer to move closer to target                 if (currSum > target)                     r--;                  // If currSum <= target then we will increase the                  // left pointer to move closer to target                 else                     l++;             }         }          return res;     }      public static void main(String[] args) {         int[] arr = {-1, 2, 2, 4};         int target = 4;         System.out.println(closest3Sum(arr, target));     } } 
Python
# Python program to find triplet sum closest to target using # sorting and two pointers  def closest3Sum(arr, target):     n = len(arr)     arr.sort()      res = 0     minDiff = float('inf')      for i in range(n - 2):         # Initialize the left and right pointers         l, r = i + 1, n - 1          while l < r:             currSum = arr[i] + arr[l] + arr[r]              # If |currSum - target| < minDiff, then we have              # found a triplet which is closer to target             if abs(currSum - target) < minDiff:                 minDiff = abs(currSum - target)                 res = currSum             # If multiple sums are closest, take maximum one             elif abs(currSum - target) == minDiff:                 res = max(res, currSum)              # If currSum > target then we will decrease the              # right pointer to move closer to target             if currSum > target:                 r -= 1              # If currSum <= target then we will increase the              # left pointer to move closer to target             else:                 l += 1      return res   if __name__ == "__main__":     arr = [-1, 2, 2, 4]     target = 4     print(closest3Sum(arr, target)) 
C#
// C# program to find triplet sum closest to target using // sorting and two pointers  using System;  class GfG {     static int closest3Sum(int[] arr, int target) {         int n = arr.Length;         Array.Sort(arr);         int res = 0;         int minDiff = int.MaxValue;          for (int i = 0; i < n - 2; i++) {                        // Initialize the left and right pointers             int l = i + 1, r = n - 1;              while (l < r) {                 int currSum = arr[i] + arr[l] + arr[r];                  // If |currSum - target| < minDiff, then we have                  // found a triplet which is closer to target                 if (Math.Abs(currSum - target) < minDiff) {                     minDiff = Math.Abs(currSum - target);                     res = currSum;                 }                 // If multiple sums are closest, take maximum one             	else if(Math.Abs(currSum - target) == minDiff) {             		res = Math.Max(res, currSum);             	}                  // If currSum > target then we will decrease the                  // right pointer to move closer to target                 if (currSum > target)                     r--;                  // If currSum <= target then we will increase the                  // left pointer to move closer to target                 else                     l++;             }         }          return res;     }      static void Main() {         int[] arr = { -1, 2, 2, 4 };         int target = 4;         Console.WriteLine(closest3Sum(arr, target));     } } 
JavaScript
// JavaScript program to find triplet sum closest to target using // sorting and two pointers  function closest3Sum(arr, target) {     let n = arr.length;     arr.sort((a, b) => a - b);     let res = 0;     let minDiff = Number.MAX_SAFE_INTEGER;          for (let i = 0; i < n - 2; i++) {                  // Initialize the left and right pointers         let l = i + 1, r = n - 1;          while (l < r) {             let currSum = arr[i] + arr[l] + arr[r];                          // If |currSum - target| < minDiff, then we have              // found a triplet which is closer to target             if (Math.abs(currSum - target) < minDiff) {                 minDiff = Math.abs(currSum - target);                 res = currSum;             }             // If multiple sums are closest, take maximum one             else if(Math.abs(currSum - target) == minDiff) {             	res = Math.max(res, currSum);             }                          // If currSum > target then we will decrease the              // right pointer to move closer to target             if (currSum > target)                 r--;                          // If currSum <= target then we will increase the              // left pointer to move closer to target             else                 l++;         }     }      return res; }  // Driver Code let arr = [-1, 2, 2, 4]; let target = 4; console.log(closest3Sum(arr, target)); 

Output
5




Next Article
2 Sum - Pair Sum Closest to Target using Binary Search

R

Ripunjoy Medhi
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • Mathematical
  • Programming Language
  • Sorting
  • two-pointer-algorithm
Practice Tags :
  • Algorithms
  • Arrays
  • Mathematical
  • Sorting
  • two-pointer-algorithm

Similar Reads

  • 2 Sum - Pair Sum Closest to Target
    Given an array arr[] of n integers and an integer target, the task is to find a pair in arr[] such that it’s sum is closest to target. Note: Return the pair in sorted order and if there are multiple such pairs return the pair with maximum absolute difference. If no such pair exists return an empty a
    15 min read
  • 4 Sum - Quadruplet Sum Closest to Target
    Given an array arr[] of n integers and an integer target, the task is to find a quadruplet in arr[] whose sum is closest to target. Note: There may be multiple quadruplets with sum closest to the target, return any one of them. Examples: Input: arr[] = {4, 5, 3, 4, 1, 2}, target = 13Output: {4, 5, 3
    15 min read
  • Find the Closest Subsequence Sum to Target
    Given an integer array arr[] and an integer target. The task is to find a subsequence of arr such that the absolute difference between the sum of its elements and target is minimized. Return the minimum possible value of abs(sum - target). Note: Subsequence of an array is an array formed by removing
    5 min read
  • 2 Sum - Pair Sum Closest to Target using Binary Search
    Given an array arr[] of n integers and an integer target, the task is to find a pair in arr[] such that it’s sum is closest to target. Note: Return the pair in sorted order and if there are multiple such pairs return the pair with maximum absolute difference. If no such pair exists return an empty a
    10 min read
  • Subset with sum closest to zero
    Given an array 'arr' consisting of integers, the task is to find the non-empty subset such that its sum is closest to zero i.e. absolute difference between zero and the sum is minimum.Examples: Input : arr[] = {2, 2, 2, -4} Output : 0 arr[0] + arr[1] + arr[3] = 0 That's why answer is zero.Input : ar
    8 min read
  • Two Sum - Pair Closest to 0
    Given an integer array arr[], the task is to find the maximum sum of two elements such that sum is closest to zero. Note: In case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.Examples: Input: arr[] = [-8, 5, 2, -6]Output: -1Explanation: The min absol
    15+ min read
  • 3 Sum - Triplet Sum in Array
    Given an array arr[] of size n and an integer sum, the task is to check if there is a triplet in the array which sums up to the given target sum. Examples: Input: arr[] = [1, 4, 45, 6, 10, 8], target = 13Output: true Explanation: The triplet [1, 4, 8] sums up to 13 Input: arr[] = [1, 2, 4, 3, 6, 7],
    15 min read
  • Print triplets with sum less than k
    Given an array of distinct integers and a sum value. Print all triplets with sum smaller than given sum value. Expected Time Complexity is O(n2). Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : (-2, 0, 1) (-2, 0, 3) Explanation : The two triplets have sum less than 2. Input : arr[] = {5, 1
    15 min read
  • 3 Sum - Count all triplets with given sum
    Given an array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: 2Explanation: Two triplets that add up to -2 are:arr[0] + arr[3] + arr[4] = 0 + (-3) + (1
    10 min read
  • Find all triplets that sum to a given value or less
    Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X. Example: Input : arr[] = {-1, 1, 3, 2}, X = 3Output: (-1, 1, 3), (-1, 1, 2)Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences