Lesson 1: What Is an Algorithm?
An algorithm is a precise, step-by-step procedure for solving a problem. You follow algorithms every day without noticing: a recipe is an algorithm for cooking a dish, the directions to a friend's house are an algorithm for getting there, and the long-division method you learned at school is an algorithm for dividing numbers. In programming, an algorithm is the idea behind the code — the plan that the code implements. Two programs can solve the same problem with the same answer but very different algorithms, and the difference matters enormously.
Consider finding a name in a class list. One approach is to read the list from the top until you find the name. Another is to use the fact that the list is alphabetical: open it in the middle, decide whether the name comes before or after, and repeat on the correct half. Both approaches are correct, but the second is dramatically faster on a long list. That is the whole subject of this course: not just solving problems, but solving them well, and knowing how to tell the difference.
A good algorithm has four qualities. It is correct: it produces the right answer for every valid input, not just the examples you tried. It is efficient: it uses a reasonable amount of time and memory. It is clear: another person can read it and understand why it works. And it terminates: it always finishes, never looping forever. The first lesson of competitive programming is that correctness comes before speed — a fast wrong answer scores nothing — but the second lesson is that a correct solution that is too slow also scores nothing, because contests give every problem a time limit, usually a couple of seconds.
# Two algorithms for the same job: find a name in a list.
names = ["ana", "ben", "cy", "dan", "eli", "fay", "gus"]
def find_linear(names, target):
for i, name in enumerate(names):
if name == target:
return i
return -1
def find_binary(names, target):
lo, hi = 0, len(names) - 1
while lo <= hi:
mid = (lo + hi) // 2
if names[mid] == target:
return mid
if names[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(find_linear(names, "eli")) # 4
print(find_binary(names, "eli")) # 4
Problems, inputs and edge cases
Every contest problem gives you three things: a story, a precise definition of the input and the output, and limits on the input size. The limits are not decoration — they are a hint about which algorithm the problem expects. If the input can have up to a hundred thousand items, a solution that compares every pair will be far too slow; if the input is at most twenty items, an approach that tries every possibility might be exactly right. Learning to read limits is one of the most valuable contest skills, and the next three lessons give you the language for it.
The other habit to build from day one is thinking about edge cases before you write code: the empty input, the input with one item, the input where everything is the same, the largest input allowed. Most contest failures are not caused by a wrong idea but by an edge case the programmer never considered. Get into the habit of writing down two or three edge cases for every problem, and testing them by hand, before you trust your solution.
Going further
Algorithms are not only in computers. Sorting a hand of cards, finding a word in a dictionary by opening it in the middle, or planning the fastest route through a supermarket are all algorithms, and thinking about them that way is good training. The dictionary example is particularly instructive: nobody reads a dictionary from the first page, because the alphabetical order lets you halve the search at each step — the same idea as binary search. Noticing the algorithms in everyday life builds the instinct that contest problems reward: seeing the structure of a problem before reaching for code.
Programmers often describe an algorithm in pseudocode before writing it in a real language: plain-language steps, with the structure of code but none of the syntax. Pseudocode is useful because it forces you to think about the idea rather than the punctuation, and because it is easy to share with someone who programs in a different language. In a contest, a few lines of pseudocode on paper — or even in a comment at the top of your file — can be the difference between a solution you understand and one you are guessing at.
Try a small experiment to feel the difference between algorithms: take a shuffled list of a thousand numbers and find a value in it twice — once by scanning from the start, and once by sorting the list first and then binary searching. Time both approaches with the time module. On a single search the scan wins, because sorting costs more than the scan saves; on a hundred searches the binary search wins by a wide margin. That crossover — where the cost of preparation pays for itself — is a pattern you will meet again and again, and recognising it is one of the most practical skills in this course.
Key Terms
- Algorithm
- A precise, step-by-step procedure for solving a problem, independent of any programming language.
- Correctness
- An algorithm produces the right answer for every valid input.
- Efficiency
- How much time and memory an algorithm uses as the input grows.
- Termination
- An algorithm always finishes; it never loops forever.
- Time limit
- The maximum time a contest allows a solution to run, usually a couple of seconds.
- Edge case
- An unusual or extreme input — empty, single-item, all-equal, or maximum-size — where bugs often hide.
- Input limits
- The stated maximum size of the input in a problem; a hint about which algorithm is expected.
Discussion Questions
- Why can two correct programs for the same problem be very different in quality? What besides the answer matters?
- A recipe is an algorithm. What would make a recipe incorrect, inefficient, or unclear — and do the same ideas apply to code?
- Why do contest problems state input limits? What can you learn from them before writing any code?
Practice Questions
- What is the difference between an algorithm and a program?
- Why is the alphabetical (binary) search faster than reading from the top?
- Name the four qualities of a good algorithm from this lesson.
- What is an edge case? Give one example for a program that finds the largest number in a list.
- Why does a correct solution still score nothing if it is too slow?
Show answers
- An algorithm is the idea or plan; a program is the algorithm written in a programming language. The same algorithm can be written in Python, C++ or Java.
- It halves the remaining list at each step instead of checking one item at a time. On a long sorted list the difference is enormous.
- Correct, efficient, clear, and terminating. A good algorithm gives the right answer, in reasonable time and memory, understandably, and always finishes.
- An unusual or extreme input; for example, an empty list or a list with one item. Edge cases are where bugs hide, so they deserve tests of their own.
- Because contests enforce a time limit. A solution that exceeds the limit is judged wrong, however correct its answers would be.