How to Choose an Algorithm to Solve a Problem
The same problem can be solved using different algorithms, but which one is the best? There are two metrics for evaluating an algorithm:
- Time complexity (time consumed)
- Space complexity (memory consumed)
Generally, the less time and memory an algorithm uses, the better it is. Time complexity analysis can be further broken down into three cases:
- Best case: Considers the
minimumnumber of steps the algorithm needs to execute. - Worst case: Considers the
maximumnumber of steps the algorithm needs to execute. - Average case: Considers the
averagenumber of steps the algorithm needs to execute.
Big O Notation as a Measurement Standard
Typically, we focus on finding the worst case, and we usually use Big O notation — a method for evaluating algorithm efficiency that represents execution speed and typically indicates the worst-case execution time.
So how do we express it?
- O(n): Assuming n is the number of elements, if each element is visited once, we write it as O(n).
- O(n^2): If a nested loop visits every element once, it’s O(n^2).
- O(log n): Like binary search, we only need to visit elements log2(n) times, so it’s written as O(log n).
Note: “log” stands for “logarithmic.”
As shown in the chart above, good algorithms don’t grow exponentially as the number of elements increases. As developers, Big O Notation serves as a tool for measuring code efficiency, and we should aim to minimize unnecessary steps whenever possible.
Resources:
Feel free to leave a comment on my blog. Your feedback motivates me to keep writing. Thank you for reading, and let’s grow together to become better versions of ourselves.