Jump Game II [Medium] — Greedy BFS-Level Jumps
Find minimum number of jumps to reach the last index using greedy BFS-style level tracking.
webcoderspeed.com
83 articles
Find minimum number of jumps to reach the last index using greedy BFS-style level tracking.
Master BFS and DFS on graphs and grids: islands, flood fill, shortest paths, connected components, and multi-source BFS with 5-language implementations.
Count connected land components in a binary grid using DFS flood fill or BFS. Classic easy problem, foundation for all island variants.
Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.
Calculate the perimeter of an island in a binary grid. Each land cell contributes 4 edges minus 2 for each land neighbour.
Find the maximum area of any island in a binary grid. DFS returns the area of each island, track the maximum.
Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.
Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.
For each cell find distance to nearest 0. Multi-source BFS from all 0s simultaneously gives optimal O(m*n) solution.
Fill each empty room with distance to nearest gate. Multi-source BFS from all gates (0) simultaneously, walls (-1) are barriers.
Count land cells that cannot reach the border. Boundary DFS marks all reachable land from borders, then count remaining land cells.
Count islands in grid2 that are subsets of islands in grid1. DFS the island in grid2 and verify every cell is also land in grid1.
Find the largest island after flipping exactly one 0 to 1. Color each island with DFS, store sizes, then check each 0 cell's unique neighbour islands.
Find cells that can flow to both Pacific and Atlantic oceans. Run DFS backwards from each ocean border, find intersection.
Find shortest clear path from top-left to bottom-right in binary matrix using 8-directional BFS. Return path length or -1.
Find the water cell farthest from any land. Multi-source BFS from all land cells gives each water cell its min distance to land.
Search for a word in a grid by moving to adjacent cells without reuse. DFS with backtracking: mark visited, recurse, unmark.
Count islands with distinct shapes. Encode each island's DFS traversal path as a string to capture shape, store in a set.
Count islands fully surrounded by water (no border touch). Flood-fill border land first, then count remaining connected land components.
Find minimum flips to connect two islands. DFS to find and color first island, then BFS outward until reaching second island.
Find path from top-left to bottom-right minimizing maximum absolute difference between consecutive cells. Use Dijkstra or binary search + BFS.
Count islands after each addLand operation. Online version requires Union-Find: add each land cell and union with adjacent land cells.
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).
BFS from entrance in a maze to find nearest exit (border empty cell). Classic BFS shortest path with exit condition.
Minimum dice rolls to reach square n^2. Convert board position to 2D coordinates (Boustrophedon order), BFS on board states.
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.
Complete cheatsheet for BFS and DFS on graphs and grids: 7 patterns, complexity table, common pitfalls, and problem index.
Calculate trapped water in a 3D height map using BFS with a min-heap to process cells from shortest boundary inward.
Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.
Find minutes until all oranges rot using multi-source BFS starting from all initially rotten oranges simultaneously.
Count islands in a 2D grid using BFS or DFS to flood-fill connected land cells, marking them visited.
Detect if all courses can be finished (no cycle) using Kahn's algorithm: BFS on in-degree zero nodes.
Return a valid course order using Kahn's BFS topological sort, or empty array if a cycle exists.
Find the shortest word transformation sequence using BFS where each step changes exactly one character.
Find cells that can flow to both oceans by doing reverse BFS from each ocean's borders and finding the intersection.
Fill each empty room with its distance to nearest gate using simultaneous multi-source BFS from all gates.
Serialize a binary tree to a string using BFS level-order and deserialize back using a queue for reconstruction.
Find the maximum depth of a binary tree using recursive DFS (one line) or iterative BFS level counting.
Return values grouped by level using BFS with a queue, processing each level in a batch loop.
Traverse a binary tree in zigzag level order by toggling insertion direction at each level.
Find the rightmost node at each level using BFS and taking the last element seen at each depth.
Connect each node to its next right node using BFS level order or O(1) space pointer manipulation.
Find all nodes at distance K from a target node by building parent pointers then doing BFS.
Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.
Group tree nodes by vertical column then row, sorting by value within same position using BFS with coordinates.
Verify a binary tree is complete using BFS: once a null child is seen, no more non-null nodes should follow.
Serialize a binary tree to string and back using BFS level-order or DFS preorder with null markers.
Perform level-order traversal of an N-ary tree using BFS, collecting all children at each level.
Find the level with the maximum sum using BFS level-order traversal to compute each level's total.
Find time for infection to spread through entire tree from a start node by converting to graph then doing BFS.
Find minimum swaps to sort each level of a binary tree using BFS and cycle-detection in permutation sorting.
Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.
Sum all nodes at the deepest level of a binary tree using BFS to process level by level.
Determine if two nodes are cousins (same depth, different parents) using BFS to track depth and parent.
Remove minimum invalid parentheses to produce all valid results. BFS approach for minimum removals, DFS for complete enumeration.
A* combines Dijkstra's correctness with a heuristic to guide search toward the goal. Uses f(n)=g(n)+h(n) priority. Optimal when heuristic is admissible.
Check if a graph is bipartite using BFS 2-coloring. A graph is bipartite if and only if it contains no odd-length cycles — equivalent to being 2-colorable.
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.
Introduction to network flow: max flow problem, Ford-Fulkerson algorithm with BFS (Edmonds-Karp), max-flow min-cut theorem, and applications in matching and connectivity.
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.
Serialize a binary tree to a string and deserialize it back. Meta loves this problem for testing tree traversal and string parsing. Both BFS and preorder DFS approaches shown.
Return the values visible from the right side of a binary tree — the last node of each BFS level. O(n) BFS with level tracking.
Calculate how much water can be trapped in a 3D height matrix. Uses a min-heap BFS starting from the boundary, always processing the lowest border cell to determine water trapped inside.