patternjavaMinor
Determining if a pair exists in a large sorted array
Viewed 0 times
determiningarraylargeexistssortedpair
Problem
I'm doing practice interview questions from here. Here is the one I am currently on - if you are given a very large sorted
I tested this code and it works. What I am having trouble with is the next part of the question - he asked if there's an optimal method \$O(1)\$ to find the match for the previous question?
How would you optimize this code so that the match is a constant time operation? I still don't how that would be done because it looks like iteration is still required.
int array, then check of there exists a pair.public static int sumOfTwoExists(int[] largeArray, int a, int b) {
A: for(int count = 0; count a + b) {
break A;
}
}
}
return -1;
}I tested this code and it works. What I am having trouble with is the next part of the question - he asked if there's an optimal method \$O(1)\$ to find the match for the previous question?
How would you optimize this code so that the match is a constant time operation? I still don't how that would be done because it looks like iteration is still required.
Solution
\$O(1)\$ is impossible indeed. Your solution is \$O(n^2)\$, because you ignore the most important part of the question: the array is sorted.
The \$O(n)\$ solution is to set a pair of iterators to the beginning and the end of the array. Then if a sum of their values is less than target, advance the beginning; if it greater, retreat the end. Keep going until they meet (or a target is found).
The \$O(n)\$ solution is to set a pair of iterators to the beginning and the end of the array. Then if a sum of their values is less than target, advance the beginning; if it greater, retreat the end. Keep going until they meet (or a target is found).
Context
StackExchange Code Review Q#78446, answer score: 5
Revisions (0)
No revisions yet.