Core Module
12 min forge

Time Complexity

Learn how to measure the efficiency of your algorithms and why it matters in high-scale engineering.

⏳ Time Complexity: Measuring Speed

In the world of high-scale engineering, "working code" isn't enough. It must be efficient. Time complexity helps us predict how an algorithm's runtime grows as the input size ($n$) increases.

πŸ’‘ The Logic (ELI5)

Imagine you're looking for a specific toy in a box:

  • O(1): You know exactly where it is. You grab it instantly, regardless of how many toys are in the box.
  • O(n): You have to look at every single toy in the box until you find yours. If the box doubles in size, it takes twice as long.
  • O(log n): You have a sorted pile. You look at the middle, discard half, and repeat. You find it very fast even in huge piles.

πŸ” The Deep Dive

Big O Notation

Big O notation provides an upper bound on the time requirements of an algorithm. It focuses on the worst-case scenario.

ComplexityNameExample
O(1)ConstantAccessing an array element by index
O(log n)LogarithmicBinary Search
O(n)LinearSingle loop through an array
O(n log n)LinearithmicMerge Sort, Quick Sort
O(nΒ²)QuadraticNested loops (Bubble Sort)
O(2ⁿ)ExponentialRecursive Fibonacci
O(n!)FactorialGenerating all permutations

Why Drop Constants?

We care about the growth rate. $O(2n)$ and $O(100n)$ both grow linearly. As $n$ approaches infinity, the constant factor becomes insignificant compared to the impact of $n$.


πŸ› οΈ Code Forge: Complexity Examples

javascript Standard
/** * O(1) - Constant Time * It doesn't matter if the array has 10 or 1 million items. */ function getFirstItem(items) { return items[0]; // One operation } /** * O(n) - Linear Time * The runtime grows directly with the size of the array. */ function findItem(items, target) { for (let item of items) { if (item === target) return true; } return false; } /** * O(nΒ²) - Quadratic Time * Common in "Brute Force" solutions involving nested loops. */ function hasDuplicate(items) { for (let i = 0; i < items.length; i++) { for (let j = i + 1; j < items.length; j++) { if (items[i] === items[j]) return true; } } return false; }

🎯 Interview Pulse

Common Patterns

  1. Halving the search space: Usually indicates O(log n).
  2. One loop: Usually O(n).
  3. Nested loops: Usually O(nΒ²).
  4. Dividing and then looping: Often indicates O(n log n).

Pro-Tip

Always start with the most intuitive (often O(nΒ²)) solution in an interview, then explain how you'll use a better data structure (like a HashMap) to bring it down to O(n).