538 views
1 votes
1 votes
Consider the problem that given a set Sof n integers and another integer x, whether or not there exist two elements in S whose sum is exactly x. What is the worst case time complexity for the most efficient algorithm which solves the given problem?
Is not it work like subset sum problem in dynamic programming? Then complexity should be O(n^2).
How O(n logn)?

1 Answer

2 votes
2 votes
Solution:
1. Sort the array → nlogn
2. Consider i=0 and j=n-1(Last element)
3. sum= arr[i] + arr[j]
4. If sum<x then i++ (  we need to increase the value of sum so we should increment i to increase the overall sum as the array is sorted)
5. Similarly if sum>x then j—
6. If sum==x then match found

Therefore total complexity= nlogn + n = nlogn

Additional info:
This problem can be solved in O(n) complexity as well using extra space, this is a famous problem known as “Two Sum”.

Related questions

0 votes
0 votes
0 answers
1
0 votes
0 votes
1 answer
2
Sachdev aprajita asked May 23, 2019
439 views
Finding the running time of the following algorithm.$Procedure$ $A(n)$ $\textrm{ if (n}<=\textrm{2) then return 1 ;}$ $else$ $Return(A(\left \lceil \sqrt{n} \right ...
1 votes
1 votes
1 answer
3
shikharV asked Nov 15, 2015
1,043 views
The answer to the above problem is A but I am expecting it to be D as constant amount of work is required to solve each subproblem.
0 votes
0 votes
0 answers
4
Sajal Mallick asked Nov 27, 2023
195 views
As we have to select maximal set of “non overlapping” activities. So like job scheduling algo of greedy we can solve it. So according to that complexity must be O(n l...