Clone Graph — BFS/DFS with HashMap
Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.
webcoderspeed.com
31 articles
Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.
Count connected components in an undirected graph given as adjacency matrix. DFS or Union-Find both work.
Determine if all rooms are reachable. Start from room 0, DFS using keys found in each room to unlock new rooms.
Check if a path exists between source and destination in an undirected graph. BFS from source or Union-Find both work in O(V+E).
Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.
Check if you can reach a 0 in the array by jumping arr[i] steps left or right. BFS/DFS from start index.
Determine if you can finish all courses given prerequisites. Equivalent to detecting a cycle in a directed graph using BFS (Kahn) or DFS coloring.
Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.
Check if n nodes and edges form a valid tree: must be connected and acyclic. Exactly n-1 edges, all connected via BFS/DFS or Union-Find.
Count connected components in an undirected graph. Union-Find or BFS both give O(V+E) solution.
Find the edge that creates a cycle in an undirected graph that started as a tree. Process edges with Union-Find; the first edge whose endpoints share a root is redundant.
Find all paths from node 0 to node n-1 in a DAG. DFS with backtracking: explore each path, add to results when destination reached.
Find time for signal to reach all nodes. Single-source shortest path (Dijkstra) from node k; answer is max of all shortest distances.
Find cheapest flight from src to dst with at most k stops. Bellman-Ford with k+1 iterations or BFS level-by-level.
Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.
Find ALL shortest transformation sequences. BFS builds layer map, DFS reconstructs all paths backwards from endWord to beginWord.
Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.
Check if people can be split into two groups with no dislikes within a group. Equivalent to bipartite check on dislikes graph.
Check if a graph can be 2-colored such that no adjacent nodes share a color. BFS/DFS 2-coloring on all connected components.
BFS with (position, last_jumped_back) state to find min jumps home avoiding forbidden positions. State space BFS avoids revisiting same position+direction.
Evaluate queries like A/C = A/B * B/C. Build weighted directed graph from equations, BFS/DFS to multiply edge weights along paths.
Count total reachable nodes in a subdivided graph within M moves. Dijkstra from node 0 gives max remaining moves at each node; use those to count subdivisions.
Detect if all courses can be finished (no cycle) using Kahn's algorithm: BFS on in-degree zero nodes.
Find the shortest word transformation sequence using BFS where each step changes exactly one character.
Find time for infection to spread through entire tree from a start node by converting to graph then doing BFS.
Find the path from source to destination minimising the maximum edge weight. Binary search on the answer + BFS/DFS connectivity check. O(E log W) total.
Find the itinerary using all flight tickets exactly once (Eulerian path). Uses Hierholzer's algorithm: DFS with post-order insertion into result — the only graph algorithm that uses post-order for path construction.
Derive character ordering from a sorted alien dictionary using topological sort. Build a directed graph from adjacent word comparisons and apply Kahn's BFS algorithm.
Count islands after each addLand operation using incremental Union-Find. Each new land cell potentially merges with up to 4 neighbors — classic Amazon system-at-scale problem.
Merge accounts sharing common email addresses using Union-Find. Group emails by owner, merge accounts with shared emails, sort each merged group.
Create a deep copy of an undirected graph using DFS with a HashMap to track visited/cloned nodes. Meta tests this to evaluate graph traversal and pointer manipulation.