231 interactive walkthroughs. Watch algorithms execute step-by-step with live runtime state, source highlighting, and test cases.
Save solved problems, build streaks, earn XP, and get spaced-repetition reviews so what you learn here actually sticks. Visualizers are free to browse — the engineering OS is for members.
Sort first, then lock one anchor and solve the remaining pair with inward pointers.
Simulate digit-by-digit addition with carry over linked lists.
Insert nodes at specific indices by traversing to index - 1.
Derive character order from an alien dictionary using Topological Sort (Kahn's Algorithm).
Use backtracking through a Directed Acyclic Graph (DAG) to eagerly collect every unique path to the target.
Sort greed factors and cookie sizes, then eagerly feed the least greedy child first.
Bottom-up DFS checking if subtree heights differ by at most 1. Early termination on imbalance.
Computes the absolute shortest paths sequentially from a source node to all other reachable nodes. Safely handles negative edges and detects negative cycles.
Track the lowest price seen so far and compute the best profit at every step.
Harvest all positive uphill price differences between adjacent days.
Shrink the sorted search window until the middle element either matches the target or the interval disappears.
Recursive DFS visiting left, then root, then right. See how in-order produces sorted output for BSTs.
Iterative inorder using curr pointer + stack. Two-phase loop: go left (push), then pop-record-go right.
BFS level-order traversal using a queue. Watch nodes get visited level by level with queue state tracked in real time.
DFS recursion with a level parameter to slot each node into the correct sub-array — no queue needed.
Postorder DFS computing max gain from each subtree while tracking the global maximum path sum.
Recursive DFS visiting left, then right, then root. Children are always processed before their parent.
Iterative postorder with a single stack. Uses curr and lastVisited pointers to avoid revisiting the right subtree.
Iterative postorder using two stacks. Phase 1: fill stack2 in reverse-postorder via stack1. Phase 2: pop stack2 for correct order.
Recursive DFS visiting root, then left, then right. Watch the call stack and result array build in real time.
Iterative DFS using an explicit stack. Push root, then loop: pop → record → push right → push left.
BFS collecting the last node of each level. See which nodes are visible from the right side of the tree.
BFS with alternating direction per level. Watch the zigzag pattern build as levels alternate left-to-right and right-to-left.
Generic Level-Order Graph Traversal starting from a given node. Essential foundation for shortest path algorithms.
Distribute n elements into n buckets by value range, sort each bucket, then concatenate.
Consider strings bursting last within sub-windows length combinations to evaluate maximum nested rewards.
Compute local optimums with sweeping left-to-right pass followed by right-to-left pass.
Decompose ratings into ascending/descending mountain runs and sum arithmetic triangles, adjusting the shared peak.
Determine how many fleets of cars will arrive at a destination by tracking time-to-target using a monotonic stack.
Process pick-ups and drop-offs as net capacity changes on a timeline array.
Apply a level-bounded Bellman-Ford traversal to find the minimum cost trail with at most K transfers.
Count the ways to reach the top by summing the ways to reach the 1-step and 2-step previous stairs.
Perform a BFS to deeply copy an undirected graph, resolving cycles using a hash map.
Find the absolute minimum coins needed for any amount by comparing combinations of all available coin denominations.
Calculate unique coin combinations sequentially over the amount target to prevent double-counting combinations as permutations.
Find all unique combinations that sum to target using candidates an unlimited number of times.
Find unique combinations summing to target where each candidate is used at most once.
Find valid combinations of k numbers (1-9) that sum up to n without reusing digits.
Find all possible combinations of k numbers out of the range [1, n].
Given preorder and inorder arrays, recursively construct a binary tree. Preorder gives the root, while inorder splits left and right subtrees.
Measure area with both outer walls, then move the shorter wall inward to search for a taller boundary.
Insert each number into a hash set; if it already exists, a duplicate is found.
Generate the nth term of the reading sequence.
DFS tracking the max value on the path from root. A node is good if its value >= max so far.
Count occurrences of each element, then reconstruct the sorted array from counts.
Line-by-line walkthrough of stable counting sort with a live locals tracker.
Why right-to-left placement with prefix-sum end-pointers preserves the original order of equal keys.
Detect cycles in a directed graph using DFS (visited states) to determine if all courses can be finished.
Determine the topological order of courses using Kahn's Algorithm (BFS) and detect cycles in prerequisites.
Sweep from right to left with a monotonic stack of warmer indices waiting to help earlier days.
Parse and expand iteratively nested repeating strings.
Calculate parsing possibilities by evaluating if single characters or double characters map to letters A-Z.
Bypass a node by pointing curr.next to curr.next.next to remove it.
Generic Graph Traversal that dives deep into branches before backtracking. Foundational for cycle detection and topological sort.
Understand how to maintain head, tail and list size when designing a linked list.
Use DFS to check for cycles. We find a cycle when we explore a node that is already visited and is not the direct parent of the current node.
DFS computing height while tracking max left+right height across all nodes to find the longest path.
Computes the absolute shortest paths sequentially from a source node to all other reachable nodes in a positively edge-weighted graph.
Find minimum insert/delete/replace operations dynamically comparing text alignments across a matrix.
Safely serialize an array of strings into a single string by prefixing each word with its length and a '#' delimiter, bypassing delimiter collision issues.
Numbers go onto the stack; each operator pops the last two values, computes, and pushes the result back.
Compute n! by multiplying n with the recursive factorial of n-1.
Calculate the nth Fibonacci number strictly computing bottom-up to save recursion overhead.
Run binary search twice: once for the left boundary and once for the right boundary of the target.
Convert an edge list to an adjacency list, then run BFS with visited sets until the destination is found.
Binary search the starting index of the best k-length window instead of comparing each element independently.
Computes the running median of an incoming stream of numbers efficiently by balancing a Max-Heap and a Min-Heap.
Compare mid with the right boundary to decide whether the minimum is in the rotated right block or the sorted left block.
Iterate the string to build frequency maps arrays for vowels and consonants.
Compare mid with its right neighbor; the slope tells you which side must contain a peak.
Execute Floyd-Warshall to compute all-pairs shortest paths and identify the city with minimal threshold-connectivity.
Slide a short matching window across the haystack and compare the candidate substring.
Check each string in an array and record its index if it contains a target character.
Search for the leftmost bad version by keeping bad mids and discarding everything before good mids.
Computes the shortest paths between ALL pairs of nodes simultaneously in a weighted graph using a 2D matrix dynamic programming approach.
If tank runs negative, reset the candidate starting station to the next index immediately.
Verify if a graph is a valid tree (connected and no cycles) using Union-Find.
Sort each string to generate a universal anagram key, using a Hash Map to group them.
Hash 26-letter frequency counts so every anagram shares the same signature without sorting.
Treat the feedback API as the comparison oracle and keep halving the remaining guess range.
Build straights by sequentially satisfying combinations using a frequency map.
Maximize loot by choosing between robbing the current house + the house two doors down, or skipping it entirely.
Solve the house robber problem twice (once skipping the first house, once skipping the last) to account for the circular street.
Convert a decimal integer to its binary equivalent by repeatedly dividing by 2 and prepending the remainders.
Use one stack for incoming pushes and another for outgoing pops, transferring only when needed.
Push to the queue, then rotate older elements behind the new one so the front behaves like stack top.
Build a prefix tree from scratch — insert words character by character, then search and check prefixes by walking the tree.
Linearly add non-overlapping prefix intervals, merge overlaps via min/max expansion, then add suffix.
Traverse the BST search path until the first empty child slot appears, then insert there.
Find the merge point by swapping pointers to align distances.
Learn the basics of linked list traversal using a current pointer.
Recursive DFS swapping left and right children at every node. Watch the tree mirror itself.
Advance the source string only when characters match; the target string keeps moving regardless.
Maintain a one-to-one character mapping using two hash maps simultaneously to verify isomorphic consistency.
Store all jewels in a Set, then verify each stone with O(1) time complexity.
Track the max reachable index; return false immediately if moving past it.
Track the farthest choice possible within the current jump boundary.
Computes a Topological Sort of a DAG using BFS by systematically removing nodes with 0 incoming edges. Unreachable nodes indicate a cycle.
Build the LPS table and reuse prefix matches so substring search skips redundant comparisons.
Constructs a Minimum Spanning Tree greedily by sorting edges by weight and using a Disjoint Set structure to safely combine components.
Maintain a size-k min-heap across streamed adds so the root is always the current kth largest.
Keep a min-heap of size k while scanning nums; the root ends up as the kth largest.
Use in-order traversal so the kth visited node is the kth smallest BST value.
Seed a min-heap with the first column, then pop k-1 times, pushing each popped cell's right neighbor.
An integer string is odd if its last digit is odd. Scan right-to-left for the first odd digit.
Find the maximum rectangular area spanning adjacent bars by tracking height boundaries with a monotonic increasing stack.
Repeatedly smash the two heaviest stones in a max-heap until at most one stone remains.
Prioritize giving $10 bills as change before $5 bills to maximize flexibility.
Start from the end to skip trailing spaces, then count characters until the first space.
Iterate over digit mappings to generate all combinations representing the phone number.
Detect cycles using Floyd's Tortoise and Hare algorithm.
Store visited node references in a hash set and stop the first time a node repeats.
Find the start of a cycle using phase 1 and phase 2 intersection.
Assume the first word is the prefix, then iteratively shorten it until it matches the start of the next word.
Compute intersecting string characters via 2D matrices, pulling diagonals for matches and edges for non-matches.
Put every number in a set, then only start counting from sequence beginnings.
Linearly search prior numbers validating smaller ones to extend sequences, logging max lengths per index.
Expand from all possible centers to discover the longest valid palindrome within the string memory bounds.
Keep the window as large as possible while at most k characters differ from the most frequent letter inside it.
Expand the right edge, and whenever a duplicate appears, shrink the left edge until the window is valid again.
Walk downward until the current node becomes the first split point between p and q.
DFS returning p or q when found, identifying the LCA where both subtrees return non-null.
Design a data structure with O(1) operations that evicts the least recently used item using a Hash Map and Doubly Linked List.
Scan a grid and launch recursive DFS traversals to sink sub-islands and measure their cumulative area.
Count consecutive 1s while scanning and reset the counter on every 0.
DFS recursion computing 1 + max(left, right) depth. Watch depth values propagate back up the tree.
Top-down DFS carrying depth as a parameter. Update global max at each node — preorder style.
Track the running max AND min products to account for the property where multiplying two negative numbers creates a positive.
Apply Kadane's algorithm to compute the largest contiguous sum by abandoning negative prefix sums.
Find the median of two sorted arrays in O(log(min(m,n))) time by binary searching the optimal partition index between them.
Sort start and end times separately; sweep through events and track peak concurrent meetings.
Sort by start time, then iteratively expand the boundary of the active trailing interval.
Fill from the back so the largest values land in their correct positions without extra space.
Combine two sorted lists picking the smallest heads sequentially.
Use a slow and fast pointer to find the middle node efficiently.
Minimize the cost to reach the top by choosing the cheapest path from the two preceding steps.
Construct a Minimum Spanning Tree (MST) using Prim's algorithm to link 2D points with minimal total Manhattan distance.
Find the minimum cost to cut a stick at given points using interval DP.
Store each pushed value together with the minimum seen so far so min() stays O(1).
Insert values with bubble-up, then extract-min with sift-down. Watch the tree and array in sync.
Find the minimum number of insertions to balance parentheses.
Find the smallest substring containing all characters of a target string by expanding and contracting a sliding window.
Use the Gauss sum formula: expected sum minus actual sum gives the missing number.
Push non-zero values toward the front with a write pointer, then fill the tail with zeroes.
Place N queens on an NxN board so none attack each other, using sets for diagonals.
Broadcast a signal through a weighted directed graph using Dijkstra's Algorithm to find total transmission time.
Scan nums2 right-to-left with a decreasing stack, seeding each value's next greater into a hash-map, then answer nums1 queries in O(1).
Simulate a circular array by scanning twice while the monotonic stack keeps candidate greater values.
Sort intervals by earliest end time to minimize conflicts and maximize schedule space.
Identify and count disconnected land masses in a grid using recursive DFS flood filling.
Count isolated network clusters using DSU and determine the minimum number of cables needed to bridge them.
Extend Dijkstra's algorithm to count the total number of distinct paths that achieve the absolute minimum travel time.
Group odd and even indexed nodes separately, then combine them.
Multi-source DFS/BFS to find cells that can reach both the Pacific and Atlantic oceans.
Check for palindromes by reversing the second half and comparing.
Slice every prefix of the remainder as a candidate, verify it's a palindrome with two pointers, then recurse on the suffix — choose, explore, un-choose.
Expand outwards from every single character and between every character to count all palindromes efficiently.
Ensure the total sum is even, then iterate combinations to see if a subset strictly equals sum/2.
Find last occurrences of each character, extending partition boundary until index catches up.
DFS exploring root-to-leaf paths with a running sum. Backtrack when a path doesn't reach the target.
Top-down DFS carrying a running sum. Check newSum === target at leaves. An 'ans' flag locks in the result.
Binary search the turning point where the increasing slope switches into a decreasing slope.
Slide a fixed-size window and compare frequency balance with the target permutation.
Generate all possible permutations of an array by trying every unused element in each slot.
Generate all unique permutations by sorting the input and recursing with a functionally-sliced `choices` array — dedup collapses to a `choices[i] === choices[i-1]` sibling-skip.
BFS level-by-level connecting each node's next pointer to the next node in the same level.
Determine if a number is a power of 2 by recursively halving it.
Constructs a Minimum Spanning Tree greedily by growing a single connected component and selecting the cheapest incident edge at each step.
Build prefix products from the left, then multiply in suffix products from the right.
Partition array around pivot, recursively sort left and right halves using divide and conquer.
Find pattern matches in text using a rolling hash to avoid O(M) comparisons.
Find pattern matches in text using a rolling hash to avoid O(M) comparisons.
Sort numbers digit by digit from least significant to most significant using stable counting sort.
Reconstruct a flight itinerary using Hierholzer's algorithm for finding an Eulerian Path.
Understand double recursion using the classic Fibonacci sequence.
Use a Disjoint Set Union (DSU) structure to identify exactly which edge mathematically creates a cycle in a tree structure.
Enforce pattern combinations over wildcard/star lookbacks inside a 2D matrix matching rules.
Walk one pointer ahead to find distinct values and overwrite the front of the array in-place.
Bypass duplicates since they are adjacent in a sorted list.
Overwrite matching values by copying non-matching elements toward the front of the array.
Remove specific values from a list using a dummy node approach.
Maintain an n-gap between two pointers to find the node perfectly.
Track primitive depth and emit only the characters that are not on the outermost shell.
Reorders a Linked List by splitting it into two halves, reversing the second half, and merging them alternately.
Rearrange a string so no two adjacent characters are the same.
Find the minimum times 'a' must be repeated for 'b' to be a substring.
Iteratively reverse a linked list using prev, curr, and next pointers.
Swap characters from both ends moving inward until the pointers meet in the middle.
Reverse the first k characters for every blocks of 2k characters.
Reverse the order of words in a string, cleaning up extra spaces.
Form a circular list then break it at the correctly calculated point.
Run BFS level by level from every rotten orange so each minute spreads rot to fresh neighbors.
Recursive DFS comparing two trees node by node. Both structure and values must match.
Compare the target with the current node and follow the only subtree that can still contain it.
At every step, one half of the rotated array is still sorted. Detect it and decide whether the target lies there.
Convert a binary tree to a string using level-order traversal (BFS), and reconstruct the exact same tree from the string.
Navigate an 8-directional binary grid using BFS to find the minimal distance from start to finish.
Finds the shortest path from a source node to all other nodes in an unweighted graph using Level Order Traversal (BFS).
Use index parity around matched pairs to tell which side still has the broken pairing pattern.
XOR all values together so duplicate pairs cancel out and only the unique number remains.
Maintain a decreasing deque of indices so the current maximum is always at the front.
Maintain a balance counter, increment for 'L' and decrement for 'R'. Split when balance is 0.
Binary search the integer answer space and keep the largest mid whose square does not exceed x.
Generate all possible subsets (the power set) by exploring include and exclude decisions recursively.
Generate all unique subsets from an array that may contain duplicates by sorting and skipping.
For each node in the main tree, check if the subtree rooted there matches the target tree.
Pre-order serialize both trees with null markers, then check if subRoot's string is a substring of root's string.
Recursively sum the elements of an array by moving an index to the base case.
Find the total beauty sum across all contiguous substrings.
Sum numbers down to 0 using a basic recursive call stack.
Find minimum moves to determine critical floor using k eggs.
Swap adjacent nodes iteratively by keeping track of the previous node.
Find the minimum time to swim to the target using Dijkstra on a grid of elevations.
Recursive mirror check comparing left.left with right.right and left.right with right.left.
Iterative BFS using a queue: enqueue mirror pairs, dequeue two at a time, validate, and push children in mirror order.
Calculate hypothetical idle periods based on the most frequent task, then fill gaps.
Count frequencies, then push into a min-heap keyed by frequency and cap it at size k.
Orders a Directed Acyclic Graph (DAG) linearly such that for every directed edge U -> V, node U comes before V. DFS solves this natively using a post-order stack process.
Track the best wall seen from both sides and trap water above shorter boundaries.
Calculate cost differences to greedily send the people generating maximum relative savings to City A.
Scan once with a hashmap of seen values and resolve the complement the moment it appears.
Use the sorted order to squeeze two pointers inward until the sum matches the target.
Map combinations by simulating paths from Top and paths from Left, optimized into O(M) space.
Build a hash map of character counts for s, then decrement the counts while iterating over t.
Use left and right pointers to scan inwards, skipping symbols and checking equality.
Create a cleaned lowercase copy, reverse it into extra space, and compare both strings directly.
Push opening brackets and match them off in reverse order whenever a closing bracket arrives.
Carry valid lower and upper bounds down the tree to verify every node respects BST ordering.
Check if segments of the string can be matched against an exact hash set dictionary iteratively.
Find the shortest transformation sequence between two words using BFS on word mutations.
DFS over a grid with mark-and-restore: stamp '#' on the current cell, probe the 4 neighbors for the next character, then put the original back on the way out.