This is one of the basic interview question about algorithm about finding the two numbers from array such that there sum is equal to K.
In this post, we'll look into different approaches for finding all the pair of integer such that there sum is equal to K.
Approach 1 Brute-Force
In this approach, for each input element check whether there is any element exist whose sum is K. This can be solved with just two loops.
Time Complexity : O(n^2) for nested loops, Space Complexity : O(1)
Approach 2
In this approach, we first sort the array using merge or heap sort which give O(nlogn) complexity. Then on sorted array we main two indices, i point to starting index and j point to last element index. We compute A[i]+A[j]. If sum equals K, then we found the pair increment both i & j. If the sum is less then k, increment i, if sum is greater than K decrements j.
Time Complexity : O(nlogn) if array is already sorted then complexity would be O(n), Space Complexity : O(1)
Approach 3
In this approach we use HashMap, our task is find two indexes of the array whose sum is K i.e, A[i]+A[j]=K. For each input element A[i] we check whether K-A[i] also exist in the Hash map. key will be array element, value will be index of element.
Time Complexity : O(n) , Space Complexity : O(n)
If you know anyone who has started learning Java, why not help them out! Just share this post with them.
Thanks for studying today!...
In this post, we'll look into different approaches for finding all the pair of integer such that there sum is equal to K.
Approach 1 Brute-Force
In this approach, for each input element check whether there is any element exist whose sum is K. This can be solved with just two loops.
Time Complexity : O(n^2) for nested loops, Space Complexity : O(1)
Approach 2
In this approach, we first sort the array using merge or heap sort which give O(nlogn) complexity. Then on sorted array we main two indices, i point to starting index and j point to last element index. We compute A[i]+A[j]. If sum equals K, then we found the pair increment both i & j. If the sum is less then k, increment i, if sum is greater than K decrements j.
Time Complexity : O(nlogn) if array is already sorted then complexity would be O(n), Space Complexity : O(1)
Approach 3
In this approach we use HashMap, our task is find two indexes of the array whose sum is K i.e, A[i]+A[j]=K. For each input element A[i] we check whether K-A[i] also exist in the Hash map. key will be array element, value will be index of element.
Time Complexity : O(n) , Space Complexity : O(n)
If you know anyone who has started learning Java, why not help them out! Just share this post with them.
Thanks for studying today!...





