Why Learn DSA? A Tale of Two Librarians

Meet two librarians

A library has 10,000 books. Two librarians are asked: “Do we have the book Java Basics?”

  • Librarian A keeps the books in one big pile. She checks the books one by one. On a bad day she checks all 10,000.
  • Librarian B keeps the books on shelves sorted A to Z. She walks to the “J” shelf and finds it in seconds.

Both are correct, but B is much faster. The only difference is how the books are stored and the steps she follows. That's what DSA is about:

WordMeaningIn the story
Data structurea way to store datathe pile, or the sorted shelves
Algorithmclear steps that solve a problemcheck one by one, or jump to the right shelf

Let Java count the work

Here we look for one number among 1,000 numbers. We count how many numbers each method has to look at:

public class Main {
    public static void main(String[] args) {
        int[] books = new int[1000];
        for (int i = 0; i < books.length; i++) books[i] = i * 3;   // 0, 3, 6, 9 ... (sorted)
        int wanted = 2994;

        // Librarian A: check every book from the start
        int checksA = 0;
        for (int b : books) {
            checksA++;
            if (b == wanted) break;
        }

        // Librarian B: books are sorted, so look in the middle and throw away half each time
        int checksB = 0, lo = 0, hi = books.length - 1;
        while (lo <= hi) {
            checksB++;
            int mid = (lo + hi) / 2;
            if (books[mid] == wanted) break;
            if (books[mid] < wanted) lo = mid + 1;
            else hi = mid - 1;
        }

        System.out.println("Librarian A checked " + checksA + " books");
        System.out.println("Librarian B checked " + checksB + " books");
    }
}

Output

Librarian A checked 999 books
Librarian B checked 9 books

Same answer, a tiny fraction of the work. You'll learn Librarian B's trick (binary search) in Module 7.

How this course works

  • Every module has short lessons and then challenges you solve in the browser.
  • We often build a data structure ourselves as a small Java class first, so you see how it works inside. Then we use Java's ready-made version (ArrayList, HashMap, ArrayDeque, …).
  • Every example on these pages was really run – the output you see is the real output.

Tip: You should know basic Java: variables, if, loops, methods, arrays and a simple class. If not, take the Learn Java course first – it's in the same category.

HOME LABS COMMUNITY DASHBOARD