Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Asymptotic Notation  ›  Lesson

Constant and Linear Time

Linear 12 minConstant-time work stays the same however large the input gets, while linear-time work grows in direct proportion to the input size.

Constant and Linear Time

Your code runs in 2 milliseconds on your laptop with 100 test records. Will it survive a customer with 10 million records? A stopwatch cannot tell you, because the answer depends on the machine. Computer scientists ask a better question: how does the work grow as the input grows? The two simplest answers are constant and linear.

The rule

Double the input and watch the work: unchanged is constant, doubled is linear.

Call the input size n: the number of items in a list, characters in a string, rows in a table.

  • Constant time, written O(1): the work does not depend on n. Reading a[5], adding two numbers, or checking whether a list is empty all take the same time for 10 items or 10 million.
  • Linear time, written O(n): the work grows in step with n. Summing a list, finding its largest value, or searching an unsorted list for a name all touch each item once.

We count steps, not seconds, and we ignore constant factors. A loop that does 3 small steps per item does 3n steps; that is still linear, because doubling n still doubles 3n. What matters is the shape of the growth, not the exact count.

The shortcut

Run the doubling test in your head: imagine the input twice as large and ask what happens to the work.

Classifying four small tasksStep 1 of 4
  1. Return the first item

    Twice as many items, still one read. The work is unchanged, so this is constant.

The trap is being fooled by a loop. A loop only makes code linear if the number of times it runs grows with n. A loop with a fixed count, like "the first 10 items", is constant.

Drills

Answer fast — trust the rule.

quick drill

What is the growth rate of reading the element at index 7 of an array?

quick drill

Finding the largest number in an unsorted list of n numbers is…

quick drill

A function loops over a list and does 4 steps for each item. What is its growth rate?

quick drill

A function always looks at the first 100 items of a list (or all of them if there are fewer). As lists get very long, its growth rate is…

Remember

  • Double the input: unchanged work is constant, doubled work is linear.
  • Count steps, not seconds, and drop constant factors: 5n is linear.
  • The trap: a loop with a fixed count is constant, not linear.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe doubling test

Take two tasks: (1) return the first item of a list, and (2) return the largest item of an unsorted list. Use the doubling test to classify each as constant or linear, and explain why a loop that does 3 steps per item is still linear.