Complexity Questions in ML Coding
Analyzing Big-O time and space complexity for machine learning algorithms, matrix operations, and data structures.
Why Big-O Complexity Matters in ML Interviews
In machine learning coding interviews, writing working code is only half the requirement.
You must state the Time Complexity (Operations) and Space Complexity (RAM / VRAM Memory) of your algorithms in terms of key problem dimensions:
- : Number of samples.
- : Number of features or embedding dimensions.
- : Sequence length.
- : Number of clusters or neighbors.
┌─────────────────────────────────────────────────────────────┐
│ TIME COMPLEXITY: Total scalar operations required. │
│ SPACE COMPLEXITY: Peak memory bytes allocated in RAM/VRAM. │
└─────────────────────────────────────────────────────────────┘
Essential ML Complexity Cheatsheet
┌──────────────────────────┬──────────────────────────┬──────────────────────────┐
│ ALGORITHM │ TIME COMPLEXITY │ SPACE COMPLEXITY │
├──────────────────────────┼──────────────────────────┼──────────────────────────┤
│ Matrix Multiply (N,M)x(M,P)│ O(N * M * P) │ O(N * P) │
│ Linear Regression Fit │ O(N * D + D^3) │ O(N * D + D^2) │
│ k-Means Iteration (K,N,D)│ O(N * K * D) per iter │ O(N * D + K * D) │
│ Decision Tree Training │ O(N * D * log N) │ O(Nodes + Depth) │
│ Brute-Force k-NN Query │ O(Q * N * D) │ O(Q * N) │
│ Self-Attention (T, d) │ O(T^2 * d) │ O(T^2 + T * d) │
└──────────────────────────┴──────────────────────────┴──────────────────────────┘
Worked Examples Explained
1. Matrix Multiplication:
To compute each entry in the output matrix of shape , we perform multiplications. There are entries, so total time is .
2. Normal Equation Linear Regression:
- multiplication: time.
- Inverting matrix: time.
- Total time: . Explodes when feature dimension !
3. Self-Attention Mechanism:
- where : Matrix multiplication produces a similarity matrix taking time.
- Storing the attention weight matrix takes memory, creating the quadratic sequence length bottleneck!
Say this out loud
Big-O complexity analysis quantifies scalability for machine learning algorithms. Matrix multiplication takes O(N M P) time. Normal equation linear regression scales cubic O(D^3) with feature dimensions. Self attention requires O(T^2 d) time and O(T^2) memory, creating quadratic sequence length bottlenecks.
Followups to expect
- What is the time complexity of sorting vs argpartition in NumPy? Full sorting (
np.argsort) takes time. Partial sorting (np.argpartition) extracts top smallest elements in linear average time. - How does Strassen's Algorithm improve matrix multiplication complexity? Strassen's algorithm reduces matrix multiplication complexity from down to approximately using sub-matrix block decompositions.
Check yourself
What is the Big-O time complexity of multiplying two matrices A of shape (N, M) and B of shape (M, P)?