Log In
75 votes
Suppose we have a balanced binary search tree $T$ holding $n$ numbers. We are given two numbers $L$ and $H$ and wish to sum up all the numbers in $T$ that lie between $L$ and $H$. Suppose there are $m$ such numbers in $T$. If the tightest upper bound on the time to compute the sum is $O(n^a\log^bn+m^c\log^dn)$, the value of $a+10b+100c+1000d$ is ______.
in DS
recategorized by

Just additional information -->

In worst case we may have to traverse each element in order to check that the element is in between L and H or not, because it is not given that L and H are in the Tree so How can we traverse each elements in O(m) time?
how you get b as 1, then d also can be 1 ?
This a beautiful question and equally beautiful discussion.


Just compare the answer $\mathbf{O(\log n + m)}$ which you get after solving, with the pattern given in the question, that is, with $\mathbf{O(n^a\log^bn+m^c\log^dn)}$


The explanation provided here and to, both contradict each other. Please explain any difference, why answer is different.

During inorder traversal if we take elements between L and H then it take O(n) time(time for in order traversal) then why we do some extra work and pay extra cost O(log n). Because L and H is already given and L and H need not be in BST.

So answer is a=1 , b=0, c=0, d=0.

We can't take 'm' ='n' because in worst case all tree elements sum up.

6 Answers

111 votes
Best answer

In worst case for finding $L$ and $H$ it will take $O(\log n)$ time as the given tree is balanced binary search tree.
Now there are $m$ elements between $L$ and $H$. So to traverse m element it will take $O(m)$ time (traversal algorithm given below). So, total

$O(m+\log n)  \implies a=0, b=1,c=1,d=0$
$\therefore 0+(10 \times 1)+(100 \times 1)+(1000 \times 0)=110$. 

To find all the numbers from $L$ to $H$ we can do an inorder traversal from root and discard all elements before $L$ and after $H$. But this has $O(n)$ time complexity. So, we can do a modification to inorder traversal and combine with binary search as follows:

  1. Find $L$ using binary search and keep all nodes encountered in the search in a stack. 
  2. After finding $L$ add it to stack as well and initialize $sum = 0$.
  3. Now, for all nodes in stack, do an inorder traversal starting from their right node and adding the node value to sum. If $H$ is found, stop the algorithm. 

selected by

Point 3, you are saying do inorder traversal starting from the right node until H is encountered. It is for all values encountered in stack. Then i think time complexity will be more.

Sir, the tree is a balanced BST unlike the one you've drawn.

@kalpish, can you elaborate this stack using concept with some example? see this discussion on group.

See we can understand like this :

First in order to find number which is labelled L , it will O(logn) time as it is a balanced BST.Then to add the m numbers between L and H , we use the modification of inorder traversal which will hence take O(m) time.Hence the value of a = 0 , b = 1 , c = 1 and d = 0 Hence the answer is 110.

I think while searching L we should not keep all the elements in the stack. Only the elements which are greater than L has to  be kept.
Otherwise we may be adding values smaller than L or sometimes same values more than once.

While searching for 15, we should not add 10 to the stack.

Impeccable explanation! Thanks a lot...
How can we start inorder from L?

anyhow we have to reach L first!
For reaching L log n is time, as explained in answer. Sorry for previous comment stack will be required.
why answer isn't 1100-(c=1,d=1)

Balanced BST takes logn time and for each m element it takes O(mlogn)
For each m element it does not take mlogn.

Search for L in Balanced Binary Search Tree = O(Log n)

Now, start taking inorder elements of the balanced tree, one by one. In each iteration you compare the element you got with L and H. If the element is between L && H then add it to the sum.

Hence, after inorder traversal is complete, you will have the sum (no need to complete inorder traversal till n elements since we are concerned only till m).

Total time taken = Time to search L + inorder Traversal of only m elements

O(logn + m)
DFS takes $O(x +y)$ time where $x$ is the number of nodes and $y$ is the number of edges. What to do with the $y$? No information is given in the question. Should we ignore it? Or can we do it like this:
A tree with $m$ nodes has $m - 1$ edges, so $O(x + y)$ becomes $O(m + m - 1) \rightarrow O(2m -1)=O(m)$.

