1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to Algorithms

Algorithms and Computational Complexity

What an algorithm is

An algorithm is a finite, precisely specified procedure for solving a problem or carrying out a task. It consists of instructions that can be followed in a defined order, with the aim of producing a correct result.

The word algorithm is historically linked to the name of the ninth-century mathematician Muhammad al-Khwarizmi. His work helped transmit Indian place-value numerals to the Arabic-speaking world and included methods for carrying out calculations and solving algebraic problems. His name was Latinized as Algoritmi, from which algorithm developed. The history also points to a conceptual connection: formal rules for manipulating numbers and equations are early examples of systematic procedures for solving problems.

Effective methods

An effective method is a procedure with properties that make it possible to carry out reliably:

  • It consists of a finite number of exact instructions.

  • It applies to a defined class of problems.

  • It always finishes after a finite number of steps.

  • It produces the correct answer for problems in that class.

  • Its instructions can, in principle, be followed by a person using only ordinary aids such as writing materials.

Methods for long division and solving equations are familiar examples: the solver follows a sequence of specified operations rather than relying on a vague description of what the answer should be.

An algorithm is not merely a general idea for solving a problem. It is a sufficiently precise procedure whose steps can be followed to reach a result.

Unambiguous does not necessarily mean deterministic

An algorithm’s instructions must be unambiguous: at each point, the procedure must say what actions are permitted. This is different from requiring the algorithm to produce exactly the same behavior every time.

A route-finding procedure, for instance, may select different roads depending on traffic or other inputs. Its choices can vary while its general structure remains clear. More generally, an algorithm can use choices, randomness, or changing inputs, provided the procedure specifies how these are handled and what correctness or termination guarantees apply.

Algorithms were originally carried out by people

Before electronic computers, the word computer commonly referred to a person who performed calculations. Groups of trained human computers carried out the large quantities of numerical work needed by scientific, engineering, and military projects. Such workers helped develop and apply methods that remain part of computing today.

This history emphasizes that algorithms are not inherently tied to electronic devices. They are procedures that can be carried out by people or machines, so long as the executor can follow the instructions.


Standard algorithms and problem-solving

Many problems that seem to require a new solution turn out to have established algorithms. These standard methods are important because they prevent people from having to reinvent solutions to common tasks. They also give a starting point for comparing methods and choosing an appropriate one.

Algorithms are not always as modular as components in electronics: an established method may still need to be adapted to a particular problem or system. That adaptation can introduce errors. Nevertheless, knowledge of standard algorithms is a central part of computer science.

A sorting interview question illustrates why algorithm choice matters. Sorting a million integers by an inefficient method can require far more work than using a well-designed sorting algorithm. The amount of data matters, but so does the way the algorithm’s work grows as the data set increases.


Sorting algorithms

Sorting arranges items into a specified order, such as from smallest to largest. Sorting methods provide clear examples of how algorithms work and how their efficiency can be analyzed.

Bubble sort

Bubble sort repeatedly compares neighboring items and swaps them when they are in the wrong order. A pass through the list moves some out-of-place values toward their correct positions. Passes continue until the list is sorted.

For example, if a larger number appears immediately before a smaller number, the two are swapped. The process is then repeated across the list.

  • If the data are already sorted and the implementation detects that a full pass made no swaps, the procedure can finish after one pass. Its best-case work is proportional to the number of items, or O(n)O(n)O(n).

  • If the data are in reverse order, many values must travel through the list over repeated passes. The worst-case work grows proportionally to n2n^2n2, or O(n2)O(n^2)O(n2).

Bubble sort is useful for explaining comparisons and complexity, but it is generally unsuitable for large real-world sorting tasks because its work grows rapidly.

Merge sort

Merge sort uses a divide-and-conquer strategy:

  1. Divide the data into smaller sublists.

  2. Sort the smaller sublists.

  3. Merge the sorted sublists into one sorted list.

Merging two already-sorted lists can be done efficiently by repeatedly comparing their next available items. This avoids the repeated long-distance movement of values that makes bubble sort slow. Merge sort typically has time complexity O(nlog⁡n)O(n \log n)O(nlogn), making it substantially more suitable for large data sets.

