From 15ebc627a54f6a1281215449fe00eb267a8b6c9c Mon Sep 17 00:00:00 2001 From: Avnee29 Date: Mon, 28 Oct 2024 15:07:27 +0530 Subject: [PATCH] POTD_27_OCT_2024_TripletFamily.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Efficient approach: The idea is similar to Find a triplet that sum to a given value.   Sort the given array first. Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element. Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k]. If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k]. Time Complexity: O(N^2) Auxiliary Space: O(1) --- 27_OCT_2024_TripletFamily.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 27_OCT_2024_TripletFamily.cpp diff --git a/27_OCT_2024_TripletFamily.cpp b/27_OCT_2024_TripletFamily.cpp new file mode 100644 index 0000000..6f72acd --- /dev/null +++ b/27_OCT_2024_TripletFamily.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool findTriplet(vector& arr) { + // Your code + int n = arr.size(); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + for(int k = j + 1; k < n; k++) { + if((arr[i]+arr[j]==arr[k]) || (arr[i]+arr[k]==arr[j]) || (arr[j]+arr[k]==arr[i])){ + return true; + } + + } + } + } + + return false; + } +};