Skip to main content

I thought I’d briefly share the analogy I use to easily understand complexities on the surface before deeply diving into the nitty-gritties of them!

Once Upon a Time (Complexity)…

Imagine you’re at a carnival/ park with rides, and each ride represents a different algorithm. Some rides are quick and thrilling the kind that make me dizzy, while others are slow and scenic. To decide which ride to go on, you need to understand how long each one takes and how much space it needs. Enter the point of this article: Time Complexity and Space Complexity!

Time Complexity

Time complexity is like the speed of a ride. It tells you how the time to complete a task grows as the size of the input (let’s call it n) increases. Here’s a quick rundown of the most common time complexities:

  • O(1) – Constant Time: Imagine a car. No matter how many people want to use it, it always takes the same amount of time.
  • O(log n) – Logarithmic Time: Think of trying to find a page in a book by opening it in the middle and discarding half the pages each time. Efficient! 📚
  • O(n log n) – Linearithmic Time: Imagine sorting a deck of cards by repeatedly splitting and merging them. It’s a bit more complex but still manageable. 🃏
  • O(n^2) – Quadratic Time: Think of a dance where everyone has to pair up with everyone else. The number of dances grows quadratically with the number of dancers. 💃🕺
  • O(2^n) – Exponential Time: Picture popping one kernel of popcorn in a pot but instead it doubles in number every minute. Soon, you’ll have an entire dish or two of popcorn. 🍿
  • O(n!) – Factorial Time: Imagine trying to arrange a group of friends in every possible order for a photo. The number of arrangements grows factorially. Say cheese! 📸

Space Complexity

Space complexity is like the amount of space a ride would need. It tells you how much memory and algorithm uses as the input size grows. Here are some common space complexities.

  • O(1) – Constant Space: A tiny suitcase that fits everything you need, no matter how much you pack. I wish I owned a suitcase like that. 💼
  • O(n) – Linear Space: A suitcase that grows with the number of items you pack. More items, bigger suitcase! Story of my life.
  • O(n^2) – Quadratic Space: A suitcase that needs to grow quadratically with the number of items. It’s like packing large dresses for a gala! 

Finally…

 

Understanding time and space complexities helps you choose the best ride for your needs. Whether you’re moving around with O(1) or dancing with O(n^2), Big O notation is your trusty guide to navigating the world of algorithms.

So, next time you encounter an algorithm, just remember it’s all about how fast it goes and how much space it needs. And with that, you’re ready to conquer the adventures of code!

More in depth resources on time and space complexities:

  1. GeeksforGeeks
  2. FreeCodeCamp
  3. Leetcode is my favorite resources for mastering algorithms