Timsort

Timsort is a practical sorting algorithm used in several widely used programming environments. It combines ideas from insertion sort and merge sort and takes advantage of runs of data that are already ordered. Like other standard algorithms, it can be improved as implementations are tested and bugs are discovered.


Measuring algorithm efficiency

The time taken by a program on one computer is not, by itself, a useful measure of how well its algorithm scales. Faster hardware can make a slow method finish sooner, but it does not change how the method’s workload grows as the input becomes larger.

Time and space complexity

For an input containing nnn items, time complexity describes how the amount of computational work changes as nnn increases. It is often measured by counting steps or operations rather than seconds, because elapsed time depends on the computer and implementation.

Space complexity describes how the amount of memory required changes as the input grows. In many discussions, “complexity” refers to time complexity unless space is explicitly mentioned.

Best case, worst case, and typical behavior

An algorithm’s workload can depend on the particular input, not just its size:

  • Best-case analysis considers the easiest inputs of a given size.

  • Worst-case analysis considers the most demanding inputs.

  • Average-case analysis considers expected behavior under assumptions about the distribution of inputs.

For bubble sort, already-sorted data can produce a best case of O(n)O(n)O(n) if the algorithm stops after a pass with no swaps, while reverse-sorted data produces a worst case of O(n2)O(n^2)O(n2). A worst-case analysis is useful because it provides a guarantee about the maximum work for inputs of a given size, though it does not necessarily describe every individual run.

Empirical tests can also help reveal practical behavior. For example, an experiment can sort many randomly generated lists of different sizes and graph the observed work. Such a simulation illustrates scaling but does not replace a mathematical analysis or prove the behavior for every possible input.

Big-OOO notation

Big-OOO notation describes an upper-bound growth rate, focusing on how an algorithm scales as the input becomes large. For example, O(n2)O(n^2)O(n2) indicates that the work grows no faster than a quantity proportional to n2n^2n2, apart from constants and lower-order terms.

Big-OOO analysis largely ignores:

  • The particular computer used.

  • Constant factors in the workload.

  • Small differences that matter only for particular input sizes.

This abstraction makes it possible to compare the underlying growth of algorithms rather than comparing individual machines. It also has limitations: an algorithm with a theoretically better growth rate can be slower in practice for small inputs, and constants can have a major effect on real performance.

A rough hierarchy of common growth rates, from generally more scalable to less scalable, includes:

  • O(1)O(1)O(1): constant work.

  • O(log⁡n)O(\log n)O(logn): logarithmic work.

  • O(n)O(n)O(n): linear work.

  • O(nlog⁡n)O(n \log n)O(nlogn): work typical of many efficient sorting methods.

  • Polynomial growth, such as O(n2)O(n^2)O(n2).

  • Exponential or factorial growth, which can become impractical very quickly.

The hierarchy is a guide, not a guarantee that every algorithm in a lower-growth category will be faster on every real input.


Polynomial-time problems and the class PPP

The Cobham–Edmonds thesis is the practical idea that problems solvable in polynomial time are often considered tractable. In complexity theory, PPP is the class of decision problems that can be solved by a deterministic Turing machine in polynomial time.

A polynomial running time is bounded by a polynomial in the input size, such as O(n2)O(n^2)O(n2) or O(n5)O(n^5)O(n5). Polynomial time is generally treated as a useful indicator of scalability, but it does not mean that an algorithm is always fast. A high-degree polynomial, a large constant factor, or a very large input can still make a computation impractical.

Conversely, an algorithm that is not known to run in polynomial time is not automatically useless. Many important practical methods work on difficult problems, often by using approximations, heuristics, or techniques effective on the inputs encountered in practice. The distinction between polynomial and non-polynomial complexity is a broad theoretical guide, not a simple dividing line between “usable” and “impossible.”


The traveling salesperson problem

The traveling salesperson problem (TSP) asks for a shortest tour through a collection of locations, subject to specified rules. In the version considered here:

  • Every location must be visited.

  • Each location is visited once.

  • The tour returns to its starting point.

  • The total distance should be as small as possible.

