Skip to content

Time Complexity

In one line

Time complexity describes how an algorithm's runtime grows as the input size increases, expressed in Big O notation.

In simple words

Time complexity is a way to describe how fast an algorithm slows down as you give it more data. If an algorithm takes 1 second for 100 items, how long does it take for 1000 items? 10000? Time complexity answers this.

Big O notation is the standard way to express time complexity:

  • O(1) — constant: same time regardless of input size (array access)
  • O(n) — linear: time grows proportionally with input (linear search)
  • O(n²) — quadratic: time grows with the square of input (bubble sort)
  • O(log n) — logarithmic: time grows very slowly (binary search)

Understanding time complexity helps you choose the right algorithm. For large datasets, the difference between O(n) and O(n²) is enormous: for 1 million items, O(n) does 1 million operations, but O(n²) does 1 trillion.

Example

javascript
// O(n) — linear search: checks each element once
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}

// O(log n) — binary search: halves the search space each step
function binarySearch(sorted, target) {
  let lo = 0, hi = sorted.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (sorted[mid] === target) return mid;
    if (sorted[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

Linear search is O(n) — worst case checks all n elements. Binary search is O(log n) — halves the search space each iteration, so for 1 million items it takes about 20 steps.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary