Data Structures & Algorithms Big O & Complexity
💡
Exercise 2

Counting Operations 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

Now that you know what Big O is, let's learn how to count operations to figure out the time complexity of code. 🔍

💡 Think of it like this: Imagine you're counting how many steps it takes to walk somewhere. More steps = takes longer. In code, we count how many "steps" (operations) the computer needs to do.

# Example 1: O(1) — constant time (always 1 step) def get_first(arr): return arr[0] # Just one operation, no matter how big arr is! # Example 2: O(n) — linear time (steps grow with input size) def print_all(arr): for item in arr: # If arr has 100 items, this runs 100 times print(item) # n items → n steps # Example 3: O(n²) — quadratic time (steps grow MUCH faster) def print_pairs(arr): for i in arr: # n times for j in arr: # n times for EACH i print(i, j) # n × n = n² total steps!

How to count operations:

  • 🔢 Single operation (assignment, comparison, arithmetic) = O(1)
  • 🔄 One loop going through n items = O(n)
  • 🔄🔄 Nested loops (loop inside a loop) = O(n × n) = O(n²)
  • ✂️ Cutting in half each step (like binary search) = O(log n)
  • 📌 Drop constants and lower terms: O(2n + 5) → O(n), O(n² + n) → O(n²)

Quick comparison for n = 1,000:

  • O(1) → 1 step ⚡
  • O(log n) → ~10 steps 🏃
  • O(n) → 1,000 steps 🚶
  • O(n log n) → ~10,000 steps 🐢
  • O(n²) → 1,000,000 steps 🐌
  • O(2ⁿ) → more than atoms in the universe! 💀
📋 Instructions
Analyze the three functions below. For each, print its Big O complexity. The functions are already written — you just need to figure out their complexity and print the answers. ```python def func_a(n): for i in range(n): print(i) def func_b(n): for i in range(n): for j in range(n): print(i, j) def func_c(n): return n * 2 ``` Print the complexity for each: ``` func_a: O(n) func_b: O(?) func_c: O(?) ```
func_b has a nested loop (loop inside a loop). If each loop runs n times, the total is n × n. func_c does just one multiplication regardless of n — that's constant time.
🧪 Test Cases
Input
"func_a: O(n)"
Expected
func_a: O(n)
Test case 1
Input
"func_b: "
Expected
func_b: O(n^2)
Test case 2
Input
"func_c: "
Expected
func_c: O(1)
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.