A common mathematical representation is a weighted graph: locations are vertices, and travel distances between pairs of locations are edge weights. A valid tour is a cycle visiting every vertex exactly once, also called a Hamiltonian cycle.

Brute-force search

A direct approach is to enumerate possible tours, calculate each tour’s length, and keep the shortest. If the starting location is fixed and direction is counted separately, a problem with nnn locations has (n−1)!(n-1)!(n−1)! possible visit orders. If a tour and its reverse are considered the same, the number of distinct tours is approximately (n−1)!/2(n-1)!/2(n−1)!/2 for a symmetric distance problem.

For 131313 locations, fixing the starting point gives 12!12!12! orders before accounting for reverse-direction duplicates. This is manageable for a small example. But factorial growth becomes overwhelming as the number of locations increases: even a powerful computer cannot compensate for the enormous growth of the search space.

This is an example of why an algorithm can work well for a small input yet be entirely impractical at a larger scale.

Nearest-neighbor heuristic

The nearest-neighbor algorithm is a simple heuristic for TSP:

  1. Start at a chosen location.

  2. Travel to the nearest location that has not yet been visited.

  3. Repeat until every location has been visited.

  4. Return to the starting point.

This method is fast and easy to implement, but it does not always find the optimal tour. The outcome can depend on the starting point, so trying different starting locations may give different tours.

Exact methods, heuristics, and bounds

A TSP method may be exact or approximate:

  • An exact algorithm finds an optimal tour, but may require impractical computation for large instances.

  • An approximate algorithm finds a tour efficiently but may not be optimal.

  • A heuristic is a practical strategy that often produces useful answers but, unless accompanied by a proof, does not necessarily provide a guarantee on how close it is to optimal.

The Held–Karp algorithm is an exact dynamic-programming approach to TSP. Its time complexity is commonly expressed as O(n22n)O(n^2 2^n)O(n22n). This is much better than enumerating every tour, but it still grows exponentially and is unsuitable for sufficiently large instances.

For metric TSP, where travel distances satisfy the triangle inequality, the Christofides algorithm produces a tour whose length is at most 3/23/23/2 times the optimal tour length. Such a guarantee is an approximation bound. A later result described in the lecture gives a marginally tighter approximation guarantee; its significance is mainly that even a very small improvement can represent a new theoretical advance.

Upper and lower bounds

Let L∗L^*L∗ be the length of an optimal tour.

  • Any feasible tour gives an upper bound on L∗L^*L∗, because the optimal tour cannot be longer than a valid tour already found.

  • A lower bound estimates a length that no valid tour can beat.

Bounds help evaluate a result even when the exact optimum is not known. If a feasible tour is close to a strong lower bound, the gap between them limits how much better the unknown optimum could be. A proved approximation ratio gives a formal guarantee; simply comparing several heuristic routes does not, by itself, establish such a guarantee.


Recursion and iteration

Algorithms often use recurring structures to control repeated work.

Iteration

Iteration repeats a set of steps, commonly until a condition is met or for each item in a collection. A sorting algorithm that repeatedly scans a list is an example.

Recursion

Recursion occurs when a procedure is defined in terms of smaller instances of itself. A recursive algorithm must have a stopping condition, or base case, to prevent it from continuing indefinitely.

The factorial function illustrates recursion:

n!=n(n−1)!n! = n(n-1)!n!=n(n−1)!

with the base case 0!=10! = 10!=1. The recursive definition connects the calculation for nnn to a smaller calculation, namely the one for n−1n-1n−1.

In modern computer science, recursion has this specific technical meaning. Older literature sometimes used the word more broadly, so historical uses do not always match the current definition.


Representing algorithms

Algorithms can be described using different forms, each with advantages and limitations.

Flowcharts

A flowchart represents a procedure visually using standardized shapes and arrows. It can show operations, decisions, and the paths that execution may take. Flowcharts were used to model processes and later to describe computer programs.

Their standardized visual symbols can make them understandable across programming languages. However, drawing flowcharts by hand or on early computers could be cumbersome, which contributed to their declining use.

Pseudocode

