What is an algorithm? Counting steps

What an algorithm is; Big-O intuition by counting.

1. What is this?

An algorithm is a precise recipe: steps that solve a problem. Big-O describes how steps grow as input grows. Scanning n items once is O(n) — linear: twice the items, twice the work. A single print is O(1) — constant: same work whatever n is. A loop inside a loop touching all pairs is O(n²).

2. Why do we use it?

An O(n²) page works for 100 rows and dies at 100,000. Naming growth helps you pick the right recipe before users feel it.

3. Syntax breakdown

  • for (let i = 0; i < n; i++) { print(i); }

    One loop over n items: O(n) steps.

  • print(first); print(last);

    Fixed work regardless of n: O(1).

  • for i... for j... { }

    Nested loops over n each: about n*n = O(n²).

5. Common mistakes

  • Treating Big-O as exact seconds — it describes growth, not speed.
  • Ignoring constants and setup for tiny inputs where they dominate.
  • Assuming nested loops are always O(n²) — it depends on what each loop ranges over.

Practice task

Add scan(20) and confirm steps equal n each time (linear growth).

Hint

Add scan(20); at the bottom and Run.

Try it below — tests run automatically when you press Run.

dsa

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is an algorithm?

  2. 2. Scanning n items once is…

  3. 3. A loop inside a loop over n each is…

4. Example — edit and run

dsa

Output

Press Run to see output.

Expected output: n=5 steps=5