Estructuras de datos y algoritmos
1.3.2kata 2 de 5

Big-O y complejidad temporal

Cómo escalan los algoritmos: O(1), O(log n), O(n), O(n log n), O(n²), O(2^n)

Big-O describe cómo escala el tiempo/espacio con el tamaño de entrada. O(1) es constante (acceso directo), O(log n) es logarítmico (búsqueda binaria), O(n) es lineal (recorrer una lista), O(n log n) es linearitmo (sort eficiente), O(n²) es cuadrático (bucles anidados), O(2^n) es exponencial (recursión sin memoización). Para datos de 1 millón, la diferencia entre O(n) y O(n²) es millones vs. trillones de operaciones.

Entender Big-O es crítico en ML: un algoritmo O(n²) en un dataset de 1M filas es inviable. O(n) o O(n log n) es manejable. La regla: prefiere complejidad baja incluso si el código es más complejo.

structure.txt
# O(1) — constant time
def get_first(arr):
    return arr[0]

# O(log n) — binary search on sorted
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 scan
def find_max(arr):
    return max(arr)

# O(n log n) — efficient sort
sorted_arr = sorted(arr)  # uses Timsort

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

Debugging lab

Detecta y corrige el error en el código.

0/1 tests passing0%
  1. 01

    # Check if all pairs sum to target for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[i] + arr[j] == target: return True # O(n²) brute force