Pseudocode describes an algorithm in a structured form resembling programming language, but without requiring the syntax of a particular language. It allows a reader to focus on the logic rather than details of implementation.

Pseudocode is widely used but is not always standardized. Different writers may use different conventions, so a description must still be precise enough for its intended readers.


Formal models of computation

A central theoretical question is how to define what can be computed by an algorithm. Formal models make it possible to reason precisely about that question.

Church’s lambda calculus and Turing machines

Lambda calculus, developed by Alonzo Church, is a formal system for expressing and manipulating functions. It provides a mathematical framework for representing computation.

In 1936, Alan Turing described a simple abstract computing device now called a Turing machine. A basic Turing machine has:

  • A tape divided into cells that can store symbols.

  • A read/write head that examines and changes a cell.

  • A finite set of rules that determines what the machine does next, including whether the head moves and which state follows.

A universal Turing machine can simulate other Turing machines when supplied with their descriptions and inputs. This makes the model useful for understanding general-purpose computation.

Turing developed this model while investigating a mathematical decision problem, not as a proposal for building a practical computer. The model is an abstraction that allows researchers to reason about what procedures can compute and how much resource they require.

The Church–Turing thesis

The Church–Turing thesis says, in essence, that any function that can be calculated by an effective procedure can be computed by a Turing machine. It links the informal notion of an algorithm to a formal model of computation.

It is a thesis about the meaning of effective computation, not a theorem proved from a more basic definition of “every possible algorithm.” Turing machines are theoretical models; their value comes from the broad range of computing systems and procedures they can represent.


Decision problems and complexity classes

A decision problem is a problem whose answer is yes or no. Many questions that appear to ask for a number or object can be converted into decision problems.

For example, rather than asking for the shortest TSP tour, one can ask: “Is there a tour with length less than or equal to a specified limit?” This produces a yes-or-no question that can be analyzed using complexity theory.

The class NPNPNP

NPNPNP is the class of decision problems for which a proposed yes solution can be verified in polynomial time by a deterministic procedure. This definition concerns checking a supplied certificate, not necessarily finding one quickly.

For example, given a completed Sudoku grid, a verifier can check that every row, column, and required subgrid follows the puzzle’s constraints. Finding a valid completion may be much harder than checking a proposed completion.

For TSP, if someone supplies a proposed tour and a distance limit, it is relatively straightforward to check whether the tour visits every location as required and meets the limit. This gives the decision version of TSP a polynomial-time verification procedure.

Every problem in PPP is also in NPNPNP, because if a problem can be solved in polynomial time, its answer can also be verified in polynomial time.

NPNPNP-complete and NPNPNP-hard problems

A problem is NP-complete if it is in NPNPNP and is at least as hard as every problem in NPNPNP, under an appropriate notion of reduction. A reduction translates instances of one problem into instances of another while preserving the answer. It allows the difficulty of one problem to be related to that of another.

A problem is NP-hard if it is at least as hard as the problems in NPNPNP, but it need not itself belong to NPNPNP. In particular, some NP-hard problems are not decision problems or do not have solutions verifiable in polynomial time.

Sudoku and decision versions of TSP are examples associated with NP-completeness. Many other difficult problems can be connected through reductions, which lets researchers study a broad family of problems using shared techniques.


The PPP versus NPNPNP question

The question PPP versus NPNPNP asks whether every problem whose proposed solution can be checked in polynomial time can also be solved in polynomial time. In notation, the question is whether P=NPP = NPP=NP or P≠NPP \ne NPP=NP.

Most complexity theorists suspect that P≠NPP \ne NPP=NP, but no proof is known. The question matters because it concerns the possible gap between finding a solution and verifying a solution.

If P=NPP = NPP=NP, then every problem in NPNPNP would have a polynomial-time solving algorithm. This would have far-reaching consequences for optimization, automated reasoning, scheduling, and other fields. It would not automatically mean that every creative or difficult task became effortless: practical performance also depends on constants, input sizes, and the form of the algorithm.

