Article

Algorithms and Complexity

Analyze time and space complexity by comparing linear and binary search.

6 min read2026-12-02beginnerBy m7mdbook
On this page

Algorithms and Complexity

An algorithm is a sequence of steps for solving a problem. Complexity describes how the time or extra memory required by those steps grows as the input gets larger.

Read Big O as an upper bound

Suppose an algorithm examines every element in an array of length n once. Its running time is O(n) under the assumption that each visit takes constant time. Big O describes an upper bound on growth. It does not predict how many milliseconds a particular machine will take. Worst-case, average-case, and best-case running times are separate quantities and can each have their own bound.

Linear search checks items in order until it finds the target or exhausts the array. Its worst-case time is O(n), and it works on unsorted inputs. Binary search needs a sorted array. Each comparison discards roughly half of the remaining candidates, giving O(log n) worst-case time.

typescript
function binarySearch(values: readonly number[], target: number): number {
  let low = 0;
  let high = values.length - 1;

  while (low <= high) {
    const middle = low + Math.floor((high - low) / 2);
    const value = values[middle];

    if (value === target) return middle;
    if (value < target) low = middle + 1;
    else high = middle - 1;
  }

  return -1;
}

The search returns a matching index or -1 when the target is absent. If a value occurs more than once, the function can return any matching index.

Count extra memory as well as time

The iterative search uses a fixed number of variables, so its auxiliary space is O(1). That figure excludes the input array. If you copy or sort an unsorted input first, count the cost of that preparation separately. For a single lookup in an unsorted array, a linear scan avoids that preparation. A sorted array can make binary search worthwhile when you run many lookups.

Test the boundaries

Try searching for 8 in [2, 4, 8, 16], then look for 3. Also test an empty array and a one-element array. For duplicate values, assert that the returned index points to the target unless your contract specifically promises the first match.