Think like this

(1)L and H don't exist in the tree.

(2)L and H are the lowest and the highest data value respectively in balanced bst.

For case1: First before finding sum I need to make sure whether my L and H exist in BST or not. If they don't exist, then I won't execute my code for finding the sum. So, TC for finding L and H in Balanced BST is $O(logn)$

This is obviously not the worst case.

Case 2: Worst Case: First find L and H->$O(logn)$

Say, all n nodes lie between L and H. Now I need to find sum of all numbers in BST.

Do Inorder traversal in $O(n)$ time.

Total time complexity : $O(logn+n)$

In most of the answers and cooments it is said that " we can find L in O(Log n) and O(m) for sum".

I am not getting why and how it is O(m) ?

How traversal is applied on m elements ??
we already know L number then why we search it...why can't we do directly inorder traversal and add numbers after L

After finding L logn time ..we should apply inorder tranversal from node we want nos > L and <H

and we can continue adding till we reached wll take O(m) right ??


@Ayush Upadhyaya

If BST is given instead of BBST/AVL

Then O(n) [worst case to search L] + O(m) (indorder) ==> O(n)  ???


@jatin khachane 1-Yes I think so.

In the worst case, all elements might be present in between L and H, then it should take O(n) time to sum it up

@Ayush Upadhyaya 's comment is the perfect answer.

It will $\mathbf{O(n)}$ in the worst case and not $\mathbf{O(m)}$


I am still doubtful whether its $\mathbf{O(m)}$ or $\mathbf{O(n)}$ in the $\mathbf{Worst\;Case}$.

Can someone can clarify this.





@Ayush Upadhyaya

@Verma Ashish

Shaik Masthan


