</>
Skip to content
DSA lessons (4/55)

DSA — Complexity

What is Complexity?

Complexity measures how an algorithm's resource usage grows with input size.

Time Complexity

How execution time grows with input size.

# O(1) - Constant
def get_first(arr):
    return arr[0]

# O(n) - Linear
def find_element(arr, target):
    for item in arr:
        if item == target:
            return True
    return False

# O(n²) - Quadratic
def bubble_sort(arr):
    for i in range(len(arr)):
        for j in range(len(arr) - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

Space Complexity

How memory usage grows with input size.

# O(1) space
def sum_array(arr):
    total = 0
    for num in arr:
        total += num
    return total

# O(n) space
def create_copy(arr):
    return arr.copy()

Common Complexities

ComplexityNameExample
O(1)ConstantArray access
O(log n)LogarithmicBinary search
O(n)LinearLinear search
O(n log n)LinearithmicMerge sort
O(n²)QuadraticBubble sort
O(2^n)ExponentialFibonacci (naive)

Mini Practice

  1. Analyze time complexity of functions
  2. Identify space complexity
  3. Compare different algorithms
  4. Optimize inefficient code

Up Next

Continue with Big O — Big O notation.

Related Topics

Frequently Asked Questions about Complexity

What is Complexity in DSA?

Complexity 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 Complexity?

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 Complexity.

Why is Complexity important in DSA?

Complexity is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.