AP Computer Science Principles · Study guide

Algorithmic Efficiency

AP® Computer Science Principles · Big Idea 3 · Algorithms and Programming

Algorithmic Efficiency

How to tell whether an algorithm runs in a reasonable amount of time, how to count the work an algorithm does, and when a good-enough answer is the right choice.

1Problems and instances

A problem is a general description of a task that can (or cannot) be solved with an algorithm. An instance of a problem also includes a specific input. Sorting is a problem; sorting the list (2, 3, 1, 7) is an instance of it.

Kind of problemWhat it asksExample
Decision problema yes or no questionIs there a road path from the school to the stadium?
Optimization problemfind the best answer among many possible onesWhat is the shortest road path from the school to the stadium?

2What efficiency measures

Efficiency is an estimate of how much computing work (time, memory) an algorithm uses. It is described as a function of the size of the input: how the work grows as the list gets longer or the number gets bigger. A program that is quick on 10 items may be hopeless on 10 million.

Efficiency can be worked out by careful mathematical reasoning, or measured informally by counting how many times a statement, or group of statements, runs.

3Counting the work

Here are three algorithms that work on a list called nums. Each has a counter, checks, added just to count how often the main comparison runs. The first finds the largest value:

checks ← 0
best ← nums[1]
FOR EACH item IN nums
{
  checks ← checks + 1
  IF (item > best)
  {
    best ← item
  }
}
DISPLAY(checks)

The next two answer the same question (does any value appear twice?) in different ways. The first compares every item with every other item:

checks ← 0
found ← false
i ← 1
REPEAT LENGTH(nums) TIMES
{
  j ← 1
  REPEAT LENGTH(nums) TIMES
  {
    IF (i ≠ j)
    {
      checks ← checks + 1
      IF (nums[i] = nums[j])
      {
        found ← true
      }
    }
    j ← j + 1
  }
  i ← i + 1
}
DISPLAY(checks)

The second notices that comparing item 2 with item 5 is the same as comparing item 5 with item 2, so it checks each pair only once:

checks ← 0
found ← false
i ← 1
REPEAT LENGTH(nums) - 1 TIMES
{
  j ← i + 1
  REPEAT LENGTH(nums) - i TIMES
  {
    checks ← checks + 1
    IF (nums[i] = nums[j])
    {
      found ← true
    }
    j ← j + 1
  }
  i ← i + 1
}
DISPLAY(checks)

Running all three on lists with no repeated values (so no algorithm can stop early) gives:

List lengthLargest valueEvery pair, both waysEvery pair once
10109045
2020380190
40401,560780

Doubling the list doubles the work for the largest-value loop (linear growth) and roughly quadruples it for both duplicate checkers (a loop inside a loop, so about n × n: square growth). The two duplicate checkers are both correct, but one does half the work. Different correct algorithms for the same problem can have different efficiencies.

4Reasonable and unreasonable time

Algorithms whose work grows like a polynomial or slower (constant, linear, square, cube, and so on) are said to run in a reasonable amount of time. Algorithms whose work grows exponentially (doubling with each extra item, like 2ⁿ) or factorially (n × (n − 1) × … × 1, written n!) are examples of algorithms that run in an unreasonable amount of time.

Figure 1. Linear and square growth stay on the chart. Exponential growth starts small but runs off the top before n reaches 10.

At a billion steps per second, here is how long each kind of growth takes:

Growthn = 10n = 20n = 50n = 100
constantunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a second
linearunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a second
squareunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a second
cubeunder a thousandth of a secondunder a thousandth of a secondunder a thousandth of a secondabout a thousandth of a second
exponentialunder a thousandth of a secondabout a thousandth of a second13 daysa 14-digit number of years
factorial4 thousandths of a second77 yearsa 48-digit number of yearsa 142-digit number of years

Every polynomial row stays under a second even at n = 100. The exponential row jumps from a blink to 13 days at n = 50 and a 14-digit number of years at n = 100, and the factorial row is worse: just 20 items take about 77 years. A faster computer barely helps; doubling the speed only halves those times.

The key idea

