Programming

Python DSA & Interview Patterns Cheat Sheet

Quick reference for Python algorithms & data structures: Big-O of Python types, hash maps & prefix sums, two pointers & sliding window, monotonic stack, backtracking, bisect, linked lists, trees/BFS, heapq, topological sort, DP, LRU Cache, and Dijkstra.

1 min readUpdated 2026-11-30

Python Built-In Time Complexities

  • list: append/pop() = $O(1)$ · pop(0) / x in list = $O(n)$ · sort() = $O(n \log n)$
  • dict / set: lookup / insert / delete = $O(1)$ average
  • collections.deque: append / appendleft / pop / popleft = $O(1)$
  • heapq: heappush / heappop = $O(\log n)$ · peek heap[0] = $O(1)$

Sliding Window & Monotonic Stack

python
# Variable Sliding Window (O(n))
left = 0
for right, val in enumerate(arr):
    # expand window with val
    while window_invalid():
        # shrink window removing arr[left]
        left += 1

# Monotonic Decreasing Stack (Next Greater Element)
stack = []
for i, x in enumerate(nums):
    while stack and x > nums[stack[-1]]:
        prev = stack.pop()
        ans[prev] = x
    stack.append(i)
python
# Backtracking: Choose -> Explore -> Unchoose
def dfs(start):
    res.append(path.copy())
    for i in range(start, len(nums)):
        path.append(nums[i])
        dfs(i + 1)
        path.pop()

# Binary Search on sorted array
from bisect import bisect_left, bisect_right
idx = bisect_left(sorted_arr, target)

Tree BFS, Kahn's Topological Sort & Dijkstra

python
from collections import deque
import heapq

# Level-order BFS
q = deque([root])
while q:
    for _ in range(len(q)):
        node = q.popleft()
        if node.left: q.append(node.left)
        if node.right: q.append(node.right)

# Max-heap via heapq: negate priorities (-val)
# Dijkstra lazy-deletion check:
# if cost > dist[node]: continue

Dynamic Programming (@lru_cache vs Tabulation)

python
from functools import lru_cache

@lru_cache(maxsize=None)
def dp(state):
    if base_case:
        return 0
    return best_transition