Measuring efficiency

Fast and light on memory · Part of Complexity and data

Key idea

Practice

6 questions · about 3 min

Explained step by step

Algorithm

When designing an algorithm there are 2 goals, in this order. The first is that it works: it gives the right answer for every possible input. The second is that it's efficient: if there are several ways to solve it, pick the fastest one and the one that uses the least memory. A super-fast algorithm that's sometimes wrong is useless. It's like a GPS: first it has to take you to the right place, and only then does the shortest route matter.

Time complexity

An algorithm's efficiency is looked at in 2 ways. Time efficiency says how long it takes to run. Space efficiency says how much memory it uses while running. Ideally it's fast and uses little memory, although you often gain in one at the cost of the other. It's like moving house: a big truck makes 1 trip but takes up a lot of room; a van takes up little room but makes 5 trips.

Complexity looks like an abstract topic to start with, but you can hardly talk about a data structure without asking how fast it is and how much memory it uses. That's why it comes first: it's the ruler everything else is measured with. Every time you see a new structure or algorithm, the first question will be its complexity. It's like learning to read a map before traveling: then you use it on every trip.

Complexity analysis

The most direct way to compare 2 algorithms is to run them and time them. But it has 2 problems. The result depends on the machine: the same code takes a different time on an old computer and a new one. And it depends on the size of the data: an algorithm can win with 100 items and lose with 1 million. To be sure you'd have to test on many machines and with many sizes, and that costs a lot.

Complexity analysis estimates efficiency without running the code, just by reasoning. It looks at how time and memory grow as the size of the input, called n, grows. It doesn't say "it takes 3 seconds", but "if you double the data, the time doubles" or "quadruples". It's like working out how much fuel a car uses per kilometer: it doesn't tell you how long today's trip takes, but it does tell you how the cost grows with distance.

Complexity analysis has 3 advantages over timing with a stopwatch. You don't need to run the code, so it costs no time or energy. It doesn't depend on the machine, so the result holds on any computer. And it tells you what happens with lots of data, which is exactly where it matters most. It's like reading a fridge's energy label: you don't need to plug it in for a year to know how much it uses.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Fast and light on memory