Skip to content
Advertisement

Get Minimum and maximum numbers from a list

Assuming we have a list containing integers and we need to find min & max. What is the best way to do it ? I can think of following :

  1. If number of reads are much higher than writes; keep the list in sorted manner. Whenever a number is added; add it in sorted manner. Now to get min and max we can just get first and last element of this list.

  2. If number of writes are higher than reads; iterate on the list and return result. But this is O(n) which looks to be expensive.

Is there any other better way ?

Advertisement

Answer

Assuming you can observe any mutation to the list, you could store (cache) the min and max values and possibly update the cached values when a number is added / removed. At this point, the order of the list doens’t matter.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement