AntInLoop

Master Algorithms & Data Structures Visually

AntInLoop is a free interactive computer science platform featuring 95 algorithm visualizers, 26 data structure visualizers, 84 step-prediction games, narrated walkthroughs in 4 languages (English, Arabic, Russian, Chinese), and code implementations in C++, Python, Java, and JavaScript.

Popular Algorithms

  • Bubble Sort Algorithm — Bubble Sort is a simple, stable, in-place comparison sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. (Demo | Code)
  • Insertion Sort Algorithm — Insertion Sort is a stable, in-place comparison sorting algorithm that builds a sorted prefix one element at a time by shifting larger elements to the right. (Demo | Code)
  • Selection Sort Algorithm — Selection Sort is an in-place comparison sorting algorithm that repeatedly selects the smallest element from the unsorted region and swaps it into the next sorted position. (Demo | Code)
  • Heap Sort Algorithm — Heap Sort is an in-place comparison sorting algorithm that builds a binary max-heap in O(n) time and repeatedly extracts the maximum element to achieve guaranteed O(n log n) time. (Demo | Code)
  • Merge Sort Algorithm — Merge Sort is a stable, divide-and-conquer sorting algorithm with a guaranteed O(n log n) time complexity in all cases, ideal for linked lists and external sorting. (Demo | Code)
  • Bucket Sort Algorithm — Bucket Sort is a distribution-based sorting algorithm that partitions elements into ordered buckets, sorts each bucket individually, and concatenates them for O(n + k) average time. (Demo | Code)
  • Counting Sort Algorithm — Counting Sort is a stable, non-comparison integer sorting algorithm that runs in linear O(n + k) time when input keys fall within a known, bounded integer range. (Demo | Code)
  • Radix Sort Algorithm — Radix Sort is a non-comparison sorting algorithm that sorts integers or fixed-length strings digit by digit using a stable subroutine such as Counting Sort. (Demo | Code)
  • Binary Search on the Answer (Parametric Search) — Binary Search on the Answer transforms optimization problems ("minimize the maximum" or "maximize the minimum") into O(log Range) monotonic feasibility checks. (Demo | Code)
  • Linear Search Algorithm — Linear Search sequentially scans each element of a list until it finds the target value or reaches the end, requiring no prior sorting. (Demo | Code)
  • Binary Search Algorithm — Binary Search is a divide-and-conquer search algorithm that halves the search interval on every step to locate a target or boundary in a sorted or monotonic domain in O(log n) time. (Demo | Code)
  • Ternary Search Algorithm — Ternary Search divides a search interval into three parts using two midpoints, primarily used to find the maximum or minimum of a unimodal function in O(log n) time. (Demo | Code)
  • Exponential Search Algorithm — Exponential Search finds a target in a sorted or unbounded array in O(log i) time by doubling the probe index until passing the target, then running Binary Search on the final bracket. (Demo | Code)
  • Jump Search Algorithm — Jump Search locates a target in a sorted array by jumping ahead in fixed blocks of size sqrt(n) and then performing a linear scan within the candidate block. (Demo | Code)
  • Fibonacci Search Algorithm — Fibonacci Search locates a target in a sorted array in O(log n) time by dividing the search range using Fibonacci numbers, using only addition and subtraction instead of division. (Demo | Code)
  • Interpolation Search Algorithm — Interpolation Search improves on Binary Search for uniformly distributed sorted arrays by estimating the target position proportionally, achieving O(log log n) average time. (Demo | Code)

