I have two sets of arrays, as and bs, all of length n. If I choose an a and a b, I know that a[i] <= N and b[i] <= N for all 0 <= i < n. What's the most efficient way to calculate whether a[i] + b[i] <= N for all i?
Currently, I'm simply looping through the arrays and comparing a[0] + b[0] <= N, a[1] + b[1] <= N etc. Obviously this is an O(n) approach.
Is there any way to pre-process the as and bs arrays so that the search for a sum a[i] + b[i] > N can be done faster than linear time?
If you can't preprocess, then
O(n)is the best you can have. Proof is by contradicion: suppose you are given some algorithm which is better thanO(n); it means that for some largensome indexes will be skipped (since the algorithm has better than linear time complexity). We can construct a counter example; let's run the algorithm for a large enoughnif algorithm returns
false(i.e. for someja[j] + b[j] > N) it is incorrect. If algorithm returnstrueit skips some indexes, e.g. indexk(since the algorithm is better than linear andnis large enough). So the counter example will bethe algorithm will return
false(indexkwill be skipped, when all the rest values are the same as in the 1st run) which is incorrect now.If you can preprocess
aandbarrays, you can computemax = Max(a[i] + b[i])and then returnhaving
O(1)time and space complexity