How to check for pair in array with given sum-interview problem?
Problem Description: Given an array of n integers and given a number K, determines whether there is a pair of elements in the array that sums to exactly K. Output: false (There is no pair of elements whose sum is equal to 15) Do we know something about the range of the numbers in the array? Ans: No, they can be arbitrary integers.
How to count pairs with a given sum?
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
How to print all pairs with given sum?
A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum. Method 2 (Use hashing) . We create an empty hash table. Now we traverse through the array and check for pairs in the hash table.
How to check the sum of two elements in an array?
Sort the array A [] then walk two pointers inward from the ends of the array, at each point looking at their sum. If it is exactly k, then we are done. If it exceeds k, then any sum using the larger element is too large, so we walk that pointer inwards.
How to find pair of numbers in array?
Use two pointers, X and Y. Start X=0 at the beginning and Y=N-1 at the end. Compute the sum sum = array [X] + array [Y]. If sum > M, then decrement Y, otherwise increment X. If the pointers cross, then no solution exists.
How to find pairs whose sums already exist in an array?
Given an array of n distinct and positive elements, the task is to find pair whose sum already exists in the given array. Recommended: Please try your approach on {IDE} first, before moving on to the solution. A Naive Approach is to run three loops to find pair whose sum exists in an array.
How to check for pairs in an array?
Use two loops and check A [i] + A [j] == K for each pair (i, j) in A []. If there exists a pair with sum equals to K then return true. By end of both loops, If you didn’t find such a pair then return false. The total no. of comparison in worst case = Total no. of possible pairs = nC2 = n (n-1)/2 = O (n²)
https://www.youtube.com/watch?v=8wrlCL6cvfQ