Popular Data Structures

  • disjoint-set — A Disjoint Set (DSU) partitions elements into non-overlapping sets and extends cleanly to Weighted/Potential DSU (tracking relative offsets or parity) and Rollback DSU (supporting undo).
  • adjacency-list — An Adjacency List stores a dynamic list of outgoing neighbors for each vertex, using optimal O(V + E) memory and powering nearly all modern sparse-graph algorithms.
  • adjacency-matrix — An Adjacency Matrix stores a graph as a V x V grid where entry (u, v) holds the edge indicator or weight, giving O(1) edge lookups and powering Floyd–Warshall and matrix walk counting.
  • binomial-heap — A Binomial Heap is a mergeable priority queue composed of a forest of heap-ordered Binomial Trees mirroring the binary representation of n, supporting O(log n) merge and O(1) amortized insert.
  • fibonacci-heap — A Fibonacci Heap is a lazy mergeable priority queue using circular doubly linked root lists and cascading cuts to achieve O(1) amortized insert, merge, and decrease-key, and O(log n) amortized extract-min.
  • bloom-filter — A Bloom Filter is a space-efficient probabilistic bit-array data structure that tests set membership in O(k) time with zero false negatives and a tunable, low false-positive rate.
  • hash-set — A Hash Set stores unique elements backed by a hash table, providing O(1) expected membership testing, insertion, and deletion for deduplication and fast lookups.
  • skip-list — A Skip List is a probabilistic multi-level linked list that adds randomized express lanes on top of a sorted linked list, achieving O(log n) expected search, insert, and delete without tree rotations.
  • b-tree — A B-Tree is a self-balancing multi-way search tree that packs hundreds of sorted keys per node to match disk pages and CPU cache lines, guaranteeing shallow O(log_t n) height for databases and filesystems.
  • red-black-tree — A Red-Black Tree is a self-balancing Binary Search Tree using 1 color bit (red/black) per node to guarantee height <= 2 log2(n + 1) and O(log n) worst-case search, insertion, and deletion with O(1) rotations.
  • avl-tree — An AVL Tree is a strictly height-balanced Binary Search Tree where every node's left and right subtree heights differ by at most 1, guaranteeing O(log n) worst-case search, insertion, and deletion via rotations.
  • suffix-tree — A Suffix Tree is a compressed Trie of all suffixes of a string, built in linear O(n) time via Ukkonen's algorithm to answer pattern matching and repeated substring queries in O(m) time.

