DSA — Big O Notation
What is Big O?
Big O notation describes the upper bound of an algorithm's growth rate.
Big O Examples
# O(1) - Constant Time
def get_value(arr, index):
return arr[index]
# O(log n) - Logarithmic
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# O(n) - Linear
def linear_search(arr, target):
for i, val in enumerate(arr):
if val == target:
return i
return -1
# O(n²) - Quadratic
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
Growth Rate Comparison
| n | O(1) | O(log n) | O(n) | O(n log n) | O(n²) |
|---|---|---|---|---|---|
| 1 | 1 | 0 | 1 | 0 | 1 |
| 10 | 1 | 3 | 10 | 33 | 100 |
| 100 | 1 | 7 | 100 | 664 | 10,000 |
| 1000 | 1 | 10 | 1000 | 9966 | 1,000,000 |
Rules for Big O
- Drop constants: O(2n) → O(n)
- Drop lower-order terms: O(n² + n) → O(n²)
- Different inputs = different variables
Mini Practice
- Determine Big O of simple functions
- Analyze nested loops
- Compare algorithm efficiencies
- Optimize for better Big O
Up Next
Continue with Recursion — recursive problem solving.
Related Topics
Frequently Asked Questions about Big O Notation
What is Big O Notation in DSA?
Big O Notation is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Big O Notation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Big O Notation.
Why is Big O Notation important in DSA?
Big O Notation is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.