Efficiency estimates how an algorithm's work grows with the size of its input, and you can measure it by counting how many times statements run. Polynomial growth (constant, linear, square, cube) is reasonable; exponential and factorial growth is unreasonable. Different correct algorithms for the same problem can differ in efficiency.

5When good enough is the answer

Some problems cannot be solved in a reasonable amount of time because no efficient algorithm is known for them. A delivery driver who must visit every stop and come back by the shortest route is facing one. With 6 stops there are 720 possible orders, few enough to check every one. With 50 stops there are 50! orders, a 65-digit number. No computer can check them all.

In cases like this, people look for approximate solutions. A heuristic is an approach that produces a solution that is not guaranteed to be the best, used when methods that always find the best solution are impractical. A common one for the driver: always go to the nearest stop you haven't visited yet.

Figure 2. The nearest-stop rule is fast and usually decent, but here it leaves E for last, far from the start, and drives 18% farther than the best route.

For these 6 stops, checking all 720 orders finds a 30.1-mile route. The nearest-stop rule needs only 21 distance comparisons and finds a 35.5-mile route: 18% longer, but found instantly, and the same rule still works for 50 or 5,000 stops when checking every order is impossible. That trade (give up the guarantee of the best answer to get a good answer at all) is what makes a heuristic appropriate.

6Worked examples

Worked Example 1 Count the work

A loop inside a loop

An algorithm has a loop that runs once for each of the n items in a list, and inside it another loop that also runs n times. About how many times does the inner statement run for a list of 1,000 items? Is that reasonable?

  1. 1
    For each of the 1,000 passes of the outer loop, the inner statement runs 1,000 times.
  2. 2
    1,000 × 1,000 = 1,000,000 runs.
  3. 3
    That is square growth, a polynomial, so it runs in a reasonable amount of time.
Answer: About 1,000,000 times; reasonable.
Worked Example 2 Classify the problem

Decision or optimization?

Classify each: (a) Does this list contain the number 42? (b) What is the cheapest set of flights from Boston to Denver? (c) Is the password at least 8 characters long?

  1. 1
    (a) and (c) have yes or no answers.
  2. 2
    (b) asks for the best answer among many possibilities.
Answer: (a) decision, (b) optimization, (c) decision.
Worked Example 3 Reasonable or not?

Trying every combination

A program finds which songs to put on a playlist by trying every possible group of the n songs. Each song is either in or out, so there are 2ⁿ groups. Is this reasonable for 60 songs?

  1. 1
    2ⁿ is exponential growth.
  2. 2
    2⁶⁰ is about 1.2 × 10¹⁸ groups; at a billion per second that is 37 years.
Answer: No. Exponential growth is unreasonable; a heuristic (for example, adding songs one at a time by rating) would be appropriate.
Worked Example 4 Judge a heuristic

Is the answer the best one?

A map app uses a heuristic to plan a 40-stop delivery route. A driver says, “The computer planned it, so it must be the shortest route.” Is that right?

  1. 1
    A heuristic produces a solution that is not guaranteed to be optimal.
  2. 2
    It was chosen because checking every one of the 40! orders is impractical.
Answer: No. The route is likely good, but it is not guaranteed to be the shortest.

7Common mistakes

Common Mistake 1 · Judging efficiency from one input

Efficiency is about how the work grows as the input grows, not how long one run took. Compare the counts as the input gets bigger.

Common Mistake 2 · Calling square or cube growth unreasonable

n × n can be a lot of work, but it is still a polynomial, so it counts as reasonable. Only exponential and factorial growth are the unreasonable examples.

Common Mistake 3 · Expecting a heuristic to be optimal

A heuristic gives up the guarantee of the best answer in exchange for an answer in reasonable time.

Common Mistake 4 · Thinking a faster computer fixes exponential growth

Doubling the computer's speed handles just one more item when the work doubles with each item.

Explain efficiency like this

“Checking every possible order of the stops takes factorial time, which is unreasonable once there are more than a handful of stops. The nearest-stop heuristic runs in reasonable time and gives a route that is not guaranteed to be the shortest, which is acceptable because finding the best route is impractical.”

Name how the work grows, say whether that is reasonable, and if you suggest a heuristic, say what it gives up.