V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Algorithm Complexity Reference

Time and space costs for all 92 translated learning pages

Complexity describes how resource use grows with the input. Use this table for comparison, then open a learning page to see what each operation actually means in motion.

92 learning pages
TopicTimeSpaceNotes
Quick SortAverage O(n log n)O(log n)In-place; worst case O(n^2) with consistently poor pivots.
Bubble SortO(n^2)O(1)Stable and in-place, but quadratic even when this basic version is already sorted.
Merge SortO(n log n)O(n)Stable with predictable time; the array implementation needs auxiliary storage.
Heap SortO(n log n)O(1)In-place with a worst-case O(n log n) bound, but not stable.
Counting SortO(n+k)O(k)Excellent for a compact integer range k; unsuitable when the range is very sparse.
Binary SearchO(log n)O(1)Requires sorted data and discards half of the candidate range per probe.
Lower and Upper BoundO(log n)O(1)Two boundary searches locate an equal range without a special found branch.
Fenwick TreeO(log n)O(n)Both point updates and prefix queries follow a lowbit chain.
Dijkstra's Shortest PathO((V+E) log V)O(V)Heap-based implementation for graphs with non-negative edge weights.
Kruskal's Minimum Spanning TreeO(E log E)O(V+E)Edge sorting dominates; disjoint-set operations are nearly constant amortized.
Prim's Minimum Spanning TreeO(E log V)O(V+E)A binary heap gives the sparse-graph bound; a dense implementation can use O(V^2).
Bellman-Ford Shortest PathsO(VE)O(V)Supports negative edges; one additional relaxation round detects a reachable negative cycle.
Topological SortO(V+E)O(V)Every vertex and edge is processed once; leftover vertices reveal a directed cycle.
0/1 KnapsackO(nW)O(nW)Pseudo-polynomial in capacity W; space can be reduced to O(W).
Edit DistanceO(mn)O(mn)The full table supports reconstruction; distance alone can be computed with O(n) space.
Longest Common SubsequenceO(mn)O(mn)Keeping the table makes the backward reconstruction path explicit.
Longest Increasing SubsequenceO(n^2)O(n)This DP exposes predecessors; a patience-sorting variant reaches O(n log n).
N-QueensO(N!)O(N)Conflict checks prune the search, while recursion stores at most one choice per column.
SubsetsO(n*2^n)O(n*2^n)There are 2^n outputs, and materializing each subset copies up to n values.
Maze Solving with DFSO(RC)O(RC)Each open cell is visited at most once; recursion and visited state can cover the grid.
KMP String MatchingO(n+m)O(m)The text pointer never moves backward; preprocessing builds the LPS table.
Rabin-Karp String MatchingAverage O(n+m)O(1)Character verification prevents collision errors; adversarial collisions can cause O(nm) time.
Manacher's Longest Palindromic SubstringO(n)O(n)Mirror reuse ensures expansion work advances the right boundary only linearly overall.
Sieve of EratosthenesO(N log log N)O(N)Starting at p^2 avoids work already performed by smaller prime factors.
Euclidean AlgorithmO(log min(a,b))O(1)Each remainder strictly reduces the pair until the second value reaches zero.
Convex HullO(n log n)O(n)Andrew's monotone chain is dominated by sorting the points.
Closest Pair of PointsO(n log n)O(n)Presorting and a y-ordered merge strip keep each recursion level linear.
ArrayAccess O(1); insert/delete O(n)O(n)Appending to a doubling dynamic array is amortized O(1).
Linked ListAccess O(n); known-node update O(1)O(n)Finding an insertion position still requires traversal unless its node is already known.
StackPush/pop O(1) amortizedO(n)A linked stack makes push and pop worst-case O(1); an array stack is usually more compact.
Queue and DequeEnd operations O(1)O(n)A circular array or linked representation avoids shifting the remaining values.
Binary Search TreeAverage O(log n); worst O(n)O(n)Self-balancing variants guarantee logarithmic height while preserving the BST order.
Binary HeapPeek O(1); insert/extract O(log n)O(n)Bottom-up heap construction takes O(n), despite each individual insertion costing O(log n).
Hash TableExpected O(1); worst O(n)O(n)A suitable hash function and controlled load factor keep expected chains or probe runs short.
GraphTraversal O(V+E)O(V+E)Adjacency lists store sparse graphs compactly; matrices trade O(V^2) space for direct edge tests.
TrieInsert/search O(L)O(total characters)Runtime depends on key length L rather than the number of stored words, at a potentially high pointer cost.
Disjoint Set UnionAmortized O(alpha(n))O(n)Path compression with union by size or rank is effectively constant time in practice.
LRU CacheGet/put O(1) expectedO(capacity)The hash table locates nodes while the linked list maintains recency without linear scans.
Skip ListExpected O(log n); worst O(n)Expected O(n)Random promotion gives logarithmic expected height without tree rotations.
Segment TreeQuery/update O(log n)O(n)Any associative aggregate can replace sum, and lazy propagation supports range updates.
B+ TreeSearch/update O(log_B n)O(n)A large branching factor minimizes storage-page reads, while linked leaves make ranges sequential.
Bloom FilterAdd/query O(k)O(m) bitsStandard Bloom filters allow false positives but never false negatives for inserted items.
Cocktail Shaker SortO(n^2)O(1)Stable and in-place; bidirectional passes help some inputs but do not change the quadratic bound.
Bitonic SortO(n log^2 n)O(1) auxiliaryThe data-independent network suits parallel hardware and normally expects a power-of-two length.
Selection SortO(n^2)O(1)It performs only O(n) swaps but is generally unstable and always makes quadratic comparisons.
Insertion SortAverage/worst O(n^2); best O(n)O(1)Stable, adaptive, and effective for small or nearly sorted inputs.
Binary Insertion SortO(n log n) comparisons; O(n^2) movesO(1)Binary search reduces comparisons, but contiguous insertion still requires shifting the suffix.
Shell SortGap-dependent; common worst O(n^2)O(1)In-place and often faster than insertion sort on medium arrays, but not stable.
Top-Down Merge SortO(n log n)O(n)Stable with predictable work; recursion adds O(log n) stack frames beside the merge buffer.
Three-Way Quick SortAverage O(n log n); worst O(n^2)Average O(log n)Three-way partitioning is especially effective when many input values are equal.
Dual-Pivot Quick SortAverage O(n log n); worst O(n^2)Average O(log n)Good partitions reduce recursion depth and can improve cache behavior, but the worst case remains quadratic.
Radix SortO(d(n+k))O(n+k)Avoids comparisons when keys have d bounded digits over radix k; every digit pass must be stable.
Bucket SortAverage O(n+k); worst O(n^2)O(n+k)Near-linear behavior assumes values distribute reasonably evenly across k buckets.
Floyd-WarshallO(V^3)O(V^2)Handles negative edges but not negative cycles; the matrix is practical for dense, moderate graphs.
Strongly Connected ComponentsO(V+E)O(V)Each vertex enters and leaves the Tarjan stack once, and every directed edge is inspected once.
2-SATO(V+E)O(V+E)A formula is impossible exactly when a variable and its negation share one strongly connected component.
Maximum FlowO(EF) for integer Ford-FulkersonO(V+E)The bound depends on maximum flow F; Edmonds-Karp or Dinic gives stronger path-selection guarantees.
Bipartite MatchingO(VE)O(V)The DFS-based Hungarian method finds maximum cardinality matching; weighted assignment needs a different variant.
Lowest Common AncestorBuild O(V log V); query O(log V)O(V log V)Binary lifting answers many static-tree ancestor and distance queries efficiently.
Eulerian PathO(V+E)O(V+E)Connectivity and odd-degree conditions determine whether an undirected Eulerian trail exists.
Unbounded KnapsackO(nW)O(nW)A one-dimensional table uses O(W) space when capacities iterate upward for reusable items.
Coin ChangeO(nA)O(A)The amount A defines the pseudo-polynomial state space; unreachable states remain infinite.
Stone MergingO(n^3)O(n^2)Each interval considers all split points; prefix sums make its merge cost O(1).
Traveling Salesperson DPO(n^2 2^n)O(n 2^n)Held-Karp is exponential but far smaller than checking all n! tours.
Tree Dynamic ProgrammingO(n)O(n)Each edge contributes once to a constant number of states; recursion depth follows tree height.
Digit DPO(d × states × radix)O(d × states)Memoization collapses all prefixes that share position, constraint state, and tightness.
Rerooting DPO(n)O(n)A local reroot transition turns one rooted result into answers for every possible root.
PermutationsO(n × n!)O(n)There are n! outputs, and writing each arrangement requires O(n) work.
Combination SumExponential in target depthO(target/min candidate)Output size dominates, while sorted candidates permit early pruning and canonical ordering.
Number of IslandsO(RC)O(RC)Every grid cell is visited at most once; iterative traversal can replace recursion.
Word SearchO(RC × 4^L)O(L)Character checks and no-revisit rules prune the worst-case branching for word length L.
Sudoku SolverWorst O(9^m)O(m)Constraint checks and good cell ordering drastically reduce the search below the m-empty-cell bound.
A* SearchWorst O((V+E) log V)O(V)An admissible consistent heuristic preserves optimality and often explores far fewer states than Dijkstra.
Boyer-Moore String MatchingOften sublinear; worst O(nm)O(m+alphabet)Large safe shifts make it excellent in practice, while preprocessing depends on the chosen heuristics.
Suffix ArrayO(n log^2 n)O(n)Comparison sorting in each doubling round gives this bound; radix ranking can reach O(n log n).
LCP ArrayO(n)O(n)The reused prefix length decreases by at most one per text position, bounding total comparisons.
Aho-Corasick AutomatonO(P+n+z)O(P × alphabet) denseP is total pattern length and z is output count; sparse transitions reduce memory.
Z FunctionO(n)O(n)Comparisons that extend the Z-box move its right boundary forward, so total extension work is linear.
Linear SieveO(N)O(N)The break rule prevents a composite from being produced by more than its smallest prime factor.
Binary ExponentiationO(log exponent)O(1)Modular reduction can be applied after every multiplication without changing the recurrence.
Extended Euclidean AlgorithmO(log min(a,b))O(1) iterativeBezout coefficients provide modular inverses whenever the gcd is one.
Chinese Remainder TheoremO(k log M)O(k)The direct form assumes pairwise coprime moduli; generalized merging checks gcd compatibility.
Euler's Totient FunctionO(sqrt n) trial divisionO(1)Each distinct prime factor p multiplies the running result by (1 - 1/p).
Miller-Rabin Primality TestO(k log^3 n)O(1)A fixed witness set is deterministic for bounded machine integers; random witnesses give tiny error probability.
Fast Fourier TransformO(n log n)O(n)Pointwise multiplication between forward and inverse transforms yields fast polynomial convolution.
Pollard's Rho FactorizationExpected O(n^1/4)O(1)Random restarts handle unlucky cycles; primality testing separates terminal factors.
Rotating CalipersO(n) after the hullO(1)Monotone orientation changes ensure each pointer makes at most one full circuit.
Line Segment IntersectionO(1)O(1)Robust implementations must handle zero orientation and numeric precision explicitly.
Bentley-Ottmann Sweep LineO((n+k) log n)O(n+k)The output-sensitive bound reports k intersections without comparing every pair of n segments.
Search in a Rotated Sorted ArrayO(log n)O(1)The logarithmic guarantee assumes distinct values; duplicates can obscure which half is sorted.
Binary Search on the AnswerO(check × log range)O(1) beyond the checkCorrectness depends on a monotone predicate and a precisely defined first-true or last-true boundary.
Ternary SearchO(log range)O(1)The objective must be unimodal; continuous search stops at a chosen precision.