Introduction
Imagine you want to know how long a task will take as the size of the input grows. Understanding common complexity classes helps predict how efficient an algorithm is and how it will perform with larger data.
Imagine sorting a deck of cards. If you pick one card without looking, it takes the same time no matter how many cards there are. If you look at each card once, time grows with the number of cards. If you split the deck in half repeatedly to find a card, it takes fewer steps. But if you compare every card to every other card, it takes much longer as the deck grows.
Input Size (n) →
O(1) ──────────────■─────────────
O(log n) ─────■─────■────■────■────
O(n) ■────■────■────■────■────■──
O(n²) ■■■■■■■■■■■■■■■■■■■■■■■■■■■■def constant_time_example(lst): return lst[0] def linear_time_example(lst): total = 0 for item in lst: total += item return total def logarithmic_time_example(lst, target): low, high = 0, len(lst) - 1 while low <= high: mid = (low + high) // 2 if lst[mid] == target: return mid elif lst[mid] < target: low = mid + 1 else: high = mid - 1 return -1 def quadratic_time_example(lst): pairs = [] for i in range(len(lst)): for j in range(len(lst)): pairs.append((lst[i], lst[j])) return pairs # Example usage print(constant_time_example([10, 20, 30])) print(linear_time_example([1, 2, 3])) print(logarithmic_time_example([1, 2, 3, 4, 5], 4)) print(len(quadratic_time_example([1, 2, 3])))