The question also has implications for cryptography. Many cryptographic systems rely on problems for which checking a proposed answer is practical while finding that answer is believed to be difficult. If P=NPP = NPP=NP, some current security assumptions could be threatened. However, the exact consequences would depend on the proof and on the specific cryptographic constructions involved.

Complexity classes beyond PPP and NPNPNP

Computational complexity includes many classes beyond PPP and NPNPNP:

  • co-NP concerns decision problems for which no answers have efficiently verifiable certificates, under the corresponding formal definition.

  • PSPACE is the class of problems solvable using an amount of memory bounded by a polynomial in the input size, regardless of how much time is used.

  • BPP includes problems that can be solved in polynomial time by randomized algorithms with bounded error probability.

  • BQP is a related class for problems efficiently solvable by quantum computers with bounded error.

Complexity theory also studies hierarchies and classes whose exact relationships are unknown. Some problems cannot be solved by any algorithm at all, no matter how much time or memory is available; these are distinct from problems that are merely computationally expensive.


Unsolvable problems: the halting problem

The halting problem asks whether, given an arbitrary program and input, it is possible to decide whether that program will eventually stop or run forever.

Turing showed that no algorithm can correctly answer this question for every possible program and input. The problem is therefore undecidable: it is not merely slow to solve; a general procedure that always gives the correct answer does not exist.

This illustrates an important distinction:

  • A problem can be tractable, with an efficient algorithm.

  • A problem can be intractable, where algorithms exist but may require impractical resources.

  • A problem can be undecidable, where no algorithm solves every instance correctly.

The halting problem’s undecidability also shows why not every mathematical or computational question can be answered by writing a sufficiently clever program.


Algorithms, bias, and accountability

Algorithms used in society can produce discriminatory outcomes. An algorithm does not need to contain an explicit rule about ethnicity or another protected characteristic to have biased effects. Its inputs, training data, assumptions, or design choices may correlate with protected characteristics.

For example, a fraud-detection system might use credit scores. If credit scores are strongly associated with where people live, and residence is associated with ethnicity, the system can produce unequal effects even without explicitly using ethnicity. The resulting bias can come from the data and the design, rather than from a conscious intention encoded in a single rule.

Reducing algorithmic bias requires attention to the complete system, including:

  • Whether the training or input data represent the affected population fairly.

  • Whether input variables act as proxies for protected characteristics.

  • How the system’s outcomes differ among groups.

  • Whether the results meet legal and ethical fairness requirements.

  • How decisions can be audited, challenged, and corrected.

A system can also change after deployment. Software may receive updates, and learning systems may incorporate new data from their own operation. As a result, a system’s behavior can drift from the behavior originally specified or tested. This raises questions about verifiability and testability: whether the system continues to produce suitable results, and whether its decisions can be examined and justified.

Automated grading as a case study

An automated grading system may be carefully tested on historical data yet still produce outcomes that are unacceptable in practice. A system can disadvantage a portion of students on each examination, and the effect can accumulate when each student receives several results. The impact may therefore be much larger than the apparently limited rate of adverse decisions for a single exam.

This example shows that technical testing alone is not enough. A responsible evaluation must consider how results affect people, whether the process is perceived as fair, and whether affected individuals can understand or contest decisions. Problems can arise from the system’s social consequences and the decisions surrounding its use, not only from a coding error.


Key ideas to retain

  • An algorithm is a finite, precise procedure for solving a defined problem.

  • Efficiency is usually studied through how resource requirements scale with input size, not by measuring one run on one computer.

  • Big-OOO notation describes growth while abstracting away constants and machine-specific performance.

  • Standard algorithms can make common tasks far more efficient; bubble sort and merge sort illustrate the difference.

  • Some problems, such as TSP, become impractical for exact brute-force search as their inputs grow, motivating heuristics, approximation algorithms, and bounds.

  • PPP concerns polynomial-time solvability; NPNPNP concerns polynomial-time verification of proposed solutions.

  • The unresolved question PPP versus NPNPNP asks whether efficient verification always implies efficient solution.

  • The halting problem demonstrates that some problems are undecidable, not merely computationally expensive.

  • Algorithmic outcomes depend on data, design, and context, so fairness and accountability are part of evaluating real-world systems.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent