Prove that given a number we can find whether there're 2 elements in a red/black tree that their sum equals that number in $\Theta(n)$ time and constant space.
The original problem appears here, however the solution uses $\lg n$ space. A problem in my course required adjusting the algorithm such that we use constant space.
I thought of the following algorithm:
MyAlgorithm(root, num)
min<-findMin(root)
max<-findMax(root)
while(min.key <= max.key && min != max)
if((min.key + max.key)=num) return true
if((min.key + max.key) < num)
min<-successor(min)
else
max<-predeccessor(max)
return false
According the CLRS book both predeccessor()
and successor()
functions time complexity depends on tree height which is $O(\lg n)$ in our case since red-black tree is balanced.
However, we have the while
loop which theoretically can run almost n
times.
For example, because the algorithm above is equivalent to searching for the number num
in a sorted array, say we have this array and num<-3
:
$$
1,2,3,4,5,6,7,8,9,10
$$
In this case we'll call predecessor(max)
$8$ times which is almost $\Theta(n)$ or $\Theta((n-2)\lg n)=\Theta(n\lg n)$ asymptotically.
Am I wrong in my conclusions? How can I prove that the time complexity is indeed $\Theta(n)$?