In
theoretical computer science
Theoretical computer science is a subfield of computer science and mathematics that focuses on the Abstraction, abstract and mathematical foundations of computation.
It is difficult to circumscribe the theoretical areas precisely. The Associati ...
, the time complexity is the
computational complexity that describes the amount of computer time it takes to run an
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of Rigour#Mathematics, mathematically rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algo ...
. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elementary operation takes a fixed amount of time to perform. Thus, the amount of time taken and the number of elementary operations performed by the algorithm are taken to be related by a
constant factor.
Since an algorithm's running time may vary among different inputs of the same size, one commonly considers the
worst-case time complexity, which is the maximum amount of time required for inputs of a given size. Less common, and usually specified explicitly, is the
average-case complexity, which is the average of the time taken on inputs of a given size (this makes sense because there are only a finite number of possible inputs of a given size). In both cases, the time complexity is generally expressed as a
function of the size of the input.
Since this function is generally difficult to compute exactly, and the running time for small inputs is usually not consequential, one commonly focuses on the behavior of the complexity when the input size increases—that is, the
asymptotic behavior of the complexity. Therefore, the time complexity is commonly expressed using
big O notation, typically etc., where is the size in units of
bits needed to represent the input.
Algorithmic complexities are classified according to the type of function appearing in the big O notation. For example, an algorithm with time complexity
is a ''linear time algorithm'' and an algorithm with time complexity
for some constant
is a ''polynomial time algorithm''.
Table of common time complexities
The following table summarizes some classes of commonly encountered time complexities. In the table, , i.e., polynomial in ''x''.
Constant time
An algorithm is said to be constant time (also written as
time) if the value of
(the complexity of the algorithm) is bounded by a value that does not depend on the size of the input. For example, accessing any single element in an
array takes constant time as only one
operation has to be performed to locate it. In a similar manner, finding the minimal value in an array sorted in ascending order; it is the first element. However, finding the minimal value in an unordered array is not a constant time operation as scanning over each
element in the array is needed in order to determine the minimal value. Hence it is a linear time operation, taking
time. If the number of elements is known in advance and does not change, however, such an algorithm can still be said to run in constant time.
Despite the name "constant time", the running time does not have to be independent of the problem size, but an upper bound for the running time has to be independent of the problem size. For example, the task "exchange the values of and if necessary so that
" is called constant time even though the time may depend on whether or not it is already true that
. However, there is some constant such that the time required is always ''at most'' .
Logarithmic time
An algorithm is said to take logarithmic time when
. Since
and
are related by a
constant multiplier, and such a
multiplier is irrelevant to big O classification, the standard usage for logarithmic-time algorithms is
regardless of the base of the logarithm appearing in the expression of .
Algorithms taking logarithmic time are commonly found in operations on
binary tree
In computer science, a binary tree is a tree data structure in which each node has at most two children, referred to as the ''left child'' and the ''right child''. That is, it is a ''k''-ary tree with . A recursive definition using set theor ...
s or when using
binary search.
An
algorithm is considered highly efficient, as the ratio of the number of operations to the size of the input decreases and tends to zero when increases. An algorithm that must access all elements of its input cannot take logarithmic time, as the time taken for reading an input of size is of the order of .
An example of logarithmic time is given by dictionary search. Consider a
dictionary
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged Alphabetical order, alphabetically (or by Semitic root, consonantal root for Semitic languages or radical-and-stroke sorting, radical an ...
which contains entries, sorted in
alphabetical order
Alphabetical order is a system whereby character strings are placed in order based on the position of the characters in the conventional ordering of an alphabet. It is one of the methods of collation. In mathematics, a lexicographical order is ...
. We suppose that, for
, one may access the th entry of the dictionary in a constant time. Let
denote this th entry. Under these hypotheses, the test to see if a word is in the dictionary may be done in logarithmic time: consider
, where
denotes the
floor function
In mathematics, the floor function is the function that takes as input a real number , and gives as output the greatest integer less than or equal to , denoted or . Similarly, the ceiling function maps to the least integer greater than or eq ...
. If
--that is to say, the word is exactly in the middle of the dictionary--then we are done. Else, if
--i.e., if the word comes earlier in alphabetical order than the middle word of the whole dictionary--we continue the search in the same way in the left (i.e. earlier) half of the dictionary, and then again repeatedly until the correct word is found. Otherwise, if it comes after the middle word, continue similarly with the right half of the dictionary. This algorithm is similar to the method often used to find an entry in a paper dictionary. As a result, the search space within the dictionary decreases as the algorithm gets closer to the target word.
Polylogarithmic time
An algorithm is said to run in
polylogarithmic time if its time
is
for some constant . Another way to write this is
.
For example,
matrix chain ordering can be solved in polylogarithmic time on a
parallel random-access machine, and
a graph can be
determined to be planar in a
fully dynamic way in
time per insert/delete operation.
Sub-linear time
An algorithm is said to run in sub-linear time (often spelled sublinear time) if
. In particular this includes algorithms with the time complexities defined above.
The specific term ''sublinear time algorithm'' commonly refers to randomized algorithms that sample a small fraction of their inputs and process them efficiently to
approximately infer properties of the entire instance. This type of sublinear time algorithm is closely related to
property testing and
statistics
Statistics (from German language, German: ', "description of a State (polity), state, a country") is the discipline that concerns the collection, organization, analysis, interpretation, and presentation of data. In applying statistics to a s ...
.
Other settings where algorithms can run in sublinear time include:
*
Parallel algorithms that have linear or greater total
work (allowing them to read the entire input), but sub-linear
depth.
* Algorithms that have
guaranteed assumptions on the input structure. An important example are operations on
data structures
In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functi ...
, e.g.
binary search in a sorted array.
* Algorithms that search for local structure in the input, for example finding a local minimum in a 1-D array (can be solved in
time using a variant of binary search). A closely related notion is that of
Local Computation Algorithms (LCA) where the algorithm receives a large input and queries to local information about some valid large output.
Linear time
An algorithm is said to take linear time, or
time, if its time complexity is
. Informally, this means that the running time increases at most linearly with the size of the input. More precisely, this means that there is a constant such that the running time is at most
for every input of size . For example, a procedure that adds up all elements of a list requires time proportional to the length of the list, if the adding time is constant, or, at least, bounded by a constant.
Linear time is the best possible time complexity in situations where the algorithm has to sequentially read its entire input. Therefore, much research has been invested into discovering algorithms exhibiting linear time or, at least, nearly linear time. This research includes both software and hardware methods. There are several hardware technologies which exploit
parallelism to provide this. An example is
content-addressable memory. This concept of linear time is used in string matching algorithms such as the
Boyer–Moore string-search algorithm and
Ukkonen's algorithm.
Quasilinear time
An algorithm is said to run in quasilinear time (also referred to as log-linear time) if
for some positive constant ; linearithmic time is the case
. Using
soft O notation these algorithms are
. Quasilinear time algorithms are also
for every constant
and thus run faster than any polynomial time algorithm whose time bound includes a term
for any
.
Algorithms which run in quasilinear time include:
*
In-place merge sort,
*
Quicksort,
, in its randomized version, has a running time that is
in expectation on the worst-case input. Its non-randomized version has an
running time only when considering average case complexity.
*
Heapsort,
,
merge sort
In computer science, merge sort (also commonly spelled as mergesort and as ) is an efficient, general-purpose, and comparison sort, comparison-based sorting algorithm. Most implementations of merge sort are Sorting algorithm#Stability, stable, wh ...
,
introsort, binary tree sort,
smoothsort,
patience sorting, etc. in the worst case
*
Fast Fourier transform
A fast Fourier transform (FFT) is an algorithm that computes the discrete Fourier transform (DFT) of a sequence, or its inverse (IDFT). A Fourier transform converts a signal from its original domain (often time or space) to a representation in ...
s,
*
Monge array calculation,
In many cases, the
running time is simply the result of performing a
operation times (for the notation, see ). For example,
binary tree sort creates a
binary tree
In computer science, a binary tree is a tree data structure in which each node has at most two children, referred to as the ''left child'' and the ''right child''. That is, it is a ''k''-ary tree with . A recursive definition using set theor ...
by inserting each element of the -sized array one by one. Since the insert operation on a
self-balancing binary search tree takes
time, the entire algorithm takes
time.
Comparison sorts require at least
comparisons in the worst case because
, by
Stirling's approximation
In mathematics, Stirling's approximation (or Stirling's formula) is an asymptotic approximation for factorials. It is a good approximation, leading to accurate results even for small values of n. It is named after James Stirling, though a related ...
. They also frequently arise from the
recurrence relation
In mathematics, a recurrence relation is an equation according to which the nth term of a sequence of numbers is equal to some combination of the previous terms. Often, only k previous terms of the sequence appear in the equation, for a parameter ...
.
Sub-quadratic time
An
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of Rigour#Mathematics, mathematically rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algo ...
is said to be subquadratic time if
.
For example, simple, comparison-based
sorting algorithm
In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending ...
s are quadratic (e.g.
insertion sort), but more advanced algorithms can be found that are subquadratic (e.g.
shell sort). No general-purpose sorts run in linear time, but the change from quadratic to sub-quadratic is of great practical importance.
Polynomial time
An algorithm is said to be of polynomial time if its running time is
upper bound
In mathematics, particularly in order theory, an upper bound or majorant of a subset of some preordered set is an element of that is every element of .
Dually, a lower bound or minorant of is defined to be an element of that is less ...
ed by a
polynomial
In mathematics, a polynomial is a Expression (mathematics), mathematical expression consisting of indeterminate (variable), indeterminates (also called variable (mathematics), variables) and coefficients, that involves only the operations of addit ...
expression in the size of the input for the algorithm, that is, for some positive constant ''k''.
Problems for which a deterministic polynomial-time algorithm exists belong to the
complexity class
In computational complexity theory, a complexity class is a set (mathematics), set of computational problems "of related resource-based computational complexity, complexity". The two most commonly analyzed resources are time complexity, time and s ...
P, which is central in the field of
computational complexity theory
In theoretical computer science and mathematics, computational complexity theory focuses on classifying computational problems according to their resource usage, and explores the relationships between these classifications. A computational problem ...
.
Cobham's thesis states that polynomial time is a synonym for "tractable", "feasible", "efficient", or "fast".
Some examples of polynomial-time algorithms:
* The
selection sort sorting algorithm on ''n'' integers performs
operations for some constant ''A''. Thus it runs in time
and is a polynomial-time algorithm.
* All the basic arithmetic operations (addition, subtraction, multiplication, division, and comparison) can be done in polynomial time.
*
Maximum matchings in
graphs can be found in polynomial time. In some contexts, especially in
optimization
Mathematical optimization (alternatively spelled ''optimisation'') or mathematical programming is the selection of a best element, with regard to some criteria, from some set of available alternatives. It is generally divided into two subfiel ...
, one differentiates between
strongly polynomial time and weakly polynomial time algorithms.
These two concepts are only relevant if the inputs to the algorithms consist of integers.
Complexity classes
The concept of polynomial time leads to several complexity classes in computational complexity theory. Some important classes defined using polynomial time are the following.
*
P: The
complexity class
In computational complexity theory, a complexity class is a set (mathematics), set of computational problems "of related resource-based computational complexity, complexity". The two most commonly analyzed resources are time complexity, time and s ...
of
decision problem
In computability theory and computational complexity theory, a decision problem is a computational problem that can be posed as a yes–no question on a set of input values. An example of a decision problem is deciding whether a given natura ...
s that can be solved on a
deterministic Turing machine in polynomial time
*
NP: The complexity class of decision problems that can be solved on a
non-deterministic Turing machine in polynomial time
*
ZPP: The complexity class of decision problems that can be solved with zero error on a
probabilistic Turing machine in polynomial time
*
RP: The complexity class of decision problems that can be solved with 1-sided error on a probabilistic Turing machine in polynomial time.
*
BPP: The complexity class of decision problems that can be solved with 2-sided error on a probabilistic Turing machine in polynomial time
*
BQP: The complexity class of decision problems that can be solved with 2-sided error on a
quantum Turing machine in polynomial time
P is the smallest time-complexity class on a deterministic machine which is
robust in terms of machine model changes. (For example, a change from a single-tape Turing machine to a multi-tape machine can lead to a quadratic speedup, but any algorithm that runs in polynomial time under one model also does so on the other.) Any given
abstract machine will have a complexity class corresponding to the problems which can be solved in polynomial time on that machine.
Superpolynomial time
An algorithm is defined to take superpolynomial time if ''T''(''n'') is not bounded above by any polynomial; that is, if for every positive integer .
For example, an algorithm that runs for steps on an input of size requires superpolynomial time (more specifically, exponential time).
An algorithm that uses exponential resources is clearly superpolynomial, but some algorithms are only very weakly superpolynomial. For example, the
Adleman–Pomerance–Rumely primality test runs for time on -bit inputs; this grows faster than any polynomial for large enough , but the input size must become impractically large before it cannot be dominated by a polynomial with small degree.
An algorithm that requires superpolynomial time lies outside the
complexity class
In computational complexity theory, a complexity class is a set (mathematics), set of computational problems "of related resource-based computational complexity, complexity". The two most commonly analyzed resources are time complexity, time and s ...
P.
Cobham's thesis posits that these algorithms are impractical, and in many cases they are. Since the
P versus NP problem is unresolved, it is unknown whether
NP-complete
In computational complexity theory, NP-complete problems are the hardest of the problems to which ''solutions'' can be verified ''quickly''.
Somewhat more precisely, a problem is NP-complete when:
# It is a decision problem, meaning that for any ...
problems require superpolynomial time.
Quasi-polynomial time
Quasi-polynomial time algorithms are algorithms whose running time exhibits
quasi-polynomial growth, a type of behavior that may be slower than polynomial time but yet is significantly faster than
exponential time. The worst case running time of a quasi-polynomial time algorithm is
for some fixed When
this gives polynomial time, and for
it gives sub-linear time.
There are some problems for which we know quasi-polynomial time algorithms, but no polynomial time algorithm is known. Such problems arise in approximation algorithms; a famous example is the directed
Steiner tree problem, for which there is a quasi-polynomial time approximation algorithm achieving an approximation factor of
(''n'' being the number of vertices), but showing the existence of such a polynomial time algorithm is an open problem.
Other computational problems with quasi-polynomial time solutions but no known polynomial time solution include the
planted clique problem in which the goal is to
find a large clique in the union of a clique and a
random graph. Although quasi-polynomially solvable, it has been conjectured that the planted clique problem has no polynomial time solution; this planted clique conjecture has been used as a
computational hardness assumption to prove the difficulty of several other problems in computational
game theory
Game theory is the study of mathematical models of strategic interactions. It has applications in many fields of social science, and is used extensively in economics, logic, systems science and computer science. Initially, game theory addressed ...
,
property testing, and
machine learning
Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of Computational statistics, statistical algorithms that can learn from data and generalise to unseen data, and thus perform Task ( ...
.
The complexity class QP consists of all problems that have quasi-polynomial time algorithms. It can be defined in terms of
DTIME as follows.
:
Relation to NP-complete problems
In complexity theory, the unsolved
P versus NP
The P versus NP problem is a major unsolved problem in theoretical computer science. Informally, it asks whether every problem whose solution can be quickly verified can also be quickly solved.
Here, "quickly" means an algorithm exists that ...
problem asks if all problems in NP have polynomial-time algorithms. All the best-known algorithms for
NP-complete
In computational complexity theory, NP-complete problems are the hardest of the problems to which ''solutions'' can be verified ''quickly''.
Somewhat more precisely, a problem is NP-complete when:
# It is a decision problem, meaning that for any ...
problems like 3SAT etc. take exponential time. Indeed, it is conjectured for many natural NP-complete problems that they do not have sub-exponential time algorithms. Here "sub-exponential time" is taken to mean the second definition presented below. (On the other hand, many graph problems represented in the natural way by adjacency matrices are solvable in subexponential time simply because the size of the input is the square of the number of vertices.) This conjecture (for the k-SAT problem) is known as the
exponential time hypothesis.
Since it is conjectured that NP-complete problems do not have quasi-polynomial time algorithms, some inapproximability results in the field of
approximation algorithms
In computer science and operations research, approximation algorithms are efficient algorithms that find approximate solutions to optimization problems (in particular NP-hard problems) with provable guarantees on the distance of the returned sol ...
make the assumption that NP-complete problems do not have quasi-polynomial time algorithms. For example, see the known inapproximability results for the
set cover
The set cover problem is a classical question in combinatorics, computer science, operations research, and Computational complexity theory, complexity theory.
Given a Set (mathematics), set of elements (henceforth referred to as the Universe ( ...
problem.
Sub-exponential time
The term
sub-exponential time is used to express that the running time of some algorithm may grow faster than any polynomial but is still significantly smaller than an exponential. In this sense, problems that have sub-exponential time algorithms are somewhat more tractable than those that only have exponential algorithms. The precise definition of "sub-exponential" is not generally agreed upon, however the two most widely used are below.
First definition
A problem is said to be sub-exponential time solvable if it can be solved in running times whose logarithms grow smaller than any given polynomial. More precisely, a problem is in sub-exponential time if for every there exists an algorithm which solves the problem in time ''O''(2
''n''''ε''). The set of all such problems is the complexity class SUBEXP which can be defined in terms of
DTIME as follows.
:
This notion of sub-exponential is non-uniform in terms of ''ε'' in the sense that ''ε'' is not part of the input and each ε may have its own algorithm for the problem.
Second definition
Some authors define sub-exponential time as running times in
.
This definition allows larger running times than the first definition of sub-exponential time. An example of such a sub-exponential time algorithm is the best-known classical algorithm for integer factorization, the
general number field sieve, which runs in time about where the length of the input is . Another example was the
graph isomorphism problem, which the best known algorithm from 1982 to 2016 solved in However, at
STOC 2016 a quasi-polynomial time algorithm was presented.
It makes a difference whether the algorithm is allowed to be sub-exponential in the size of the instance, the number of vertices, or the number of edges. In
parameterized complexity, this difference is made explicit by considering pairs
of
decision problem
In computability theory and computational complexity theory, a decision problem is a computational problem that can be posed as a yes–no question on a set of input values. An example of a decision problem is deciding whether a given natura ...
s and parameters ''k''. SUBEPT is the class of all parameterized problems that run in time sub-exponential in ''k'' and polynomial in the input size ''n'':
:
More precisely, SUBEPT is the class of all parameterized problems
for which there is a
computable function
Computable functions are the basic objects of study in computability theory. Informally, a function is ''computable'' if there is an algorithm that computes the value of the function for every value of its argument. Because of the lack of a precis ...
with
and an algorithm that decides ''L'' in time
.
Exponential time hypothesis
The exponential time hypothesis (ETH) is that
3SAT
3sat (, ''Dreisat'') is a free-to-air German-language public service television channel. It is a generalist channel with a cultural focus and is jointly operated by public broadcasters from Germany ( ZDF, ARD), Austria ( ORF) and Switzerlan ...
, the satisfiability problem of Boolean formulas in
conjunctive normal form with at most three literals per clause and with ''n'' variables, cannot be solved in time 2
''o''(''n''). More precisely, the hypothesis is that there is some absolute constant such that 3SAT cannot be decided in time 2
''cn'' by any deterministic Turing machine. With ''m'' denoting the number of clauses, ETH is equivalent to the hypothesis that ''k''SAT cannot be solved in time 2
''o''(''m'') for any integer . The exponential time hypothesis implies
P ≠ NP.
Exponential time
An algorithm is said to be exponential time, if ''T''(''n'') is upper bounded by 2
poly(''n''), where poly(''n'') is some polynomial in ''n''. More formally, an algorithm is exponential time if ''T''(''n'') is bounded by ''O''(2
''n''''k'') for some constant ''k''. Problems which admit exponential time algorithms on a deterministic Turing machine form the complexity class known as
EXP Exp or EXP may stand for:
* Exponential function, in mathematics
* Expiry date of organic compounds like food or medicines
* Experience point
An experience point (often abbreviated as exp or XP) is a unit of measurement used in some tabletop r ...
.
:
Sometimes, exponential time is used to refer to algorithms that have ''T''(''n'') = 2
''O''(''n''), where the exponent is at most a linear function of ''n''. This gives rise to the complexity class
E.
:
Factorial time
An algorithm is said to be factorial time if ''T(n)'' is upper bounded by the
factorial function ''n!''. Factorial time is a subset of exponential time (EXP) because
for all
. However, it is not a subset of E.
An example of an algorithm that runs in factorial time is
bogosort, a notoriously inefficient sorting algorithm based on
trial and error. Bogosort sorts a list of ''n'' items by repeatedly
shuffling
Shuffling is a technique used to randomize a deck of playing cards, introducing an element of chance into card games. Various shuffling methods exist, each with its own characteristics and potential for manipulation.
One of the simplest shuf ...
the list until it is found to be sorted. In the average case, each pass through the bogosort algorithm will examine one of the ''n''! orderings of the ''n'' items. If the items are distinct, only one such ordering is sorted. Bogosort shares patrimony with the
infinite monkey theorem
The infinite monkey theorem states that a monkey hitting keys independently and at randomness, random on a typewriter keyboard for an infinity, infinite amount of time will almost surely type any given text, including the complete works of Willi ...
.
Double exponential time
An algorithm is said to be
double exponential time if ''T''(''n'') is upper bounded by 2
2poly(''n''), where poly(''n'') is some polynomial in ''n''. Such algorithms belong to the complexity class
2-EXPTIME.
:
Well-known double exponential time algorithms include:
* Decision procedures for
Presburger arithmetic
* Computing a
Gröbner basis
In mathematics, and more specifically in computer algebra, computational algebraic geometry, and computational commutative algebra, a Gröbner basis is a particular kind of generating set of an ideal in a polynomial ring K _1,\ldots,x_n/math> ove ...
(in the worst case)
*
Quantifier elimination
Quantifier elimination is a concept of simplification used in mathematical logic, model theory, and theoretical computer science. Informally, a quantified statement "\exists x such that ..." can be viewed as a question "When is there an x such ...
on
real closed field
In mathematics, a real closed field is a field F that has the same first-order properties as the field of real numbers. Some examples are the field of real numbers, the field of real algebraic numbers, and the field of hyperreal numbers.
Def ...
s takes at least double exponential time, and can be done in this time.
See also
*
L-notation
*
Space complexity
References
{{Use dmy dates, date=September 2019
Analysis of algorithms
Computational complexity theory
Computational resources
Time