Algorithm Basics
Where algorithms begin
An algorithm is not necessarily a complicated formula or a clever data structure. Most often, everything starts with a simple sequence of actions: iterate over values, count something, find the best element, split a number into digits, or use divisibility properties.
This section brings together exactly these basic techniques. They appear in a huge number of problems and will become building blocks for more advanced algorithms later in the course.
What this section covers
- Brute Force. You will learn to systematically check all suitable options and understand when a direct solution is a perfectly reasonable and sufficient choice.
- Counting. We will look at problems where you need to go through the data and count the number of elements that satisfy a condition.
- Minimum and Maximum. You will learn to find the smallest and largest value in one pass and choose the initial result value correctly.
- Working with Digits. We will see how to extract the digits of an integer and build simple algorithms around them.
- Divisibility. We will use the remainder operation to test divisibility and solve typical divisor problems.
- Math Problems. We will combine the basic numeric techniques and learn to translate a problem statement into a sequence of calculations.
How these topics fit together
Almost every problem in this section uses the same general approach: decide which data needs to be examined, what state should be stored during the traversal, and how that state should change at each step. At first this will be a simple iteration, then a counter, a current minimum, or individual digits of a number.
int count = 0;
for (int value : numbers) {
if (value > 0) {
count++;
}
}
The code is small, but it already contains the foundation of many algorithms: sequential traversal, a condition, and state that changes as the data is processed.