Hubbry Logo
Time complexityTime complexityMain
Open search
Time complexity
Community hub
Time complexity
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Contribute something
Time complexity
Time complexity
from Wikipedia
Graphs of functions commonly used in the analysis of algorithms, showing the number of operations N as the result of input size n for each function

In theoretical computer science, the time complexity is the computational complexity that describes the amount of computer time it takes to run an algorithm. 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.[1]: 226  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 n 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

[edit]

The following table summarizes some classes of commonly encountered time complexities. In the table, poly(x) = xO(1), i.e., polynomial in x.

Name Complexity class Time complexity (O(n)) Examples of running times Example algorithms
constant time 10 Finding the median value in a sorted array of numbers. Calculating (−1)n.
inverse Ackermann time Amortized time per operation using a disjoint set
iterated logarithmic time Distributed coloring of cycles
log-logarithmic Amortized time per operation using a bounded priority queue[2]
logarithmic time DLOGTIME , Binary search
polylogarithmic time
fractional power where , Range searching in a k-d tree
linear time n, Finding the smallest or largest item in an unsorted array. Kadane's algorithm. Linear search.
"n log-star n" time Seidel's polygon triangulation algorithm.
linearithmic time , Fastest possible comparison sort. Fast Fourier transform.
quasilinear time Multipoint polynomial evaluation
quadratic time Bubble sort. Insertion sort. Direct convolution
cubic time Naive multiplication of two matrices. Calculating partial correlation.
polynomial time P , Karmarkar's algorithm for linear programming. AKS primality test[3][4]
quasi-polynomial time QP , Best-known O(log2n)-approximation algorithm for the directed Steiner tree problem, best known parity game solver,[5] best known graph isomorphism algorithm
sub-exponential time
(first definition)
SUBEXP for all Contains BPP unless EXPTIME (see below) equals MA.[6]
sub-exponential time
(second definition)
Best classical algorithm for integer factorization

formerly-best algorithm for graph isomorphism

exponential time
(with linear exponent)
E , Solving the traveling salesman problem using dynamic programming
factorial time Solving the traveling salesman problem via brute-force search
exponential time EXPTIME , Solving matrix chain multiplication via brute-force search
double exponential time 2-EXPTIME Deciding the truth of a given statement in Presburger arithmetic

Constant time

[edit]

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 a and b 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 t such that the time required is always at most t.

Logarithmic time

[edit]

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 T.

Algorithms taking logarithmic time are commonly found in operations on binary trees 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 n 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 n is of the order of n.

An example of logarithmic time is given by dictionary search. Consider a dictionary D which contains n entries, sorted in alphabetical order. We suppose that, for , one may access the kth entry of the dictionary in a constant time. Let denote this kth entry. Under these hypotheses, the test to see if a word w is in the dictionary may be done in logarithmic time: consider , where denotes the floor function. If --that is to say, the word w is exactly in the middle of the dictionary--then we are done. Else, if --i.e., if the word w 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

[edit]

An algorithm is said to run in polylogarithmic time if its time is for some constant k. Another way to write this is .

For example, matrix chain ordering can be solved in polylogarithmic time on a parallel random-access machine,[7] and a graph can be determined to be planar in a fully dynamic way in time per insert/delete operation.[8]

Sub-linear time

[edit]

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.[9] This type of sublinear time algorithm is closely related to property testing and statistics.

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, 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.[10]

Linear time

[edit]

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 c such that the running time is at most for every input of size n. 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

[edit]

An algorithm is said to run in quasilinear time (also referred to as log-linear time) if for some positive constant k;[11] linearithmic time is the case .[12] 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, introsort, binary tree sort, smoothsort, patience sorting, etc. in the worst case
  • Fast Fourier transforms,
  • Monge array calculation,

In many cases, the running time is simply the result of performing a operation n times (for the notation, see Big O notation § Family of Bachmann–Landau notations). For example, binary tree sort creates a binary tree by inserting each element of the n-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. They also frequently arise from the recurrence relation .

Sub-quadratic time

