I have two Stacks s1 and s2. s1 containing negative integers and s2 containing positive integers. Both Stacks have been sorted already from lowest value(at the bottom) to highest(at the top). x1 and x2 are integers in s1 and s2. I would like to check both Stacks to see whether [x1 + x2 = a given integer i]. What is the best way(or THE way) to do this in O(n)?
Update: x1 and x2 are integers..sorry
update 2: the method returns a boolean value and would have these parameters:
boolean method(Stack s1, Stack s2, int i)
method would return true if any integer x1 in s1 + any integer x2 in s2 = i
I assume you mean any number in s1 + any number in s2 is a given integer i.
If so,
(at any time, if a stack is empty, you are done — there is no answer)
EDIT: I think I am wrong on step 4 based on your sort order — but this basic idea should be close.