@`JEET it will be O(m).

We will first find L. As it is a BBST so it will take logn time. Now as you get L. From that node you apply inorder traversal upto H(it is given to us so no need to go further. Stop as you get H). Initialize a variable sum and add the nodes value encountered in the traversal to sum. Hence just m elements not n.

How inorder traversal after L-

I am applying inorder traversal in above tree drawn by Rajendra Dangwal see above comments.

You got L=15. Now do inorder from L. Take H=28

20,22,25,26. You got 28 stop algorithm further. And add nodes to variable sum. So we traversed m elements between L and H not n elements.

Time= O(logn+m)

Hope it helps.


Can anyone help me in understanding what is the significance of maintaining a Stack and doing inorder traversal for each element (which is added to Stack) from Right Child?

Why are we assuming that L and H are present in the tree? Am I missing something here?
read the qsn
66 votes

Here is an example 😊

$L =25 , H = 35$
Inorder: $10,15,20,\underset{L}{\boxed{25}},26,27,28,30,31,32,33,34,\underset{H}{\boxed{35}},36,39,42$

  1. Find $L$ and $H \rightarrow O(\log n)$ time.
  2. Traverse '$m$' elements between '$L$' and  '$H$' $\rightarrow O(m)$ [Traversal algorithm]

Total $\rightarrow  O(m + \log n) $

$\qquad a= 0,b=1,c=1,d=0$

$\qquad 10 + 100 = 110$ Answer

Traversal Algorithm:

  1. Find $L$ using Binary search and keep  $H>node> L$ encountered in the search in a stack.
  2. After finding $L,$ add it to stack as well & initialize $sum = 0$
  3.  Now, for all nodes in the stack, do an inorder traversal starting from their right node and adding the node value to sum. If it is found than stop the algorithm.
  • Node (1) 
    • No Right child; Sum = Sum + Node value $= 0 + 25 = 25.$
  • Node (2)
    • Inorder Traversal from Right Child $\rightarrow  24,28$
    • Sum = sum + inorder Traversal + Node Value $=  (25 + 27 + 28) + 26$
  • Node (3)
    • Inorder Traversal From Right Child $\rightarrow 31,32,33,34,\overset{H}{\bf{35}}\overset{\to \text{Stop Inorder Traversal}}{}$
    • Sum = Sum + Inorder Traversal + Node value
      • $\qquad = 25 + 26 + 24 + 28 + (31 + 32 + 33 + 34 + 35) + 30$
      • $\qquad = 25 + 26 + 24 + 28 + 30 + 31 + 32  + 33 + 34 + 35$  Answer


  1. In Step 1, we need to find only $L$ and not $H.$
  2. In Traversal Algo: Find $L$ using Binary Search and Keep, L< Nodes< H, encountered in the search in the stack.

edited by
Thanks for valuable effort.

Now, I am having a doubt

Why traversal algo will take O(m) time ? :P

Why traversal algo will take O(m) time ? :P

OK, But first tell me why do you think we can access node > O(m) ?

I am thinking like this :

Maxi. in stack we could have logn nodes

for each of logn nodes we will do inorder traversal on right subtree.

tc=logn +m
Hi @VS ji,

Step (1) of your solution requires small correction( First we are only finding L)

Now for L we are doing in-order traversal of partially visited tree. In-order traversal gives output nodes in sorted order if it is BS-tree. So after traversal of m nodes. you will get your H also. I hope this helps.
VS is fine no need of "ji" or call me Vidhi

I got it :)

In first part we only need to Find L and no need of finding H.
@VS.Just a small addition, i think while pushing a node ,we should check if the node is <H.  Suppose in your tree i need sum from 15 to 23,then while going to left of 30, there is no need to push 30.In case we push ,then when we pop before adding we need to check that if the popped item from stack is <H.only then goto right subtree
Nice explanation ...
awesome explainantion !!!
nice explanation.. i wonder whether people were able to derive algo in exam
I just have one doubt wht we are using INORDER only??? why not any other traverasals....our main air to traverse from L to H right?? then why only INORDER ....
note, the given tree is a binary search tree(balanced) and only inorder traversal of bst guarentees elements in increasing order, we need to find elements sum between 2 elements let's say L and H. So we first find L and theen start inorder traversal after that so it guarenntes that all the elements between L and H will be found out that too in increasing order, and if you use any other traversal then there is a possibilty that you may add some extraa elements which are not b/w L and H(even if you come up with such an algorithm).
i think it should be best answer.. nice explanation.
can u provide me your notes pls if u have
I think the diagram needs and edit below node 25 there is node 26 which needs to be removed else inorder shoukd have two 26.Sorry if interpreted wrong.

A minor correction :


Node (2)

  • Inorder Traversal from Right Child β†’24,28

Instead of 24, it should be 27. 

20 votes

int getSum(node *root, int L, int H)
   // Base Case
   if (root == NULL)
      return 0;

   if (root->key < L)        
       return getSum(root->right, L, H);

  if (root->key > H)
      return getSum(root->left, L, H)

   if (root->key >= L && root->key <=H)        
      return getSum(root->left, L, H) + root->key +
             getSum(root->right, L, H);

it will be O(logn +m)

it can go max of logn depth to find nodes in range and  function calls for nodes in range ie m

Note that the code first traverses across height to find the node which lies in range. Once such a node is found, it recurs for left and right children. Two recursive calls are made only if the node is in range. So for every node that is in range, we make at most one extra call (here extra call means calling for a node that is not in range).


Thanks for valuable effort.
So in worst case 'm' can equal to 'n', right?
11 votes
Do tree traversal from root as follows: Do a recursive search to find L, saving all the nodes visited in a stack. Since tree is balanced BST, it'll take O(log n) time. After finding L instead of search do inorder traversal up to m nodes from this node and continuing (if needed) using the saved nodes during searching. Complexity O(m).

Total time = O(m) + O(log n)

a=0, b=1, c=1, d=0
a+10b+100c+1000d = 0+ 10 + 100 + 0
= 110
how the inorder traversal will take o(m) it should take o(n) for n nodes
how are u going to decide that whether m is greater or logn is greater??which one is the dominating factor??

in O(logn) we can find the either L and H, so in inorder sorted list then we can get the m middle elements and their sum in o(m) steps by simple traversal in the list.

but the why isn't the O(n) time for making the inorder traversal being considered in above answer that is to be added, so then the whole answer will change.

the better approach seems to be O(mlogn) by simple search of m elements on AVL, then a=0, b=0, c=1 & d=1

and that computes 1100 as the answer

"saving all the nodes visited in a stack."

Why stack is required [email protected] Sir

Cant we do simply like find L in logn time then Visit m elements in inorder until we reach H in O(m) time.??

sir, I have the same confusion. Have you got it now? Why is stack required here?

Just in case you read this, can this problem be solved by just finding L $[O(logn)\ time]$, then performing an inorder traversal for m+1 numbers $[O(m)\ time]$; then adding them up $[O(1)\ time]$

My point is, can it be solved simply like that, or am I missing something?


@JashanArora adding to your points, I think your approach is valid we just need to make sure that the values < L in inorder traversal must be dropped. Finally according to me we can solve it without using stack in the following way:


1. First find the value of L.


2. Now

IF  L has right node then initialise sum = L  ELSE sum = 0.


3. Now

IF  if L has right node do inoder traversal starting from the L's right node and keep on incrementing sum (making sure visited node values are >=  L if not then ignore those values ) with visited node value until we reach H. 


ELSE L itself is the right node so start inorder traversal from L itself and keep on incrementing sum ( again making sure visited node values are >=  L if not then ignore those values ) with visited node value until we reach H.


4. finally sum value is our answer.


@DigvijayPandey sir, @Arjun sir or anyone please correct me if I am wrong.

3 votes
within those m numbers, we have to search m times to see if the numbers are existing in the Balanced BST & add them.

so, m log n time.

c = 1, d = 1 => answer = 0 + 0 + 100 + 1000 = 1100
out of n elements u r checking for exactly m elements.. but it may b possible m-k elements satisfy condition(less than H greater than L).. For rest K elements again u have to do same thing.. that ll take O(n) time..

   U r saying "it may b possible m-k elements satisfy condition(less than H greater than L).. For rest K elements again u have to do same thing.. that ll take O(n) time.."

But in the question  it is clearly mentioned  that there are  'm' such numbers. So how will it be m-k . ?

Can u  please explain it.
0 votes

We can firstly do inorder traversal of this Balanced BST which will result in sorted list of elements. It will take O(n).

No we can perform binary search on this sorted list to find L and H. It will take O(logn).

After finding L and H. We will run a loop to sum all elements between L and H. As there are m elements between L and H. So it will take O(m).

So total =O(n)+O(logn)+O(m) {As m<=n and O(n+logn)>=O(n)}

Hence we get O(n)

So a=1,b=0,c=0,d=0

So a+10b+100c+1000d =1+0+0+0=1

I am getting confuse whether I am thinking right or wrong So Please help...

edited by
O(n) is right , but the question asked is for the tightest upper bound .

Related questions

36 votes
5 answers
Consider the pseudocode given below. The function $DoSomething()$ takes as argument a pointer to the root of an arbitrary tree represented by the $leftMostChild-rightSibling$ representation. Each node of the tree is of type $treeNode$. typedef struct treeNode* treeptr; struct ... tree. height of the tree. number of nodes without a right sibling in the tree. number of leaf nodes in the tree
asked Sep 28, 2014 in DS jothee 7.7k views
28 votes
3 answers
Consider a hash table with $100$ slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what is the probability that the first $3$ slots are unfilled after the first $3$ insertions? $(97 \times 97 \times 97) / 100^3$ $(99 \times 98 \times 97) / 100^3$ $(97 \times 96 \times 95) / 100^3$ $(97 \times 96 \times 95 / (3! \times 100^3)$
asked Sep 28, 2014 in DS jothee 7.4k views
4 votes
1 answer
I don't seem to get the difference in both the questions. Finding L (or a) will take O(log n) comparisons which is fine. But now to search all elements between L and H (or a and b), weather it will take O(log n) time or constant time ? In the GATE question it ... the TIFR question, it is unclear. So how much time does it take ro search all elements between L and H (or a and b). ? Kindly explain.
asked Oct 26, 2017 in DS rishi71662data4 264 views
49 votes
4 answers
There are two elements $x,\:y$ in a group $(G,*)$ such that every element in the group can be written as a product of some number of $x$'s and $y$'s in some order. It is known that $x*x=y*y=x*y*x*y=y*x*y*x=e$ where $e$ is the identity element. The maximum number of elements in such a group is ____.
asked Sep 28, 2014 in Set Theory & Algebra jothee 6.3k views