[edit]

An algorithm is said to be subquadratic time if .

For example, simple, comparison-based sorting algorithms 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

[edit]

An algorithm is said to be of polynomial time if its running time is upper bounded by a polynomial expression in the size of the input for the algorithm, that is, T(n) = O(nk) for some positive constant k.[1][13] Problems for which a deterministic polynomial-time algorithm exists belong to the complexity class P, which is central in the field of computational complexity theory. Cobham's thesis states that polynomial time is a synonym for "tractable", "feasible", "efficient", or "fast".[14]

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, 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

[edit]

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 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

[edit]

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 c.

For example, an algorithm that runs for 2n steps on an input of size n 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 nO(log log n) time on n-bit inputs; this grows faster than any polynomial for large enough n, 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 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 problems require superpolynomial time.

Quasi-polynomial time

[edit]

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, property testing, and machine learning.[15]

The complexity class QP consists of all problems that have quasi-polynomial time algorithms. It can be defined in terms of DTIME as follows.[16]

Relation to NP-complete problems

[edit]

In complexity theory, the unsolved P versus NP problem asks if all problems in NP have polynomial-time algorithms. All the best-known algorithms for NP-complete 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.[17] Since it is conjectured that NP-complete problems do not have quasi-polynomial time algorithms, some inapproximability results in the field of approximation algorithms 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 problem.

Sub-exponential time

[edit]

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,[18] however the two most widely used are below.

First definition

[edit]

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 ε > 0 there exists an algorithm which solves the problem in time O(2nε). The set of all such problems is the complexity class SUBEXP which can be defined in terms of DTIME as follows.[6][19][20][21]

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

[edit]

Some authors define sub-exponential time as running times in .[17][22][23] 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 n. 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.[24]

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 problems 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:[25]

More precisely, SUBEPT is the class of all parameterized problems for which there is a computable function with and an algorithm that decides L in time .

Exponential time hypothesis

[edit]

The exponential time hypothesis (ETH) is that 3SAT, 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 2o(n). More precisely, the hypothesis is that there is some absolute constant c > 0 such that 3SAT cannot be decided in time 2cn by any deterministic Turing machine. With m denoting the number of clauses, ETH is equivalent to the hypothesis that kSAT cannot be solved in time 2o(m) for any integer k ≥ 3.[26] The exponential time hypothesis implies P ≠ NP.

Exponential time

[edit]

An algorithm is said to be exponential time, if T(n) is upper bounded by 2poly(n), where poly(n) is some polynomial in n. More formally, an algorithm is exponential time if T(n) is bounded by O(2nk) for some constant k. Problems which admit exponential time algorithms on a deterministic Turing machine form the complexity class known as EXP.

Sometimes, exponential time is used to refer to algorithms that have T(n) = 2O(n), where the exponent is at most a linear function of n. This gives rise to the complexity class E.

Factorial time

[edit]

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 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.

Double exponential time

[edit]