Interactive Algorithm Games

  • BFS Game — Practice Breadth-First Search by predicting the next visited node in real time using FIFO queue traversal rules.
  • DFS Game — Practice Depth-First Search by predicting the next visited node and recursive backtracking steps across graphs.
  • Dijkstra's Algorithm Game — Master Dijkstra's shortest path algorithm by predicting priority-queue extractions and edge relaxations on weighted graphs.
  • Floyd-Warshall Game — Practice all-pairs shortest paths by predicting which distance matrix entries update at each intermediate vertex k.
  • KMP String Matching Game — Master Knuth-Morris-Pratt pattern matching and the LPS prefix table by predicting matches and fallback jumps.
  • Sieve of Eratosthenes Game — Practice prime number generation by predicting the next composite multiple crossed out by the Sieve of Eratosthenes.
  • Suffix Array Game — Learn suffix array construction by predicting the lexicographical ordering of string suffixes step by step.
  • Sparse Table Game — Practice building a Sparse Table and answering O(1) Range Minimum Queries using overlapping power-of-two intervals.
  • Union-Find (DSU) Game — Practice Disjoint Set Union (DSU) operations including path compression and union by rank interactively.
  • GCD Game — Practice the Euclidean Algorithm by predicting every modulo transition when computing the Greatest Common Divisor.
  • LCM Game — Two-phase interactive math game: compute GCD via the Euclidean algorithm, then derive the Least Common Multiple.
  • Binary Search Game — Practice Binary Search by picking the exact midpoint index and halving the sorted search range in O(log n) steps.
  • Merge Sort Game — Master the Merge Sort combine step by merging two sorted subarrays element by element with stable tie-breaking.
  • QuickSort Partition Game — Step through QuickSort Lomuto partitioning by predicting swaps against the pivot and its final landing index.
  • Topological Sort Game — Master Topological Sort using Kahn's Algorithm on an interactive DAG by picking zero-in-degree nodes.
  • Kruskal's MST Game — Master Kruskal's Minimum Spanning Tree algorithm by deciding whether to accept or skip each sorted edge to avoid cycles.
  • Prim's MST Game — Grow a Minimum Spanning Tree from a start vertex using Prim's algorithm by selecting the cheapest frontier edge.
  • 0/1 Knapsack DP Game — Fill the 2D 0/1 Knapsack Dynamic Programming table cell by cell by comparing Skip vs. Take transitions.
  • LCS Dynamic Programming Game — Master Longest Common Subsequence (LCS) by filling the 2D DP grid using diagonal matches and max(top, left) mismatches.
  • Activity Selection Game — Practice Greedy Activity Selection on an interactive timeline by repeatedly picking the earliest-finishing compatible interval.
  • Huffman Coding Game — Build an optimal Huffman Coding tree by merging the two lowest-frequency nodes at every step.
  • Binary Min-Heap Game — Restore the Binary Min-Heap invariant using Sift-Up and Sift-Down swaps across a live tree and array.
  • Fast Exponentiation Game — Compute a^b mod m in O(log b) steps by inspecting the exponent binary bits and choosing Square vs. Multiply & Square.
  • Trie (Insert & Query) Game — Practice Trie insert (prefix sharing & isEndOfWord) and search vs. startsWith queries interactively on a live prefix tree.
  • Segment Tree Game — Master O(log n) canonical Range Sum Queries and bottom-up Point Updates on an interactive binary segment tree.
  • Bellman-Ford Relaxation Game — Relax directed edges with negative weights across Bellman-Ford passes and detect negative weight cycles.
  • A* Search Pathfinding Game — Expand the lowest f(n) = g(n) + h(n) frontier cell on a grid with obstacles using Manhattan distance heuristics.
  • Edit Distance DP Game — Fill the 2D Levenshtein Edit Distance table cell by cell by choosing Match, Insert, Delete, or Substitute.
  • Two Pointers Pair Sum Game — Practice the Two Pointers technique by converging Left and Right pointers on a sorted array to find target pair sums in O(n).
  • Fenwick Tree (BIT) Game — Master Binary Indexed Tree lowest-set-bit jumps (i -= i & -i and i += i & -i) for O(log n) prefix queries and point updates.
  • BST (Search & Insert) Game — Navigate left vs. right branches using the BST ordering invariant to search keys and insert into empty child slots.
  • AVL Tree Rotation Game — Inspect node heights and balance factors to diagnose LL, RR, LR, or RL imbalances and rebalance an AVL Tree.
  • Z-Algorithm Z-Box Game — Compute Z[i] prefix match lengths while tracking the sliding [L, R] Z-box window in linear O(n) time.
  • Fractional Knapsack Game — Select items by highest value-to-weight ratio and take whole items or exact fractional slices to maximize value.
  • LIS Patience Sorting Game — Maintain the O(n log n) Patience Sorting tails array by appending larger elements or replacing the lower_bound slot.
  • Aho-Corasick Automaton Game — Step through trie goto edges and BFS failure links to match multiple dictionary patterns in a single linear pass.
  • Manacher's Palindrome Game — Use mirror index 2C - i, right boundary R, and character expansion to compute palindrome radii in linear O(n) time.
  • Binomial Heap Merge Game — Merge binomial forests by linking equal-degree binomial trees like binary addition while preserving min-heap root order.
  • Sliding Window Challenge — Master the Sliding Window technique by deciding when to expand R vs. shrink L to minimize subarray length in O(n).
  • Hash Table (Linear Probing) Game — Compute h(k) = k mod m, resolve open-addressing collisions on Insert, and trace Lookup probe chains interactively.
  • Monotonic Stack (NGE) Game — Maintain a decreasing monotonic stack by deciding Pop vs. Push to compute every Next Greater Element in O(n).
  • Coin Change DP Game — Fill the 1D Coin Change DP array dp[a] = min(dp[a - c] + 1) step by step to beat greedy coin traps.
  • Linked List Pointer Ops Game — Practice in-place O(1) Linked List pointer reversal and safe node insertion without dropping tail references.
  • N-Queens Backtracking Game — Place non-attacking queens row by row with live column and diagonal threat checks and backtrack out of dead ends.
  • Red-Black Tree Fixup Game — Inspect Uncle color and Grandparent-Parent-Child alignment to choose Recolor vs. LL, RR, LR, or RL rotations.
  • B-Tree (Search & Split) Game — Route queries across multi-key root separators and promote the median key when a B-Tree node overflows.
  • Two Heaps Running Median Game — Route stream numbers into Lower Max-Heap vs. Upper Min-Heap and rebalance to read O(1) running medians.
  • Bloom Filter (Insert & Query) Game — Set k hash bit positions on Insert and distinguish guaranteed negatives from probabilistic false positives on Query.
  • Tarjan's SCC Roots Game — Inspect disc[u] and low[u] values on a directed graph to extract Strongly Connected Component roots in Tarjan's stack pop order.
  • Dinic's Max Flow Game — Push exact bottleneck capacities along BFS level-graph augmenting paths in Dinic's Maximum Flow algorithm.
  • Convex Hull (Graham Scan) Game — Build a 2D lower convex hull left-to-right by checking cross products to Keep CCW turns and Pop CW dents.
  • Rabin-Karp Rolling Hash Game — Slide a rolling hash window (mod 13) to skip misses in O(1) and distinguish spurious collisions from true matches.
  • Skip List Express Search Game — Navigate multi-level Skip List express lanes by choosing Go Right vs. Drop Down in O(log n) expected time.
  • Sqrt Decomposition Query Game — Answer range sum queries in O(sqrt(n)) by combining full precomputed blocks with partial boundary elements.
  • Matrix Chain Multiplication Game — Compute subchain multiplication costs and pick the optimal Interval DP split k to minimize scalar multiplications.
  • Sudoku MRV Constraint Solver Game — Apply row, column, and 2x2 box constraint propagation (MRV) to deduce every empty cell with zero guessing.
  • Counting Sort Placement Game — Scan right-to-left using cumulative prefix counts to place each element into its exact stable output slot in O(n + k).
  • Treap (BST + Heap) Game — Enforce BST key ordering and Max-Heap priority simultaneously using Left and Right tree rotations.
  • Bitmasking & XOR Tricks Game — Evaluate O(1) XOR cancellation, Brian Kernighan n & (n - 1), lowest-set-bit n & -n, and subset bitmask operations.
  • Binary Search on Answer Game — Test feasibility predicate canShip(mid) and halve [lo, hi] to find the minimum valid capacity in O(n log S).
  • Suffix Automaton (SAM) Game — Practice Suffix Automaton online extend(c) cases (Root Link, Direct Link, Clone Split) and distinct substring queries on a live SVG automaton.
  • Binary Tree Traversals Game — Click nodes on a live SVG tree in exact Pre-Order, In-Order, or Post-Order DFS sequence across BST and expression trees.
  • Stack & Queue (LIFO vs. FIFO) Game — Master O(1) LIFO Stack push/pop vs. FIFO Queue enqueue/dequeue across Undo history, Balanced Brackets, and BFS queues.
  • Insertion Sort Shift Game — Compare the active key against the sorted prefix to decide Shift Right vs. Insert while preserving duplicate stability.
  • Ternary Search Peak Game — Compare f(m1) vs. f(m2) on a live SVG unimodal curve to discard one-third of [lo, hi] each step in O(log n).
  • Job Sequencing Deadlines Game — Schedule highest-profit jobs into the latest free timeline slot <= deadline to maximize total profit greedily.
  • Persistent Segment Tree Game — Click the exact O(log n) root-to-leaf nodes to clone via path copying while sharing untouched Version 0 subtrees.
  • Heavy-Light Decomposition (HLD) Game — Pick each parent heavy child (largest subtree size) on a live SVG tree to decompose paths into O(log n) chains.
  • Centroid Decomposition Game — Find the exact tree centroid whose removal splits every remaining component to size <= N/2 on a live SVG tree.
  • DP on Trees Game — Compute bottom-up Maximum Independent Set (Take vs. Skip) values on a live SVG tree without adjacent picks.
  • Bitmask DP (TSP) Game — Encode visited cities in a binary bitmask and choose optimal (mask, u) -> (mask | 1<<v, v) transitions.
  • Mo's Algorithm Query Sort Game — Sort offline range queries by (floor(L / B), R) to minimize sliding-window pointer movement to O((N+Q)sqrt(N)).
  • RSA & Euler's Totient Game — Compute public modulus n = p * q, Euler totient phi(n), private inverse d, and ciphertext C = M^e mod n.
  • Diffie-Hellman Key Exchange Game — Compute Alice and Bob public keys g^a mod p, g^b mod p and derive their identical shared secret key.
  • Line Segment Intersection Game — Use exact integer CCW/CW cross-product orientation signs and bounding boxes to decide if segments AB and CD intersect.
  • Point in Polygon (Ray Casting) Game — Cast a horizontal ray from P across concave polygons and count odd (Inside) vs. even (Outside) edge crossings.
  • Graph Representations Game — Translate a live directed or undirected SVG graph into an O(V^2) Adjacency Matrix or O(V + E) Adjacency List.
  • Heap Sort (In-Place) Game — Swap root max arr[0] with the unsorted tail and sift down within the shrinking Max-Heap in O(1) extra space.
  • Subsets & Power Set Game — Steer Include vs. Exclude branches along the 2^n recursion tree and map every generated subset to its bitmask.
  • Digit DP (Tight Bound) Game — Track the tight-bound flag (0..N[pos] vs. 0..9) to count constrained numbers up to 10^18 in O(digits).
  • Jump & Interpolation Search Game — Practice sqrt(n) Jump Search block leaps and O(log log n) proportional Interpolation Search probes on sorted arrays.
  • Hamiltonian Path Game — Visit every vertex on a live SVG graph exactly once, spotting degree-1 traps and backtracking cleanly.
  • Fibonacci Heap Cascading Cut Game — Inspect marked parents to decide No Cut, Cut & Mark, or Cascading Cut during O(1) amortized decreaseKey.
  • Suffix Tree Edge Splits Game — Master compressed edge splits, the $ sentinel invariant, Longest Repeated Substring, and Ukkonen O(n) builds.