GFG Problem

https://www.geeksforgeeks.org/problems/key-pair5616/1

Problem Statement: Given an array of numbers, I had to determine if there exists a pair of elements that adds up to a specific target sum. ??

My Solution: I approached this problem using a Hash, which is particularly handy when dealing with unsorted arrays. I implemented a solution with a time complexity of O(n) by traversing the array once and efficiently checking for the existence of a complement.

hasArrayTwoCandidates(arr,n,x){
    let vals = {};
    let i = 0;
    while(i < n){
       if(vals[x - arr[i]]){
           return true;
       }else{
            vals[arr[i]] = 1;
       }
       i++;
    }
    return false;
}        

Time Complexity: O(N), Space Complexity: O(N)

Other Solution: Using the Two Pointers technique, leveraging the fact that the array was sorted. I implemented a solution with a time complexity of O(n) by using two pointers that move towards each other based on the current sum.

hasArrayTwoCandidates(arr,n,x){
        arr.sort((a, b) => a - b);
        let left = 0;
        let right = n -1;
        while(left < right){
            let sum = arr[left] + arr[right];
            if(sum == x) return true;
            if(sum > x) right--;
            if(sum < x) left++;
        }
        return false;
    }        

Time Complexity: O(N), Space Complexity: O(1)




Paras Sharma

Full stack developer | MERN stack developer full stack software developer |React JS | Node js | Machine learning | Golang, Python, FastApi

1 å¹´

Two pointer technique is really good

要查看或添加评论,请登录

社区洞察

其他会员也浏览了