You can modify any algorithm to have a best case time complexity of O(n)
by adding a special case, that if the input matches this special case – return a cached hard coded answer (or some other easily obtained answer).
For example, for any sort, you can make best case O(n)
by checking if the array is already sorted – and if it is, return it as it is.
Note it does not impact average or worst cases (assuming they are not better then O(n)
), and you basically improve the algorithm’s best case time complexity.
Note: If the size of the input is bounded, the same optimization makes the best case O(1)
, because reading the input in this case is O(1)
.