How can we modify almost any algorithm to have a good best-case running time?

The ways we can modify the algorithm to have a best case running time are:

  • If the algorithm is at the point of its purpose/solution , For ex, for an increasing sort , it is already ascending order sorted and so on .
  • If we modify the algorithm such that we output and exit for its purpose only hence forcing multiple nested loops to be just one

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).


If we could introduce an instruction for that very algorithm in the computation model of the system itself, we can just solve the problem in one instruction.

But as you might have already discovered that it is a highly unrealistic approach. Thus a generic method to modify any algorithm to have a best case running time is next to impossible. What we can do at max is to apply tweaks in the algorithm for general redundancies found in various problems.

Or you can go naive by taking the best case inputs. But again that isn't actually modifying the algorithm. In fact, introducing the algorithm in the computation system itself, instead of being highly unrealistic, isn't a modification in the algorithm either.

Tags:

Algorithm