Given an integer x and a sorted array a of N distinct integers, design a linear-time algorithm to determine if there exists two distinct indices i and j such that a[i] + a[j] == x
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is type of Subset sum problem
Here is my solution. I don’t know if it was known earlier or not. Imagine 3D plot of function of two variables i and j:
For every
ithere is suchjthata[i]+a[j]is closest tox. All these(i,j)pairs form closest-to-x line. We just need to walk along this line and look fora[i]+a[j] == x:Complexity: O(n)