Author : Pratik Gholap
All Tutorials of Hashing are listed here : https://www.desiqna.in/tag/hashing_tutorials
It is recommended to go through previous hashing tutorials to get a better understanding.
PART _ (Given an array and target 'x', Find out the pair from array whose sum forms the number 'x' when both the numbers of the pair are added) :
Given an array arr1 and number 'x', To find if a pair exists in arr1 which can be added to make number 'x'.
Example-1:
Input:
arr1 = {0, -1, 2, -3, 1}
x = -2
Output: true
(-3, 1) or (1,-3) are the pairs which exist in arr1 which makes sum equal to x (-3+1=-2 and 1-3=-2)
Explanation: Calculate the sum of all possible pairs and return (true/false) if the value of any pair is equal/not equal to 'x'.
Example-2:
Input:
arr1 = {1, -2, 1, 0, 5}
x = 0
Output: false
Explanation: No sum of pairs in array has sum as 0 , therefore , false will be the answer
Approach 1: Brute-Force Approach
In the problem , we have to find the pair so to find the pair in the array, we can take one element from the array and check the remaining part by adding every element with the taken element if we get the sum equal to the number 'x' we will return true otherwise false.
So this can be done by using 2 'for' loops, First Loop we will use to take first element and Second loop will be used to traverse the array to find the second number.
Algorithm:
Time Complexity : O(n^2)
Space Complexity : O(1)
Piece of code(C++) :-
Approach 2: Hashing
As we see the above Brute-Force approach, it will work good for small size of array but for large size it will be inefficient in terms of computing the problem so we need to optimise the solution to the problem. We can do this using hashing, In this problem we will use set which will help us in maintaining the elements presence and help in accessing them faster.
So basically, we will use a single 'for' loop in which for iteration we will take the difference of 'x' and 'arr[i]' and check if that difference value is present in the set . We are using set(unordered_set) as HashTable in this problem.
Algorithm:
Time Complexity : O(n)
Space Complexity : O(n)
Piece of code(C++) :-
All Tutorials of Hashing are listed here : https://www.desiqna.in/tag/hashing_tutorials