Algorithm Visualizers

231 interactive walkthroughs. Watch algorithms execute step-by-step with live runtime state, source highlighting, and test cases.

Sign in to track your progress

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.

Showing 231 of 231

All Visualizers

Two Pointers & Sliding Window3sum

3Sum

Sort first, then lock one anchor and solve the remaining pair with inward pointers.

Linked Listadd-two-numbers

Add Two Numbers

Simulate digit-by-digit addition with carry over linked lists.

Linked Listadding-nodes-to-linked-list

Adding Nodes to Linked List

Insert nodes at specific indices by traversing to index - 1.

Graphsalien-dictionary

Alien Dictionary

Derive character order from an alien dictionary using Topological Sort (Kahn's Algorithm).

Graphsall-paths-from-source-to-target

All Paths From Source to Target

Use backtracking through a Directed Acyclic Graph (DAG) to eagerly collect every unique path to the target.

Greedy Algorithmassign-cookies

Assign Cookies

Sort greed factors and cookie sizes, then eagerly feed the least greedy child first.

Binary Treebalanced-binary-tree

Balanced Binary Tree

Bottom-up DFS checking if subtree heights differ by at most 1. Early termination on imbalance.

Graphsbellman-ford-algorithm-negative-weights

Bellman Ford Algorithm

Computes the absolute shortest paths sequentially from a source node to all other reachable nodes. Safely handles negative edges and detects negative cycles.

Arraysbest-time-to-buy-and-sell-stock

Best Time to Buy and Sell Stock

Track the lowest price seen so far and compute the best profit at every step.

Greedy Algorithmbest-time-to-buy-and-sell-stock-ii

Best Time to Buy and Sell Stock II

Harvest all positive uphill price differences between adjacent days.

Binary Searchbinary-search

Binary Search

Shrink the sorted search window until the middle element either matches the target or the interval disappears.

Binary Treebinary-tree-inorder-traversal

Binary Tree Inorder Traversal

Recursive DFS visiting left, then root, then right. See how in-order produces sorted output for BSTs.

Binary Treebinary-tree-inorder-traversal-iterative

Binary Tree Inorder Traversal - Iterative

Iterative inorder using curr pointer + stack. Two-phase loop: go left (push), then pop-record-go right.

Binary Treebinary-tree-level-order-traversal

Binary Tree Level Order Traversal

BFS level-order traversal using a queue. Watch nodes get visited level by level with queue state tracked in real time.

Binary Treebinary-tree-level-order-traversal-recursion

Binary Tree Level Order Traversal - Recursion

DFS recursion with a level parameter to slot each node into the correct sub-array — no queue needed.

Binary Treebinary-tree-maximum-path-sum

Binary Tree Maximum Path Sum

Postorder DFS computing max gain from each subtree while tracking the global maximum path sum.

Binary Treebinary-tree-postorder-traversal

Binary Tree Postorder Traversal

Recursive DFS visiting left, then right, then root. Children are always processed before their parent.

Binary Treebinary-tree-postorder-traversal-one-stack

Binary Tree Postorder Traversal - One Stack

Iterative postorder with a single stack. Uses curr and lastVisited pointers to avoid revisiting the right subtree.

Binary Treebinary-tree-postorder-traversal-two-stacks

Binary Tree Postorder Traversal - Two Stacks

Iterative postorder using two stacks. Phase 1: fill stack2 in reverse-postorder via stack1. Phase 2: pop stack2 for correct order.

Binary Treebinary-tree-preorder-traversal

Binary Tree Preorder Traversal

Recursive DFS visiting root, then left, then right. Watch the call stack and result array build in real time.

Binary Treebinary-tree-preorder-traversal-iterative

Binary Tree Preorder Traversal - Iterative

Iterative DFS using an explicit stack. Push root, then loop: pop → record → push right → push left.

Binary Treebinary-tree-right-side-view

Binary Tree Right Side View

BFS collecting the last node of each level. See which nodes are visible from the right side of the tree.

Binary Treebinary-tree-zigzag-level-order

Binary Tree Zigzag Level Order Traversal

BFS with alternating direction per level. Watch the zigzag pattern build as levels alternate left-to-right and right-to-left.

Graphsbreadth-first-search-bfs

Breadth First Search (BFS)

Generic Level-Order Graph Traversal starting from a given node. Essential foundation for shortest path algorithms.

Sortingbucket-sort

Bucket Sort

Distribute n elements into n buckets by value range, sort each bucket, then concatenate.

Dynamic Programmingburst-balloons

Burst Balloons

Consider strings bursting last within sub-windows length combinations to evaluate maximum nested rewards.

Greedy Algorithmcandy

Candy

Compute local optimums with sweeping left-to-right pass followed by right-to-left pass.

Greedy Algorithmcandy-one-pass

Candy — One Pass O(1) Space

Decompose ratings into ascending/descending mountain runs and sum arithmetic triangles, adjusting the shared peak.

Stacks & Queuescar-fleet

Car Fleet

Determine how many fleets of cars will arrive at a destination by tracking time-to-target using a monotonic stack.

Greedy Algorithmcar-pooling

Car Pooling

Process pick-ups and drop-offs as net capacity changes on a timeline array.

Graphscheapest-flights-within-k-stops

Cheapest Flights Within K Stops

Apply a level-bounded Bellman-Ford traversal to find the minimum cost trail with at most K transfers.

Dynamic Programmingclimbing-stairs

Climbing Stairs

Count the ways to reach the top by summing the ways to reach the 1-step and 2-step previous stairs.

Graphsclone-graph

Clone Graph

Perform a BFS to deeply copy an undirected graph, resolving cycles using a hash map.

Dynamic Programmingcoin-change

Coin Change

Find the absolute minimum coins needed for any amount by comparing combinations of all available coin denominations.

Dynamic Programmingcoin-change-ii

Coin Change II

Calculate unique coin combinations sequentially over the amount target to prevent double-counting combinations as permutations.

Backtrackingcombination-sum

Combination Sum

Find all unique combinations that sum to target using candidates an unlimited number of times.

Backtrackingcombination-sum-ii

Combination Sum II

Find unique combinations summing to target where each candidate is used at most once.

Backtrackingcombination-sum-iii

Combination Sum III

Find valid combinations of k numbers (1-9) that sum up to n without reusing digits.

Backtrackingcombinations

Combinations

Find all possible combinations of k numbers out of the range [1, n].

Binary Treeconstruct-binary-tree-from-preorder-and-inorder-traversal

Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder arrays, recursively construct a binary tree. Preorder gives the root, while inorder splits left and right subtrees.

Two Pointers & Sliding Windowcontainer-with-most-water

Container With Most Water

Measure area with both outer walls, then move the shorter wall inward to search for a taller boundary.

Arrayscontains-duplicate

Contains Duplicate

Insert each number into a hash set; if it already exists, a duplicate is found.

Strings - Advancedcount-and-say

Count and Say

Generate the nth term of the reading sequence.

Binary Treecount-good-nodes

Count Good Nodes in Binary Tree

DFS tracking the max value on the path from root. A node is good if its value >= max so far.

Sortingcounting-sort

Counting Sort

Count occurrences of each element, then reconstruct the sorted array from counts.

Sortingcounting-sort-stable-code

Counting Sort - Stable - Code

Line-by-line walkthrough of stable counting sort with a live locals tracker.

Sortingcounting-sort-stable-logic

Counting Sort - Stable - Logic

Why right-to-left placement with prefix-sum end-pointers preserves the original order of equal keys.

Graphscourse-schedule

Course Schedule

Detect cycles in a directed graph using DFS (visited states) to determine if all courses can be finished.

Graphscourse-schedule-ii

Course Schedule II

Determine the topological order of courses using Kahn's Algorithm (BFS) and detect cycles in prerequisites.

Stacks and Queuesdaily-temperatures

Daily Temperatures

Sweep from right to left with a monotonic stack of warmer indices waiting to help earlier days.

Strings - Advanceddecode-string

Decode String

Parse and expand iteratively nested repeating strings.

Dynamic Programmingdecode-ways

Decode Ways

Calculate parsing possibilities by evaluating if single characters or double characters map to letters A-Z.

Linked Listdeleting-nodes-in-linked-list

Deleting Nodes in Linked List

Bypass a node by pointing curr.next to curr.next.next to remove it.

Graphsdepth-first-search-dfs

Depth First Search (DFS)

Generic Graph Traversal that dives deep into branches before backtracking. Foundational for cycle detection and topological sort.

Linked Listdesign-linked-list

Design Linked List

Understand how to maintain head, tail and list size when designing a linked list.

Graphsdetect-cycle-in-an-undirected-graph

Detect Cycle in Undirected Graph

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.

Binary Treediameter-of-binary-tree

Diameter of Binary Tree

DFS computing height while tracking max left+right height across all nodes to find the longest path.

Graphsdijkstras-algorithm-shortest-path

Dijkstra's Algorithm

Computes the absolute shortest paths sequentially from a source node to all other reachable nodes in a positively edge-weighted graph.

Dynamic Programmingedit-distance

Edit Distance

Find minimum insert/delete/replace operations dynamically comparing text alignments across a matrix.

Arrays & Hashingencode-and-decode-strings

Encode and Decode Strings

Safely serialize an array of strings into a single string by prefixing each word with its length and a '#' delimiter, bypassing delimiter collision issues.

Stacks and Queuesevaluate-reverse-polish-notation

Evaluate Reverse Polish Notation

Numbers go onto the stack; each operator pops the last two values, computes, and pushes the result back.

Recursionfactorial-of-n

Factorial of N

Compute n! by multiplying n with the recursive factorial of n-1.

Dynamic Programmingfibonacci-number

Fibonacci Number

Calculate the nth Fibonacci number strictly computing bottom-up to save recursion overhead.

Binary Searchfind-first-and-last-position-of-element-in-sorted-array

Find First and Last Position of Element in Sorted Array

Run binary search twice: once for the left boundary and once for the right boundary of the target.

Graphsfind-if-path-exists-in-graph

Find if Path Exists in Graph

Convert an edge list to an adjacency list, then run BFS with visited sets until the destination is found.

Binary Searchfind-k-closest-elements

Find K Closest Elements

Binary search the starting index of the best k-length window instead of comparing each element independently.

Heap / Priority Queuefind-median-from-data-stream

Find Median from Data Stream

Computes the running median of an incoming stream of numbers efficiently by balancing a Max-Heap and a Min-Heap.

Binary Searchfind-minimum-in-rotated-sorted-array

Find Minimum in Rotated Sorted Array

Compare mid with the right boundary to decide whether the minimum is in the rotated right block or the sorted left block.

Stringsfind-most-frequent-vowel-and-consonant

Find Most Frequent Vowel and Consonant

Iterate the string to build frequency maps arrays for vowels and consonants.

Binary Searchfind-peak-element

Find Peak Element

Compare mid with its right neighbor; the slope tells you which side must contain a peak.

Graphsfind-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance

Find the City with Smallest Neighbors

Execute Floyd-Warshall to compute all-pairs shortest paths and identify the city with minimal threshold-connectivity.

Two Pointers & Sliding Windowfind-the-index-of-the-first-occurrence-in-a-string

Find the Index of the First Occurrence in a String

Slide a short matching window across the haystack and compare the candidate substring.

Stringsfind-words-containing-character

Find Words Containing Character

Check each string in an array and record its index if it contains a target character.

Binary Searchfirst-bad-version

First Bad Version

Search for the leftmost bad version by keeping bad mids and discarding everything before good mids.

Graphsfloyd-warshall-algorithm-all-pairs-shortest-path

Floyd Warshall Algorithm

Computes the shortest paths between ALL pairs of nodes simultaneously in a weighted graph using a 2D matrix dynamic programming approach.

Greedy Algorithmgas-station

Gas Station

If tank runs negative, reset the candidate starting station to the next index immediately.

Graphsgraph-valid-tree

Graph Valid Tree

Verify if a graph is a valid tree (connected and no cycles) using Union-Find.

Stringsgroup-anagrams

Group Anagrams

Sort each string to generate a universal anagram key, using a Hash Map to group them.

Hashinggroup-anagrams-approach-2-hashed-key

Group Anagrams - Approach 2 - Hashed Key

Hash 26-letter frequency counts so every anagram shares the same signature without sorting.

Binary Searchguess-number-higher-or-lower

Guess Number Higher or Lower

Treat the feedback API as the comparison oracle and keep halving the remaining guess range.

Greedy Algorithmhand-of-straights

Hand of Straights

Build straights by sequentially satisfying combinations using a frequency map.

Dynamic Programminghouse-robber

House Robber

Maximize loot by choosing between robbing the current house + the house two doors down, or skipping it entirely.

Dynamic Programminghouse-robber-ii

House Robber II

Solve the house robber problem twice (once skipping the first house, once skipping the last) to account for the circular street.

Real DSAimplement-binary-representation-of-given-number

Implement Binary representation of given number

Convert a decimal integer to its binary equivalent by repeatedly dividing by 2 and prepending the remainders.

Stacks and Queuesimplement-queue-using-stacks

Implement Queue using Stacks

Use one stack for incoming pushes and another for outgoing pops, transferring only when needed.

Stacks and Queuesimplement-stack-using-queues

Implement Stack using Queues

Push to the queue, then rotate older elements behind the new one so the front behaves like stack top.

Triesimplement-trie-prefix-tree

Implement Trie (Prefix Tree)

Build a prefix tree from scratch — insert words character by character, then search and check prefixes by walking the tree.

Greedy Algorithminsert-interval

Insert Interval

Linearly add non-overlapping prefix intervals, merge overlaps via min/max expansion, then add suffix.

Binary Search Treeinsert-into-a-binary-search-tree

Insert into a Binary Search Tree

Traverse the BST search path until the first empty child slot appears, then insert there.

Linked Listintersection-of-two-linked-lists

Intersection of Two Linked Lists

Find the merge point by swapping pointers to align distances.

Linked Listintroduction-to-linked-list

Introduction to Linked List

Learn the basics of linked list traversal using a current pointer.

Binary Treeinvert-binary-tree

Invert Binary Tree

Recursive DFS swapping left and right children at every node. Watch the tree mirror itself.

Two Pointers & Sliding Windowis-subsequence

Is Subsequence

Advance the source string only when characters match; the target string keeps moving regardless.

Stringsisomorphic-strings

Isomorphic Strings

Maintain a one-to-one character mapping using two hash maps simultaneously to verify isomorphic consistency.

Stringsjewels-and-stones

Jewels and Stones

Store all jewels in a Set, then verify each stone with O(1) time complexity.

Greedy Algorithmjump-game

Jump Game

Track the max reachable index; return false immediately if moving past it.

Greedy Algorithmjump-game-ii

Jump Game II

Track the farthest choice possible within the current jump boundary.

Graphskahns-algorithm-topological-sort-bfs

Kahn's Algorithm (BFS Topo Sort)

Computes a Topological Sort of a DAG using BFS by systematically removing nodes with 0 incoming edges. Unreachable nodes indicate a cycle.

Hashingknuth-morris-pratt-algorithm

KMP (Knuth-Morris-Pratt) Algorithm

Build the LPS table and reuse prefix matches so substring search skips redundant comparisons.

Graphskruskals-algorithm-mst

Kruskal's Algorithm (MST)

Constructs a Minimum Spanning Tree greedily by sorting edges by weight and using a Disjoint Set structure to safely combine components.

Heap / Priority Queuekth-largest-element-stream

Kth Largest Element in a Stream

Maintain a size-k min-heap across streamed adds so the root is always the current kth largest.

Heap / Priority Queuekth-largest-element-array

Kth Largest Element in an Array

Keep a min-heap of size k while scanning nums; the root ends up as the kth largest.

Binary Search Treekth-smallest-element-in-a-bst

Kth Smallest Element in a BST

Use in-order traversal so the kth visited node is the kth smallest BST value.

Heap / Priority Queuekth-smallest-sorted-matrix

Kth Smallest Element in a Sorted Matrix

Seed a min-heap with the first column, then pop k-1 times, pushing each popped cell's right neighbor.

Stringslargest-odd-number-in-a-string

Largest Odd Number in a String

An integer string is odd if its last digit is odd. Scan right-to-left for the first odd digit.

Stacks & Queueslargest-rectangle-in-histogram

Largest Rectangle in Histogram

Find the maximum rectangular area spanning adjacent bars by tracking height boundaries with a monotonic increasing stack.

Heap / Priority Queuelast-stone-weight

Last Stone Weight

Repeatedly smash the two heaviest stones in a max-heap until at most one stone remains.

Greedy Algorithmlemonade-change

Lemonade Change

Prioritize giving $10 bills as change before $5 bills to maximize flexibility.

Stringslength-of-last-word

Length of Last Word

Start from the end to skip trailing spaces, then count characters until the first space.

Backtrackingletter-combinations-of-a-phone-number

Letter Combinations of a Phone Number

Iterate over digit mappings to generate all combinations representing the phone number.

Linked Listlinked-list-cycle

Linked List Cycle

Detect cycles using Floyd's Tortoise and Hare algorithm.

Hashinglinked-list-cycle-hash-table

Linked List Cycle - Hash Table

Store visited node references in a hash set and stop the first time a node repeats.

Linked Listlinked-list-cycle-ii

Linked List Cycle II

Find the start of a cycle using phase 1 and phase 2 intersection.

Stringslongest-common-prefix

Longest Common Prefix

Assume the first word is the prefix, then iteratively shorten it until it matches the start of the next word.

Dynamic Programminglongest-common-subsequence

Longest Common Subsequence

Compute intersecting string characters via 2D matrices, pulling diagonals for matches and edges for non-matches.

Arrayslongest-consecutive-sequence

Longest Consecutive Sequence

Put every number in a set, then only start counting from sequence beginnings.

Dynamic Programminglongest-increasing-subsequence

Longest Increasing Subsequence

Linearly search prior numbers validating smaller ones to extend sequences, logging max lengths per index.

Dynamic Programminglongest-palindromic-substring

Longest Palindromic Substring

Expand from all possible centers to discover the longest valid palindrome within the string memory bounds.

Two Pointers & Sliding Windowlongest-repeating-character-replacement

Longest Repeating Character Replacement

Keep the window as large as possible while at most k characters differ from the most frequent letter inside it.

Two Pointers & Sliding Windowlongest-substring-without-repeating-characters

Longest Substring Without Repeating Characters

Expand the right edge, and whenever a duplicate appears, shrink the left edge until the window is valid again.

Binary Search Treelowest-common-ancestor-of-a-binary-search-tree

Lowest Common Ancestor of a Binary Search Tree

Walk downward until the current node becomes the first split point between p and q.

Binary Treelowest-common-ancestor-binary-tree

Lowest Common Ancestor of a Binary Tree

DFS returning p or q when found, identifying the LCA where both subtrees return non-null.

Linked Listlru-cache

LRU Cache

Design a data structure with O(1) operations that evicts the least recently used item using a Hash Map and Doubly Linked List.

Graphsmax-area-of-island

Max Area of Island

Scan a grid and launch recursive DFS traversals to sink sub-islands and measure their cumulative area.

Arraysmax-consecutive-ones

Max Consecutive Ones

Count consecutive 1s while scanning and reset the counter on every 0.

Binary Treemaximum-depth-of-binary-tree

Maximum Depth of Binary Tree

DFS recursion computing 1 + max(left, right) depth. Watch depth values propagate back up the tree.

Binary Treemaximum-depth-of-binary-tree-top-down

Maximum Depth of Binary Tree - Top Down

Top-down DFS carrying depth as a parameter. Update global max at each node — preorder style.

Dynamic Programmingmaximum-product-subarray

Maximum Product Subarray

Track the running max AND min products to account for the property where multiplying two negative numbers creates a positive.

Dynamic Programmingmaximum-subarray

Maximum Subarray

Apply Kadane's algorithm to compute the largest contiguous sum by abandoning negative prefix sums.

Binary Searchmedian-of-two-sorted-arrays

Median of Two Sorted Arrays

Find the median of two sorted arrays in O(log(min(m,n))) time by binary searching the optimal partition index between them.

Arraysmeeting-rooms-ii

Meeting Rooms II

Sort start and end times separately; sweep through events and track peak concurrent meetings.

Greedy Algorithmmerge-intervals

Merge Intervals

Sort by start time, then iteratively expand the boundary of the active trailing interval.

Arraysmerge-sorted-array

Merge Sorted Array

Fill from the back so the largest values land in their correct positions without extra space.

Linked Listmerge-two-sorted-lists

Merge Two Sorted Lists

Combine two sorted lists picking the smallest heads sequentially.

Linked Listmiddle-of-the-linked-list

Middle of the Linked List

Use a slow and fast pointer to find the middle node efficiently.

Dynamic Programmingmin-cost-climbing-stairs

Min Cost Climbing Stairs

Minimize the cost to reach the top by choosing the cheapest path from the two preceding steps.

Graphsmin-cost-to-connect-all-points

Min Cost to Connect All Points

Construct a Minimum Spanning Tree (MST) using Prim's algorithm to link 2D points with minimal total Manhattan distance.

Dynamic Programmingmin-cost-to-cut-a-stick

Min Cost to Cut a Stick

Find the minimum cost to cut a stick at given points using interval DP.

Stacks and Queuesmin-stack

Min Stack

Store each pushed value together with the minimum seen so far so min() stays O(1).

Heap / Priority Queuemin-heap

Min-Heap Operations

Insert values with bubble-up, then extract-min with sift-down. Watch the tree and array in sync.

Strings - Advancedminimum-add-to-make-parentheses-valid

Minimum Add to Make Parentheses Valid

Find the minimum number of insertions to balance parentheses.

Sliding Windowminimum-window-substring

Minimum Window Substring

Find the smallest substring containing all characters of a target string by expanding and contracting a sliding window.

Arraysmissing-number

Missing Number

Use the Gauss sum formula: expected sum minus actual sum gives the missing number.

Arraysmove-zeroes

Move Zeroes

Push non-zero values toward the front with a write pointer, then fill the tail with zeroes.

Backtrackingn-queens

N-Queens

Place N queens on an NxN board so none attack each other, using sets for diagonals.

Graphsnetwork-delay-time

Network Delay Time

Broadcast a signal through a weighted directed graph using Dijkstra's Algorithm to find total transmission time.

Stacks and Queuesnext-greater-element-i

Next Greater Element I

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

Stacks and Queuesnext-greater-element-ii

Next Greater Element II

Simulate a circular array by scanning twice while the monotonic stack keeps candidate greater values.

Greedy Algorithmnon-overlapping-intervals

Non-overlapping Intervals

Sort intervals by earliest end time to minimize conflicts and maximize schedule space.

Graphsnumber-of-islands

Number of Islands

Identify and count disconnected land masses in a grid using recursive DFS flood filling.

Graphsnumber-of-operations-to-make-network-connected

Number of Operations to Make Network Connected

Count isolated network clusters using DSU and determine the minimum number of cables needed to bridge them.

Graphsnumber-of-ways-to-arrive-at-destination

Number of Ways to Arrive at Destination

Extend Dijkstra's algorithm to count the total number of distinct paths that achieve the absolute minimum travel time.

Linked Listodd-even-linked-list

Odd Even Linked List

Group odd and even indexed nodes separately, then combine them.

Graphspacific-atlantic-water-flow

Pacific Atlantic Water Flow

Multi-source DFS/BFS to find cells that can reach both the Pacific and Atlantic oceans.

Linked Listpalindrome-linked-list

Palindrome Linked List

Check for palindromes by reversing the second half and comparing.

Backtrackingpalindrome-partitioning

Palindrome Partitioning

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.

Dynamic Programmingpalindromic-substrings

Palindromic Substrings

Expand outwards from every single character and between every character to count all palindromes efficiently.

Dynamic Programmingpartition-equal-subset-sum

Partition Equal Subset Sum

Ensure the total sum is even, then iterate combinations to see if a subset strictly equals sum/2.

Greedy Algorithmpartition-labels

Partition Labels

Find last occurrences of each character, extending partition boundary until index catches up.

Binary Treepath-sum

Path Sum

DFS exploring root-to-leaf paths with a running sum. Backtrack when a path doesn't reach the target.

Binary Treepath-sum-top-down

Path Sum - Top Down

Top-down DFS carrying a running sum. Check newSum === target at leaves. An 'ans' flag locks in the result.

Binary Searchpeak-index-in-a-mountain-array

Peak Index in a Mountain Array

Binary search the turning point where the increasing slope switches into a decreasing slope.

Two Pointers & Sliding Windowpermutation-in-string

Permutation in String

Slide a fixed-size window and compare frequency balance with the target permutation.

Backtrackingpermutations

Permutations

Generate all possible permutations of an array by trying every unused element in each slot.

Backtrackingpermutations-ii

Permutations II

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.

Binary Treepopulating-next-right-pointers

Populating Next Right Pointers in Each Node

BFS level-by-level connecting each node's next pointer to the next node in the same level.

Recursionpower-of-two

Power of Two

Determine if a number is a power of 2 by recursively halving it.

Graphsprims-algorithm-mst

Prim's Algorithm (MST)

Constructs a Minimum Spanning Tree greedily by growing a single connected component and selecting the cheapest incident edge at each step.

Arraysproduct-of-array-except-self

Product of Array Except Self

Build prefix products from the left, then multiply in suffix products from the right.

Sortingquick-sort

Quick Sort

Partition array around pivot, recursively sort left and right halves using divide and conquer.

Strings - Advancedrabin-karp-code

Rabin Karp - Code

Find pattern matches in text using a rolling hash to avoid O(M) comparisons.

Strings - Advancedrabin-karp-algorithm

Rabin Karp Algorithm

Find pattern matches in text using a rolling hash to avoid O(M) comparisons.

Sortingradix-sort

Radix Sort

Sort numbers digit by digit from least significant to most significant using stable counting sort.

Graphsreconstruct-itinerary

Reconstruct Itinerary

Reconstruct a flight itinerary using Hierholzer's algorithm for finding an Eulerian Path.

Recursionrecursion-masterclass

Recursion Masterclass

Understand double recursion using the classic Fibonacci sequence.

Graphsredundant-connection

Redundant Connection

Use a Disjoint Set Union (DSU) structure to identify exactly which edge mathematically creates a cycle in a tree structure.

Dynamic Programmingregular-expression-matching

Regular Expression Matching

Enforce pattern combinations over wildcard/star lookbacks inside a 2D matrix matching rules.

Arraysremove-duplicates-from-sorted-array

Remove Duplicates from Sorted Array

Walk one pointer ahead to find distinct values and overwrite the front of the array in-place.

Linked Listremove-duplicates-from-sorted-list

Remove Duplicates from Sorted List

Bypass duplicates since they are adjacent in a sorted list.

Arraysremove-element

Remove Element

Overwrite matching values by copying non-matching elements toward the front of the array.

Linked Listremove-linked-list-elements

Remove Linked List Elements

Remove specific values from a list using a dummy node approach.

Linked Listremove-nth-node-from-end-of-list

Remove Nth Node From End of List

Maintain an n-gap between two pointers to find the node perfectly.

Stacks and Queuesremove-outermost-parentheses

Remove Outermost Parentheses

Track primitive depth and emit only the characters that are not on the outermost shell.

Linked Listreorder-list

Reorder List

Reorders a Linked List by splitting it into two halves, reversing the second half, and merging them alternately.

Strings - Advancedreorganize-string

Reorganize String

Rearrange a string so no two adjacent characters are the same.

Strings - Advancedrepeated-string-match

Repeated String Match

Find the minimum times 'a' must be repeated for 'b' to be a substring.

Linked Listreverse-linked-list

Reverse Linked List

Iteratively reverse a linked list using prev, curr, and next pointers.

Arraysreverse-string

Reverse String

Swap characters from both ends moving inward until the pointers meet in the middle.

Stringsreverse-string-ii

Reverse String II

Reverse the first k characters for every blocks of 2k characters.

Strings - Advancedreverse-words-in-a-string

Reverse Words in a String

Reverse the order of words in a string, cleaning up extra spaces.

Linked Listrotate-list

Rotate List

Form a circular list then break it at the correctly calculated point.

Stacks and Queuesrotting-oranges

Rotting Oranges

Run BFS level by level from every rotten orange so each minute spreads rot to fresh neighbors.

Binary Treesame-tree

Same Tree

Recursive DFS comparing two trees node by node. Both structure and values must match.

Binary Search Treesearch-in-a-binary-search-tree

Search in a Binary Search Tree

Compare the target with the current node and follow the only subtree that can still contain it.

Binary Searchsearch-in-rotated-sorted-array

Search in Rotated Sorted Array

At every step, one half of the rotated array is still sorted. Detect it and decide whether the target lies there.

Binary Treeserialize-and-deserialize-binary-tree

Serialize and Deserialize Binary Tree

Convert a binary tree to a string using level-order traversal (BFS), and reconstruct the exact same tree from the string.

Graphsshortest-path-in-binary-matrix

Shortest Path in Binary Matrix

Navigate an 8-directional binary grid using BFS to find the minimal distance from start to finish.

Graphsshortest-path-in-unweighted-graph-using-bfs

Shortest Path in Unweighted Graph - BFS

Finds the shortest path from a source node to all other nodes in an unweighted graph using Level Order Traversal (BFS).

Binary Searchsingle-element-in-a-sorted-array

Single Element in a Sorted Array

Use index parity around matched pairs to tell which side still has the broken pairing pattern.

Arrayssingle-number

Single Number

XOR all values together so duplicate pairs cancel out and only the unique number remains.

Two Pointers & Sliding Windowsliding-window-maximum

Sliding Window Maximum

Maintain a decreasing deque of indices so the current maximum is always at the front.

Stringssplit-a-string-in-balanced-strings

Split a String in Balanced Strings

Maintain a balance counter, increment for 'L' and decrement for 'R'. Split when balance is 0.

Binary Searchsqrtx

Sqrt(x)

Binary search the integer answer space and keep the largest mid whose square does not exceed x.

Backtrackingsubsets

Subsets

Generate all possible subsets (the power set) by exploring include and exclude decisions recursively.

Backtrackingsubsets-ii

Subsets II

Generate all unique subsets from an array that may contain duplicates by sorting and skipping.

Binary Treesubtree-of-another-tree

Subtree of Another Tree

For each node in the main tree, check if the subtree rooted there matches the target tree.

Binary Treesubtree-of-another-tree-serialization

Subtree of Another Tree (Serialization)

Pre-order serialize both trees with null markers, then check if subRoot's string is a substring of root's string.

Recursionsum-of-all-numbers-in-array

Sum of All Numbers in Array

Recursively sum the elements of an array by moving an index to the base case.

Strings - Advancedsum-of-beauty-of-all-substrings

Sum of Beauty of All Substrings

Find the total beauty sum across all contiguous substrings.

Recursionsum-of-first-n-numbers

Sum of First N Numbers

Sum numbers down to 0 using a basic recursive call stack.

Dynamic Programmingsuper-egg-drop

Super Egg Drop

Find minimum moves to determine critical floor using k eggs.

Linked Listswap-nodes-in-pairs

Swap Nodes in Pairs

Swap adjacent nodes iteratively by keeping track of the previous node.

Graphsswim-in-rising-water

Swim in Rising Water

Find the minimum time to swim to the target using Dijkstra on a grid of elevations.

Binary Treesymmetric-tree

Symmetric Tree

Recursive mirror check comparing left.left with right.right and left.right with right.left.

Binary Treesymmetric-tree-iterative

Symmetric Tree - Iterative

Iterative BFS using a queue: enqueue mirror pairs, dequeue two at a time, validate, and push children in mirror order.

Greedy Algorithmtask-scheduler

Task Scheduler

Calculate hypothetical idle periods based on the most frequent task, then fill gaps.

Heap / Priority Queuetop-k-frequent-elements

Top K Frequent Elements

Count frequencies, then push into a min-heap keyed by frequency and cap it at size k.

Graphstopological-sort-using-dfs

Topological Sort - DFS

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.

Two Pointers & Sliding Windowtrapping-rain-water

Trapping Rain Water

Track the best wall seen from both sides and trap water above shorter boundaries.

Greedy Algorithmtwo-city-scheduling

Two City Scheduling

Calculate cost differences to greedily send the people generating maximum relative savings to City A.

Two Pointers & Sliding Windowtwo-sum

Two Sum

Scan once with a hashmap of seen values and resolve the complement the moment it appears.

Two Pointers & Sliding Windowtwo-sum-ii-input-array-is-sorted

Two Sum II - Input Array Is Sorted

Use the sorted order to squeeze two pointers inward until the sum matches the target.

Dynamic Programmingunique-paths

Unique Paths

Map combinations by simulating paths from Top and paths from Left, optimized into O(M) space.

Stringsvalid-anagram

Valid Anagram

Build a hash map of character counts for s, then decrement the counts while iterating over t.

Stringsvalid-palindrome

Valid Palindrome

Use left and right pointers to scan inwards, skipping symbols and checking equality.

Hashingvalid-palindrome-approach-1-extra-space

Valid Palindrome - Approach 1 - Extra Space

Create a cleaned lowercase copy, reverse it into extra space, and compare both strings directly.

Stacks and Queuesvalid-parentheses

Valid Parentheses

Push opening brackets and match them off in reverse order whenever a closing bracket arrives.

Binary Search Treevalidate-binary-search-tree

Validate Binary Search Tree

Carry valid lower and upper bounds down the tree to verify every node respects BST ordering.

Dynamic Programmingword-break

Word Break

Check if segments of the string can be matched against an exact hash set dictionary iteratively.

Graphsword-ladder

Word Ladder

Find the shortest transformation sequence between two words using BFS on word mutations.

Backtrackingword-search

Word Search

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.

    DSA Visualizers — 200+ Interactive Algorithm Walkthroughs — Engineering Core Log