Triplet Sum Problem Solution with Two Pointer Technique

🚀 Day 49 of My Coding Journey Today I solved my second problem of the day: 👉 Triplet Sum Problem 🧠 Problem: Given an array and a target value, determine whether there exists a triplet whose sum equals the target. 💡 Example: arr = [1, 4, 45, 6, 10, 8], target = 13 ✔️ Output: true (Triplet: 1, 4, 8) ⚡ My Approach: At first, I considered the brute force method (checking all combinations), but that would take O(n³) time ❌ Then I optimized it using: 👉 Sorting + Two Pointer Technique 🔹 Steps: Sort the array Fix one element Use two pointers (left & right) to find the remaining sum ⏱️ Time Complexity: O(n²) ✅ 💡 Key Learning: Transforming a 3Sum problem into a 2Sum problem makes it much more efficient. 📈 Progress: This is my second problem on Day 49, and I’m improving my understanding of patterns like Two Pointer and optimization techniques. Small improvements every day lead to big results 💪 #Day49 #CodingJourney #Java #DSA #ProblemSolving #Consistency #Learning My way ===== class Solution {   public boolean hasTripletSum(int arr[], int target) {    int sum=0;    Arrays.sort(arr);    for(int i=0;i<arr.length;i++)    {     int left=i+1;     int right=arr.length-1;     while(left<right)     {       sum=arr[i]+arr[left]+arr[right];       if(sum==target)       {         return true;       }       else if(sum<target)       {         left++;       }       else       {         right--;       }     }          }     return false;   } }

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories