What Is an Algorithm

What an algorithm is, how to trace one by hand, test it on edge cases and turn it into code, and what interviewers ask about the basics.

12 minLesson 1 of 5
On this page
  1. How an algorithm works
  2. What makes a list of steps an algorithm
  3. Tracing an algorithm by hand
  4. The algorithm in code
  5. Cost of finding the highest score
  6. Testing with edge cases
  7. Different algorithms for the same problem
  8. Pitfalls
  9. In the interview
  10. Check yourself
  11. What to practise next

An algorithm is a finite list of exact steps that turns an input into the correct output. It is used to solve a problem in a way that works for every valid input, not just the one you are looking at, and that a computer can follow without any judgment. You reach for one whenever a task is too large to do by eye or has to be repeated by a program.

Without an exact method, "find the winner" depends on whoever is looking at the scores. A person can glance at five numbers and answer, but nobody can glance at 3,000, and a computer has nothing to glance with. The steps have to be written down first.

How an algorithm works

Take the problem of finding the highest score in a list. A method that works for any list keeps one number, the best score seen so far, and compares every other score to it:

  1. Look at the first score and remember it as the best so far.
  2. Look at the next score. If it is bigger than the best so far, it becomes the new best so far. Otherwise, ignore it.
  3. Repeat step 2 until there are no scores left.
  4. The best so far is the answer.

This works for 5 scores or 5 million, and anyone who follows it gets the same answer.

Input 4 9 2 11 6 Steps keep the best so far Output 11
An algorithm takes an input, applies a fixed list of steps to it, and produces an output.

What makes a list of steps an algorithm

A recipe is close, but it says things like "bake until golden" or "add a pinch of salt", which a person can judge and a computer cannot. An algorithm has four properties that a recipe does not guarantee.

It has a clear input and a clear output. Here the input is a list of scores and the output is the highest one. Every step is exact, which means each question has a yes or no answer: "is this score bigger than the best so far" qualifies, and "pick the biggest-looking one" does not. It finishes, because each repeat of step 2 uses up one score, so the method always reaches step 4. And it is correct for every valid input, which is the property that people forget to check.

Tracing an algorithm by hand

Before writing code, run the steps yourself on a small input and write down what each variable holds after every step. The trace below does this for the scores 4, 9, 2, 11 and 6.

Find the highest scoreUse the arrows or ← → keys
if there are no scores: there is no winnerbest = the first scorefor each later score s:  if s > best:    best = sanswer: best
  1. scores
    04
    19
    22
    311
    46
    best
    4
    comparisons
    0

    1The method starts by taking the first score, 4, as the best so far.

  2. scores
    04
    19s
    22
    311
    46
    best
    4
    comparisons
    1

    2The next score is 9, and 9 is bigger than 4.

  3. scores
    04
    19s
    22
    311
    46
    best
    9
    comparisons
    1

    3So 9 becomes the best so far, and 4 can no longer win.

  4. scores
    04
    19
    22s
    311
    46
    best
    9
    comparisons
    2

    4The next score is 2, which is not bigger than 9, so nothing changes.

  5. scores
    04
    19
    22
    311s
    46
    best
    9
    comparisons
    3

    5The next score is 11, and 11 is bigger than 9.

  6. scores
    04
    19
    22
    311s
    46
    best
    11
    comparisons
    3

    6So 11 becomes the best so far.

  7. scores
    04
    19
    22
    311
    46s
    best
    11
    comparisons
    4

    7The last score is 6, which is not bigger than 11, so nothing changes.

  8. scores
    04
    19
    22
    311
    46
    best
    11
    comparisons
    4

    8There are no scores left, so the answer is 11. It took 4 comparisons, one for each score after the first.

1 / 8

The trace shows why the method is correct. After each step, best is the highest score seen so far. That is true after the first score, and each comparison keeps it true, so after the last score best is the highest of all. Stating a fact like this, which holds after every step, is how you argue that an algorithm works on inputs you never tried.

The algorithm in code

Each line of the code matches one line of the plain-English version.

function highestScore(scores) {
  if (scores.length === 0) return null; // no scores, no winner
  let best = scores[0];                 // the first score is the best so far
  for (let i = 1; i < scores.length; i++) {
    if (scores[i] > best) {
      best = scores[i];                 // found a new best
    }
  }
  return best;
}
 
highestScore([4, 9, 2, 11, 6]); // 11
def highest_score(scores):
    if not scores:
        return None  # no scores, no winner
    best = scores[0]  # the first score is the best so far
    for i in range(1, len(scores)):
        if scores[i] > best:
            best = scores[i]  # found a new best
    return best
 
highest_score([4, 9, 2, 11, 6])  # 11

Both languages have this built in (Math.max(...scores) in JavaScript and max(scores) in Python). The built-in does the same walk over the list, so it costs the same.

Cost of finding the highest score

With n scores the method makes n − 1 comparisons, so doubling the number of scores doubles the work. No algorithm can do better on an unsorted list, because any score that is skipped might be the highest.

TimeO(n)
SpaceO(1)

The method looks at each score once and remembers only the number best.

For now, read O(n) as "the work grows in step with the number of items". The next lesson explains Big-O notation properly.

Testing with edge cases

One passing example proves little, so test the inputs most likely to break the method. These all work with the code above:

  • The highest score is first, as in [11, 4, 9]. best starts at 11 and never changes.
  • The highest score is last, as in [4, 9, 11]. best changes on the final comparison.
  • A tie, as in [9, 11, 11]. The second 11 is not bigger than the first, so best stays 11.
  • A single score, as in [7]. The loop never runs and the answer is 7.
  • All scores negative, as in [-3, -1, -7]. best starts at −3 and becomes −1.
  • An empty list, []. There is no first score to start from, so the first line returns null (None in Python) so the code states its answer for that case instead of failing.

Inputs like these are called edge cases. Choosing them before you run the code is part of designing the algorithm.

Different algorithms for the same problem

A problem can have several correct algorithms that do very different amounts of work. To find "Okafor" in an alphabetical list of 1,000,000 names, you can check every name from the top, which takes up to 1,000,000 looks. Or you can look at the middle name, decide whether "Okafor" comes before or after it, and discard the half that cannot contain it. Repeating that halving takes about 20 looks.

The halving method is binary search, and it works only because the list is sorted. An unsorted list of scores has no such shortcut, which is why the highest-score method above has to look at every item. Choosing between algorithms by what the input guarantees is most of what the rest of this course covers.

Pitfalls

In the interview

You will rarely be asked what an algorithm is. This lesson matters because every interview problem expects you to do the same four things: state the input and output, work a small example by hand, write the steps, and test edge cases. Interviewers watch for these habits at least as closely as for the final code.

Questions to expect on a problem like this one:

  • "What is the input, and what should you return for an empty one?" Ask this yourself before you are asked. For the highest score, the input is a list of numbers, and an empty list has no highest score, so the method returns null or raises an error. Agree on the choice with the interviewer instead of assuming it.
  • "Walk me through an example." Pick an input of four or five items, run your steps on it and say what each variable holds after every step. This is the same thing the tracer above does, and it often exposes a bug before you write any code.
  • "How do you know it is correct?" State a fact that stays true after every step, such as "best is the highest score seen so far", and explain that the last step makes it true for the whole list. Then mention the edge cases you tested.
  • "What is its time and space complexity?" The time is O(n) because each item is looked at once, and the space is O(1) because only best and the loop index are stored. Say why, not only the result.
  • "Can you do better?" For an unsorted list the answer is no, because every item has to be read at least once. If the list is sorted in ascending order, the highest score is simply the last item, which takes O(1). Asking whether the input is sorted before you start is a good habit for the same reason.

Check yourself

Quick check

Which of these instructions could not be a step in an algorithm?

You run the highest-score steps on [5, 8, 8, 3]. How many times does best change after it is first set?

A friend's version sets best = 0 before the loop instead of using the first score. On which input does it give the wrong answer?

What to practise next

Big-O Notation shows how to compare algorithms by counting their steps, and How to Approach a Problem turns the habits above into a routine for interviews.