About

Algorithms and Problem Solving

Introduction to Algorithms and Problem Solving

An algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining a required output for any legitimate input in a finite amount of time.

Diagram loads as you scroll.

Essential Criteria of an Algorithm


Review of Fundamental Data Structures

Levitin organizes data structures based on how elements are arranged and accessed.

1. Linear Data Structures

Data StructureAccess TimeInsert / DeleteTypical Use Case in Algorithms
ArrayΘ(1)\Theta(1) by indexΘ(n)\Theta(n) arbitrary positionContiguous storage, sorting buffers, lookup tables
Singly Linked ListΘ(n)\Theta(n) searchΘ(1)\Theta(1) at given nodeDynamic memory allocation, chaining in hash tables
Stack (LIFO)Θ(1)\Theta(1) topΘ(1)\Theta(1) push / popDFS traversal, function call stack, undo operations
Queue (FIFO)Θ(1)\Theta(1) frontΘ(1)\Theta(1) enqueue / dequeueBFS traversal, task scheduling, level-order trees

2. Graphs

A graph G=(V,E)G = (V, E) consists of a set of vertices VV and edges EE.

3. Trees

A tree is an undirected connected graph without cycles. A rooted tree has a distinguished root vertex.


Exercises

Exercise 1

Explain the difference between an algorithm and a heuristic. Does a heuristic qualify as an algorithm under the formal Levitin definition?

Show solution ↓
Solution
  • An algorithm guarantees finding the exact correct solution for every legitimate input within a finite number of steps.
  • A heuristic is a practical rule of thumb or guideline that finds good or near-optimal solutions quickly, but does not mathematically guarantee correctness or optimality in all instances.
  • Under the formal definition given by Levitin, a procedure that fails to produce guaranteed correct output for all valid inputs is strictly classified as an approximation heuristic rather than a classical exact algorithm.
Exercise 2

Suppose a web crawler graph has ∣V∣=50,000|V| = 50{,}000 pages and each page links to an average of 10 other pages (∣E∣=500,000|E| = 500{,}000). Compare the memory footprint of an Adjacency Matrix versus an Adjacency List.

Show solution ↓
Solution

1. Adjacency Matrix:

  • Requires ∣V∣2=50,000×50,000=2,500,000,000|V|^2 = 50{,}000 \times 50{,}000 = 2{,}500{,}000{,}000 entries (2.5×1092.5 \times 10^9 booleans / bytes ≈2.5 GB\approx 2.5\text{ GB}).

2. Adjacency List:

  • Stores ∣V∣=50,000|V| = 50{,}000 head pointers plus ∣E∣=500,000|E| = 500{,}000 edge nodes.
  • Total stored references ≈550,000\approx 550{,}000 entries (≈a few megabytes\approx \text{a few megabytes}).

Conclusion: The graph is extremely sparse (∣E∣≪∣V∣2|E| \ll |V|^2). The Adjacency List uses less than 0.2% of the memory required by the Adjacency Matrix and enables neighbor exploration in Θ(deg(v))≈10\Theta(\text{deg}(v)) \approx 10 operations instead of scanning 50,000 matrix columns.