Who has the highest CGPA?line 1
  1. first = 7.2
  2. rest = [8.4, 6.9, 9.1, 8.2]
  3. best = first
  4. for c in rest:
  5. if c > best:
  6. best = c
  7. print("Highest:", best)

Variables

first
7.2 (just changed)

Roll number 1's CGPA. Drag the slider to change it.

Step 1 of 15
Try another first

That was an algorithm: exact steps that turn a list into its highest CGPA. best changes only when a bigger CGPA turns up.

Quick check

Quick check: Use the slider above the code to set the first CGPA to 9.5. After best = 9.5, how many times does best change?

What an algorithm is#

An algorithm is a finite sequence of exact steps that turns an input into the right output. Here the input is five CGPAs, one per student. Positions start at 0, so roll number 1 sits at position 0.

7.28.46.99.18.201234
cgpas

In the opener, for c in rest: hands each of the other CGPAs to c in turn. The code does four plain steps:

Step in plain wordsWhere it is in the code
1. Take the first CGPA as bestbest = first
2. Take each next CGPAfor c in rest:
3. If it is bigger than best, it becomes bestif and best = c
4. When none are left, give back bestprint

The four steps are the algorithm. The Python is one way of writing them down.

Five properties#

A list of steps must have all five of these to count as an algorithm.

PropertyMeaningIn find the maximum
InputIt takes data inThe list of CGPAs
OutputIt gives an answerThe highest CGPA
Definiteness (definite means exact)Every step is exact"Is 8.4 > 7.2?" has one answer
FinitenessIt always stopsOne pass, then done
CorrectnessRight answer for every valid inputNever misses the top

Speed is not on this list. A slow algorithm is still an algorithm. How fast it is gets measured separately, with Big O, in the next step.

Quick check

Quick check: A placement cell writes: 1. Read the CGPA list. 2. Pick a strong candidate. Which property fails?

Quick check

Quick check: A senior writes: keep picking a random student until you find one with a CGPA of 10. Nobody in the list has a 10. Which property fails?

Correct means every input#

-3-7-1
night temperatures in a Shimla hostel

The highest temperature here is -1. Watch what a common shortcut gives instead.

Algorithm or program#

AlgorithmProgram
The idea: exact stepsThose steps in one language
Written in plain words or as boxes and arrowsWritten in Python, C++, Java
One set of stepsMany programs, one per language and coder

An algorithm is a recipe. A program is that recipe written out in Hindi, Tamil or English. One recipe, many translations.

Quick check

Quick check: You rewrite find the maximum from Python into Java. What changed?

The code, with edge cases#

Here it is as a function. cg[:n] means the first n items of cg, and nums[1:] means every item except the first. Guess first, then slide n to 1, and then to 0.

Quick check

Quick check: With n = 1, how many comparisons does find_max make?

find_max, from 5 students down to 0line 1
Try another n
  1. def find_max(nums):
  2. if len(nums) == 0:
  3. return None
  4. best = nums[0]
  5. for x in nums[1:]:
  6. if x > best:
  7. best = x
  8. return best
  9. n = 5
  10. cg = [7.2, 8.4, 6.9, 9.1, 8.2]
  11. print(find_max(cg[:n]))

Variables

None yet

Line 1 runs.

Step 1 of 19

At n = 0, the check on line 2 matters. Without it, nums[0] asks for an item that does not exist, so Python crashes with an IndexError. An empty list has no maximum, so the function returns None, Python's way of saying "no value".

Same job, different algorithms#

Searching for a roll number is one job, and there is more than one algorithm for it. Linear search checks cells one by one. Count how many it touches.

Visualizer

Linear Search

Open full →

Quick check

Quick check: 1,000 roll numbers, and the one you want is not there. How many checks does linear search make?

If the list is sorted, binary search jumps to the middle. If the roll number you want is smaller, the right half cannot hold it, so that half is thrown away. You will learn it properly in Searching. For now, watch how few looks it needs.

Visualizer

Binary Search

Open full →
AlgorithmNeedsChecks for 1,000 items
Linear searchAny listUp to 1,000
Binary searchA sorted listAt most 10
Dict lookupA hash mapUsually 1: it jumps straight to the key

The same question, three algorithms, three data structures. That is why the last step and this one go together.

Families you will meet#

Most problems on this roadmap use one of a few strategies. Learn the strategy once, and you will spot it in problems you have never seen.

FamilyThe idea in one lineExample
SearchingFind an item in a collectionLinear, binary search
SortingPut items in orderBubble, merge sort
Two pointersTwo indexes walk the list toward the answerTwo prices that add up to your budget
Recursion and backtrackingSolve a smaller copy; try a choice, undo it if it failsFill a Sudoku, undo a wrong digit
GreedyTake the best-looking choice at each stepFit the most club meetings in one room
Dynamic programmingSave answers to smaller problems, never redo themFibonacci numbers without recomputing
Graph traversalVisit every node by following edgesBFS spreads level by level, DFS goes deep first

Here is the simplest sorting algorithm. Watch how the biggest value bubbles to the end each pass.

Visualizer

Bubble Sort

Open full →

Now greedy, from the table, on made-up coins of ₹1, ₹3 and ₹4:

Quick check

Quick check: To make ₹6, a greedy rule takes the biggest coin that fits each time. How many coins does it use?

In other languages#

The same find the maximum in Python, C++ and Java. The steps do not change, only the syntax. Each one refuses an empty list: Python returns None, as in the trace above, and C++ and Java stop with an error. A made-up answer like -1 would be wrong, because -1 can be a real maximum (think of Shimla).

One last check#

Quick check

Quick check: Run find the maximum on [6.5, 9.4, 9.4, 7.1]. How many times does best change, and what comes out?

Next is Big O, which turns "count the checks" into a way to compare algorithms for the same job.