MuhammadTausif / gfg-excercises

This repo is about exercises at GFG
Apache License 2.0
0 stars 0 forks source link

Triplet Family - POTD | 27-Oct-2024 #58

Closed MuhammadTausif closed 1 hour ago

MuhammadTausif commented 1 hour ago

Triplet Family

Link

Difficulty: Basic

Given an array arr of integers. Find whether three numbers are such that the sum of two elements equals the third element.

Example:

Input: arr[] = [1, 2, 3, 4, 5]
Output: true
Explanation: The pair (1, 2) sums to 3.
Input: arr[] = [5, 3, 4]
Output: false
Explanation: No triplets satisfy the condition.

Expected Time Complexity: O(n2) Expected Auxilary Space: O(1)

Constraints:

MuhammadTausif commented 1 hour ago

Solved

public boolean findTriplet(int[] arr) {

        Map<Integer, Integer>mp = new HashMap<>();
        for(int i=0;i<arr.length;i++){
            mp.put(arr[i], i);
        }
        for(int i=0;i<arr.length-1;i++){
            for(int j=i+1;j<arr.length;j++){
                int s=0;
                s=arr[i]+arr[j];
                if(mp.containsKey(s)){
                    return true;
                }
            }
        }
        return false;
    }