An algorithm is said to be double exponential time if T(n) is upper bounded by 22poly(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:

See also

[edit]

References

[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Time complexity is a fundamental concept in that quantifies the amount of computational time required by an to process an input of a given size, typically expressed as a function of the input length nn. It focuses on the worst-case scenario, where the running time T(n)T(n) represents the maximum number of steps a deterministic takes to halt on any input of length nn. The measurement of time complexity involves counting basic operations, such as comparisons or assignments, performed during execution, rather than actual clock time, to ensure hardware-independent analysis. Different cases are considered: ** captures the maximum time over all inputs of size nn, average-case evaluates the expected time assuming a over inputs, and best-case denotes the minimum time for favorable inputs. For instance, algorithms like exhibit O(n)O(n) worst-case time, while more efficient structures like binary search achieve O(logn)O(\log n). Asymptotic notation, particularly (OO), provides an upper bound on the growth rate of the running time, ignoring constant factors and lower-order terms to highlight scalability for large nn. Complementary notations include Big Omega (Ω\Omega) for lower bounds and Big Theta (Θ\Theta) for tight bounds, enabling precise comparisons of algorithm efficiency. Common complexities range from constant O(1)O(1) for fixed-time operations to exponential O(2n)O(2^n) for intractable problems. Time complexity analysis is essential for algorithm design and selection, influencing the classification of problems into complexity classes such as , the set of decision problems solvable in polynomial time (i.e., O(nk)O(n^k) for some constant kk). It underpins by revealing resource trade-offs and proving hierarchies, like the time hierarchy theorem stating that more time allows solving harder problems. In practice, it guides optimizations in to ensure for real-world data sizes.

Fundamentals

Definition and Measurement

Time complexity refers to the amount of computational resources, specifically the number of basic operations, required by an to process an input of size nn. It is formally defined as a function T(n)T(n), which quantifies the number of steps or operations needed to complete the . This measure captures the algorithm's efficiency in terms of time, independent of hardware specifics, by focusing on the growth rate relative to input size. Analysis typically considers the worst case (maximum resources needed), average case (expected resources over random inputs), or best case (minimum resources). To measure time complexity, one counts the primitive operations executed by , such as assignments, comparisons, arithmetic operations, or control transfers, each assumed to take constant time. For instance, in analysis, each line or statement involving these primitives contributes to the total count, with the overall T(n)T(n) derived from the dominant terms in loops or recursions. Constant factors and lower-order terms are disregarded to emphasize for large nn, as these details vary by but do not affect the asymptotic behavior. The concept originated in the 1960s through foundational works on resource-bounded . Alan Cobham's 1965 paper introduced the idea of intrinsic computational difficulty, proposing polynomial-time as a machine-independent measure of feasible . Independently, Juris Hartmanis and Richard E. Stearns formalized time complexity in their 1965 paper, defining it via steps to classify computable functions by resource demands. For example, accessing an element in an by index requires a fixed number of operations regardless of array size, while sorting an array of nn elements involves a variable number of comparisons and swaps that grows with nn. These illustrate how T(n)T(n) can remain bounded or scale polynomially.

Asymptotic Notation

Asymptotic notation provides a mathematical framework for describing the growth rates of functions, particularly the running time T(n) of algorithms as the input size n tends to . By focusing on dominant terms and ignoring constants and lower-order factors, these notations enable comparisons of algorithm efficiency without precise measurements. The most common notations—Big O, Big Θ, and Big Ω—offer upper, tight, and lower bounds, respectively, while their "little" counterparts provide stricter inequalities. These tools originated in but were popularized in for analyzing . Big O notation, denoted as T(n)=O(f(n))T(n) = O(f(n)), specifies an asymptotic upper bound on the growth rate of T(n). Formally, T(n)=O(f(n))T(n) = O(f(n)) if there exist constants c>0c > 0 and n0>0n_0 > 0 such that 0T(n)cf(n)0 \leq T(n) \leq c \cdot f(n) for all nn0n \geq n_0. This definition captures the worst-case scenario, ensuring that T(n) grows no faster than a constant multiple of f(n) for sufficiently large n. An equivalent formulation uses the limit superior: T(n)=O(f(n))T(n) = O(f(n)) if lim supnT(n)f(n)<\limsup_{n \to \infty} \frac{T(n)}{f(n)} < \infty. For instance, constant-time operations like array access are analyzed as O(1)O(1). The Theta notation, T(n)=Θ(f(n))T(n) = \Theta(f(n)), provides a tight bound by combining upper and lower estimates: T(n)=O(f(n))T(n) = O(f(n)) and T(n)=Ω(f(n))T(n) = \Omega(f(n)). Formally, there exist constants c1>0c_1 > 0, c2>0c_2 > 0, and n0>0n_0 > 0 such that c1f(n)T(n)c2f(n)c_1 \cdot f(n) \leq T(n) \leq c_2 \cdot f(n) for all nn0n \geq n_0. This indicates that T(n) grows at the same rate as f(n), up to constant factors. The limit form is limnT(n)f(n)=L\lim_{n \to \infty} \frac{T(n)}{f(n)} = L where 0<L<0 < L < \infty. Theta is particularly useful for average- or best-case analyses where bounds coincide. Big Ω notation, T(n)=Ω(f(n))T(n) = \Omega(f(n)), describes a lower bound on growth: T(n)=Ω(f(n))T(n) = \Omega(f(n)) if there exist constants c>0c > 0 and n0>0n_0 > 0 such that T(n)cf(n)T(n) \geq c \cdot f(n) for all nn0n \geq n_0. Equivalently, f(n)=O(T(n))f(n) = O(T(n)), or lim infnT(n)f(n)>0\liminf_{n \to \infty} \frac{T(n)}{f(n)} > 0. This ensures T(n) grows at least as fast as f(n), highlighting minimum resource requirements. For linear scans, such as traversing an of size n, the time is Ω(n)\Omega(n). Little-o and little-ω notations introduce stricter bounds without constant factors. Little-o, T(n)=o(f(n))T(n) = o(f(n)), means limnT(n)f(n)=0\lim_{n \to \infty} \frac{T(n)}{f(n)} = 0, indicating T(n) grows strictly slower than f(n). For example, n=o(nlogn)n = o(n \log n) since limnnnlogn=0\lim_{n \to \infty} \frac{n}{n \log n} = 0, showing linear growth lags behind quasilinear. Conversely, little-ω, T(n)=ω(f(n))T(n) = \omega(f(n)), satisfies limnf(n)T(n)=0\lim_{n \to \infty} \frac{f(n)}{T(n)} = 0, or f(n)=o(T(n))f(n) = o(T(n)), for strict lower bounds. These are less common in basic analyses but refine comparisons of subdominant terms. To illustrate derivation, consider an with two nested loops, each from 1 to n, executing a constant-time operation inside:

for i in 1 to n: for j in 1 to n: # constant time operation

for i in 1 to n: for j in 1 to n: # constant time operation

The inner loop runs n times per outer , yielding i=1nn=n2\sum_{i=1}^n n = n^2 total operations. Since n21n2n^2 \leq 1 \cdot n^2 for n ≥ 1, this proves T(n)=O(n2)T(n) = O(n^2). More generally, summations like i=1ni=n(n+1)2=O(n2)\sum_{i=1}^n i = \frac{n(n+1)}{2} = O(n^2) bound quadratic growth.

Sublinear Time Complexities

Constant Time

Constant time complexity, denoted as O(1)O(1), refers to algorithms whose execution time remains fixed and independent of the input size nn. In such cases, the number of basic operations performed is bounded by a constant, regardless of how large the input grows. This is formally expressed by the time function T(n)=cT(n) = c, where cc is a positive constant representing the fixed number of steps. Representative examples of O(1)O(1) operations include direct array indexing, where accessing an element at a given index requires a constant number of steps to compute the . Similarly, hash table lookups achieve O(1)O(1) average-case performance under ideal hashing conditions, as the key is mapped directly to a storage location with a fixed number of comparisons. Simple arithmetic operations, such as adding two numbers, also fall into this category, executing in a bounded time irrespective of size in standard implementations. In practice, constant time algorithms offer excellent for handling large datasets, as their does not degrade with increasing input volume, making them preferable in real-time systems where predictable execution is essential. However, hardware constraints, such as CPU cache behavior, can introduce variations in the actual runtime even for O(1)O(1) operations; for instance, cache misses may cause timing discrepancies that affect security-sensitive applications requiring strict constant-time guarantees. A common misconception is that O(1)O(1) implies uniformly fast execution across all implementations, overlooking how factors like cache effects or optimizations can alter the hidden constant cc.

Logarithmic Time

Logarithmic time complexity describes algorithms whose worst-case running time grows proportionally to the logarithm of the input size nn, formally expressed as O(logn)O(\log n). This class of complexity arises in scenarios where the problem size is repeatedly divided by a constant factor, typically 2 in binary-based operations, leading to a number of steps that scales logarithmically rather than linearly with nn. In computer science, the logarithm is conventionally base-2 (log2n\log_2 n), reflecting the binary nature of data representation and operations like bit shifts or halvings. A prominent example of logarithmic time is binary search, which efficiently locates an element in a sorted by repeatedly dividing the search interval in half. Starting with an of size nn, each iteration compares the target to the middle element and discards half the remaining elements, reducing the problem size exponentially until the target is found or confirmed absent. This process requires at most log2(n+1)\lceil \log_2 (n+1) \rceil comparisons in the worst case. Another key example involves operations on balanced binary search trees (BSTs), such as search, insertion, or deletion, which take time proportional to the tree's height; in a balanced BST with nn nodes, the height is O(logn)O(\log n), ensuring logarithmic performance for these operations. The logarithmic bound in these algorithms derives from a modeling the divide-and-conquer process. For binary search, the running time T(n)T(n) satisfies the recurrence T(n)=T(n2)+Θ(1),T(n) = T\left(\frac{n}{2}\right) + \Theta(1), where Θ(1)\Theta(1) accounts for the constant-time midpoint computation and comparison. Unrolling this recurrence yields T(n)=Θ(logn)T(n) = \Theta(\log n), as the depth of is the number of halvings needed to reduce nn to 1, which is log2n\log_2 n. Similarly, for balanced BST operations, the height hh follows h=1+h/2h = 1 + h/2 on average, solving to h=O(logn)h = O(\log n). The of logarithmic time is independent of the logarithm's base, as changing from base bb to base kk (both greater than 1) introduces only a constant factor: logbn=logknlogkb\log_b n = \frac{\log_k n}{\log_k b}. Thus, O(logbn)=O(logkn)O(\log_b n) = O(\log_k n) for any valid bases, allowing flexibility in notation without altering the . This property underscores why logn\log n without a specified base is standard in big-O notation for such algorithms.

Linear and Quasilinear Time

Linear Time

Linear time complexity, denoted as O(n)O(n), refers to algorithms whose running time is directly proportional to the input size nn, meaning the number of operations grows linearly as nn increases. This makes linear time a fundamental baseline for efficiency in design, as it ensures predictable scaling without excessive overhead for small to moderate inputs. The time complexity function for such algorithms satisfies T(n)=O(n)T(n) = O(n), often realized through a single loop that iterates exactly nn times or a constant multiple thereof. For instance, a simple for-loop from 1 to nn performs nn iterations, each taking constant time, yielding overall linear time. Representative examples include computing the sum of elements in an of size nn, which requires one pass to accumulate the total, and , which scans the array sequentially until finding a target element or reaching the end. These operations are straightforward and commonly used in practice for tasks like or element lookup in unsorted collections. Linear time algorithms are feasible and efficient for moderate input sizes, such as nn up to millions on modern hardware, but they become a performance bottleneck for very large datasets, like those in processing, where even linear growth can lead to prohibitive execution times. They often pair with O(1)O(1) extra , relying on in-place modifications or fixed auxiliary variables without requiring additional storage proportional to nn.

Quasilinear Time

Quasilinear time complexity refers to algorithms with a running time of O(nlogn)O(n \log n), where nn is the input size and the logarithm is typically base 2, though the base affects only a constant factor. This bound arises in scenarios where operations scale linearly with the input but include an additional logarithmic multiplier, often due to divide-and-conquer strategies or tree-based structures. The term "quasilinear" highlights its proximity to linear time while acknowledging the superlinear growth from the logn\log n term. This complexity class is particularly prevalent in comparison-based sorting algorithms, where the information-theoretic lower bound establishes that any such algorithm requires at least Ω(nlogn)\Omega(n \log n) comparisons in the worst case. The bound derives from the need to distinguish among n!n! possible input permutations using binary decisions from comparisons; since log2(n!)=Θ(nlogn)\log_2(n!) = \Theta(n \log n) by (n!2πn(n/e)nn! \approx \sqrt{2\pi n} (n/e)^n
Add your contribution
Related Hubs
Contribute something
User Avatar
No comments yet.