depth first search
depth first search is one of the most repeated interview dimensions. Start with edge-safe fundamentals, then move into pattern-level trade-offs.
Interview Signal
Frequently tests problem modeling, edge handling, and verbal clarity.
Common Pitfall
Template-only answers break under follow-up questioning.
Practice Strategy
Practice in 3-5 problem rounds and always review complexity alternatives.
Recommended Progression
Word Search
Solve Word Search with backtracking by exploring adjacent cells to match a target word in a grid.
Binary Tree Inorder Traversal
Binary Tree Inorder Traversal asks you to visit left subtree, node, then right subtree without losing position while mov…
Validate Binary Search Tree
Validate Binary Search Tree problem checks if a binary tree satisfies BST properties using tree traversal and state trac…
Recover Binary Search Tree
Recover a BST where two nodes are swapped by mistake using in-order traversal and careful state tracking to restore corr…
Same Tree
Check whether two binary trees are identical by comparing structure and node values using DFS or BFS traversal strategie…
Symmetric Tree
Determine if a binary tree is symmetric by comparing left and right subtrees using DFS or BFS traversal techniques effic…
Maximum Depth of Binary Tree
Find the maximum depth of a binary tree using traversal techniques to track the longest path from root to leaf.
Balanced Binary Tree
Determine if a binary tree is height-balanced using tree traversal and state tracking techniques.
Minimum Depth of Binary Tree
Find the minimum depth of a binary tree, which is the shortest path from the root node to the nearest leaf node.
Path Sum
Determine if a binary tree has a root-to-leaf path where the sum of node values equals a given target sum, using DFS or …
Path Sum II
Find all root-to-leaf paths in a binary tree where the sum of node values equals a given target using DFS backtracking.
Flatten Binary Tree to Linked List
Flatten a binary tree into a right-skewed linked list by manipulating pointers following a pre-order traversal, handling…
Populating Next Right Pointers in Each Node
Connect each node across every level by reusing established next links to traverse a perfect binary tree without extra q…
Populating Next Right Pointers in Each Node II
Populate each next pointer in a binary tree to its immediate right node, handling nulls and uneven levels efficiently us…
Binary Tree Maximum Path Sum
Calculate the maximum sum of any path in a binary tree by exploring all node sequences using DFS and dynamic programming…
Sum Root to Leaf Numbers
Calculate the sum of all root-to-leaf numbers in a binary tree where each path represents a number.
Surrounded Regions
Transform the matrix in-place by marking regions surrounded by 'X' as 'X', while keeping border-adjacent 'O's intact.
Clone Graph
Clone Graph involves cloning a graph using DFS, focusing on graph traversal and neighbor management using hash tables.
Binary Tree Preorder Traversal
Perform a binary tree preorder traversal by visiting root nodes first, then left and right subtrees, tracking state iter…
Binary Tree Postorder Traversal
Solve Binary Tree Postorder Traversal using state tracking and binary-tree traversal techniques, focusing on Stack, Tree…
Binary Tree Right Side View
The Binary Tree Right Side View problem asks you to return the visible nodes from the right side of a binary tree, trave…
Number of Islands
Count the number of distinct islands in a binary grid using array traversal combined with depth-first search exploration…
Course Schedule II
Solve the 'Course Schedule II' problem using graph indegree and topological ordering, utilizing DFS or BFS to find the c…
Design Add and Search Words Data Structure
Build a WordDictionary supporting dynamic word addition and search with wildcard matching efficiently using Trie and DFS…
Invert Binary Tree
Invert Binary Tree swaps every node's left and right children using tree traversal, with recursive DFS or iterative BFS …
Kth Smallest Element in a BST
Find the kth smallest element in a BST by leveraging in-order traversal to efficiently track node order and count.
Lowest Common Ancestor of a Binary Search Tree
Find the lowest common ancestor (LCA) of two nodes in a binary search tree, using binary-tree traversal and state tracki…
Lowest Common Ancestor of a Binary Tree
Identify the lowest common ancestor of two nodes in a binary tree using traversal and state tracking techniques efficien…
Binary Tree Paths
Find all root-to-leaf paths in a binary tree using DFS and backtracking, constructing strings for each complete path eff…
Serialize and Deserialize Binary Tree
This problem asks to serialize and deserialize a binary tree, requiring an efficient approach to handle traversal and st…
Minimum Height Trees
Identify all roots of a tree that produce minimum height using graph indegree analysis and topological trimming.
Longest Increasing Path in a Matrix
Find the length of the longest increasing path in a matrix with given movement constraints using graph techniques.
Reconstruct Itinerary
Reconstruct Itinerary requires building a valid travel route using all tickets once, starting from JFK with lexical orde…
House Robber III
Maximize the loot by robbing non-adjacent houses in a binary tree structure using dynamic programming and DFS.
Flatten Nested List Iterator
Implement an iterator to flatten a nested list of integers, accounting for potential nesting levels.
Water and Jug Problem
Determine if two jugs with given capacities can measure an exact target amount using math and DFS strategies efficiently…
Mini Parser
Deserialize a nested list string using stack-based state management, handling integers and nested lists with depth-first…
Lexicographical Numbers
Generate all numbers from 1 to n in lexicographical order using a depth-first search pattern optimized with trie logic f…
Longest Absolute File Path
Find the length of the longest absolute file path in a filesystem string using stack-based depth tracking efficiently.
Evaluate Division
Compute the results of division queries from given equations using graph traversal and depth-first search efficiently.
Sum of Left Leaves
Compute the total of all left leaves in a binary tree using precise traversal and state tracking techniques for correctn…
Pacific Atlantic Water Flow
Find all cells on an island where water can flow to both the Pacific and Atlantic oceans using DFS or BFS.
Battleships in a Board
Count the number of non-overlapping battleships on a 2D board using array traversal and depth-first search patterns effi…
Flatten a Multilevel Doubly Linked List
Flatten a multilevel doubly linked list by correctly updating next, prev, and child pointers to create a single-level se…
Path Sum III
Path Sum III challenges you to count paths in a binary tree that sum to a given target value with downward traversal.
Serialize and Deserialize BST
Design an algorithm to serialize and deserialize a binary search tree with efficient traversal and state tracking.
Island Perimeter
Determine the perimeter of an island in a grid of land and water cells using DFS or BFS.
Concatenated Words
Find concatenated words by using dynamic programming and depth-first search to identify valid words made of other words …
Find Mode in Binary Search Tree
Find Mode in Binary Search Tree asks to identify the most frequent element(s) in a BST using binary-tree traversal.
Most Frequent Subtree Sum
Identify the most frequent subtree sum in a binary tree using DFS and hash table tracking for efficient state management…
Find Bottom Left Tree Value
Find the leftmost value in the last row of a binary tree using efficient traversal strategies.
Freedom Trail
Determine the minimum rotations and button presses to spell a keyword on a circular dial using state transition dynamic …
Find Largest Value in Each Tree Row
Find the largest value in each row of a binary tree using depth-first or breadth-first search techniques.
Minesweeper
Solve the Minesweeper game by updating revealed squares and handling clicks with Depth-First Search and Array manipulati…
Minimum Absolute Difference in BST
Find the minimum absolute difference between values of any two nodes in a BST using tree traversal and careful state tra…
Convert BST to Greater Tree
Convert a BST into a Greater Tree by updating each node’s value with the sum of all greater values in the tree.
Diameter of Binary Tree
The Diameter of Binary Tree problem involves finding the longest path between any two nodes using tree traversal techniq…
Number of Provinces
Solve Number of Provinces by scanning the adjacency matrix and launching DFS once per unvisited city component.
Maximum Depth of N-ary Tree
Find the maximum depth of an N-ary tree, leveraging tree traversal techniques and state tracking.
Binary Tree Tilt
Calculate the sum of the binary tree's node tilts using tree traversal and state tracking.
Array Nesting
Find the longest nested set in a permutation array using a depth-first traversal, handling cycles efficiently for medium…
Subtree of Another Tree
Determine if one binary tree is an exact subtree of another by comparing structure and node values recursively.
N-ary Tree Preorder Traversal
Solve the N-ary Tree Preorder Traversal problem using depth-first search and stack-based traversal methods.
N-ary Tree Postorder Traversal
Postorder traversal of an N-ary tree can be efficiently solved using DFS and stack-based methods, tracking state across …
Construct String from Binary Tree
Given a binary tree, construct a string representation based on preorder traversal while adhering to specific formatting…
Merge Two Binary Trees
Merge Two Binary Trees requires combining nodes by summing overlapping values while preserving non-null nodes from eithe…
Add One Row to Tree
The problem requires adding a row of nodes to a binary tree at a specified depth.
Average of Levels in Binary Tree
Calculate the average value of nodes on each level of a binary tree using traversal and state tracking.
Find Duplicate Subtrees
Identify all duplicate subtrees in a binary tree by efficiently tracking structure and values with depth-first traversal…
Two Sum IV - Input is a BST
Determine if a binary search tree contains two nodes whose values sum to a target using efficient traversal and state tr…
Print Binary Tree
Print Binary Tree requires arranging a binary tree into a visually structured matrix using precise traversal and positio…
Maximum Width of Binary Tree
Determine the maximum width of a binary tree by calculating the width of each level and considering the positions of the…
Trim a Binary Search Tree
Trim a Binary Search Tree by maintaining its structure while removing nodes outside a given range.
Second Minimum Node In a Binary Tree
Find the second minimum node in a binary tree by traversing the tree and tracking state.
Bulb Switcher II
Compute all unique bulb configurations after a fixed number of presses using math and bit manipulation efficiently.
Implement Magic Dictionary
Design a Magic Dictionary to allow searching with one-character modifications, using Hash Table and String techniques.
Redundant Connection
Identify and remove the redundant edge that causes a cycle in a graph starting as a tree.
Redundant Connection II
Find and remove the redundant connection in a directed graph that was originally a rooted tree.
Longest Univalue Path
Find the longest path in a binary tree where all nodes share the same value using depth-first search efficiently.
Employee Importance
Calculate an employee's total importance including all direct and indirect subordinates using array scanning and hash lo…
Max Area of Island
Find the largest connected land area in a binary grid using array traversal and depth-first search efficiently.
Accounts Merge
Merge accounts by connecting emails and returning each user's sorted email list using array scanning and hash lookup eff…
Flood Fill
Flood Fill is an array and DFS problem where you change connected pixels to a target color efficiently using recursion o…
Network Delay Time
Find the minimum time for a signal to travel to all nodes in a directed graph or determine if it's impossible.
Contain Virus
Contain Virus involves using array-based Depth-First Search to contain viral spread by building walls around infected re…
Cracking the Safe
The Cracking the Safe problem involves finding the shortest password sequence to unlock a safe using graph traversal and…
Pyramid Transition Matrix
The Pyramid Transition Matrix problem requires determining whether a pyramid can be formed with given blocks and valid p…
Couples Holding Hands
This problem requires arranging couples sitting apart in a row with the minimum number of swaps using graph traversal an…
Swim in Rising Water
Solve the problem of swimming through a grid of rising water with a binary search on the valid answer space.
Minimum Distance Between BST Nodes
Find the minimum difference between values of two different nodes in a Binary Search Tree using tree traversal and state…
Is Graph Bipartite?
Determine whether an undirected graph can be split into two independent sets using DFS, BFS, or Union Find patterns.
Cheapest Flights Within K Stops
Find the cheapest flight from a source to a destination with at most K stops using graph traversal techniques efficientl…
All Paths From Source to Target
Find all paths in a directed acyclic graph (DAG) from source to target using depth-first search and backtracking.
Find Eventual Safe States
Solve the problem of finding eventual safe states in a directed graph using depth-first search and topological sorting.
Binary Tree Pruning
Binary Tree Pruning removes subtrees not containing a 1, applying binary-tree traversal with state tracking.
Making A Large Island
Calculate the largest island size by converting at most one zero in a binary grid using array and DFS techniques efficie…
Sum of Distances in Tree
The problem asks to compute the sum of distances between each node and all others in a tree structure using depth-first …
Similar String Groups
Determine the number of connected groups of similar strings by swapping at most two letters using array scanning and has…
Keys and Rooms
Determine if all rooms can be visited given keys distributed across a set of interconnected locked rooms using graph tra…
Loud and Rich
Determine the quietest person richer than each individual using graph indegree analysis and topological ordering techniq…
All Nodes Distance K in Binary Tree
Find all nodes at distance K from a target node in a binary tree using various tree traversal techniques.
Smallest Subtree with all the Deepest Nodes
Find the smallest subtree that contains all the deepest nodes in a binary tree.
Leaf-Similar Trees
Determine if two binary trees have identical leaf sequences using efficient traversal and state tracking techniques.
Possible Bipartition
Determine if a group of n people with mutual dislikes can be split into two non-conflicting groups using graph traversal…
Increasing Order Search Tree
Rearrange a binary search tree so all nodes follow increasing order with only right children using in-order traversal.
Minimize Malware Spread
Identify which single infected node to remove to minimize total malware spread in a connected network graph efficiently.
Minimize Malware Spread II
Minimize Malware Spread II asks to minimize the spread of malware in a network of nodes by removing one infected node.
Shortest Bridge
Find the minimum flips to connect two separate islands in a binary matrix using Array and DFS techniques efficiently.
Range Sum of BST
Given a BST and a range, calculate the sum of all node values within that range.
Most Stones Removed with Same Row or Column
Maximize the number of stones removed from a 2D plane using graph traversal and DFS.
Flip Equivalent Binary Trees
Determine if two binary trees are flip equivalent by recursively swapping subtrees.
Regions Cut By Slashes
Determine the number of regions in a grid divided by slashes using array scanning and union-find techniques efficiently.
Univalued Binary Tree
Determine if a binary tree is uni-valued using traversal and state tracking techniques.
Binary Tree Cameras
Determine the minimum number of cameras required to monitor every node in a binary tree using efficient DFS and state tr…
Flip Binary Tree To Match Preorder Traversal
Determine the minimum set of nodes to flip in a binary tree so its pre-order traversal matches a given voyage sequence.
Distribute Coins in Binary Tree
Minimize the number of moves needed to distribute coins in a binary tree so that each node has exactly one coin.
Vertical Order Traversal of a Binary Tree
Perform a vertical order traversal of a binary tree, sorting nodes by their values within columns.
Smallest String Starting From Leaf
Determine the lexicographically smallest string from a leaf to root using binary-tree traversal and careful state tracki…
Cousins in Binary Tree
Determine if two nodes in a binary tree are cousins by leveraging binary-tree traversal and state tracking.
Number of Enclaves
This problem involves finding the number of land cells that cannot reach the boundary in a grid using DFS and array mani…
Sum of Root To Leaf Binary Numbers
Calculate the sum of binary numbers from root to leaf paths in a binary tree.
Maximum Difference Between Node and Ancestor
Find the maximum absolute difference between a node and its ancestor in a binary tree.
Recover a Tree From Preorder Traversal
Recover a binary tree from its preorder traversal string by tracking node depth and reconstructing child relationships e…
Coloring A Border
Given a grid and a starting cell, color all border cells of the connected component using DFS while preserving interior …
Escape a Large Maze
The 'Escape a Large Maze' problem involves navigating a massive grid with blocked squares and finding if a target can be…
Binary Search Tree to Greater Sum Tree
Convert a Binary Search Tree to a Greater Sum Tree by accumulating all larger node values using reverse in-order travers…
Flower Planting With No Adjacent
In this problem, you are tasked with planting flowers in gardens with specific constraints based on graph traversal prin…
Insufficient Nodes in Root to Leaf Paths
Remove nodes in a binary tree whose all root-to-leaf paths sum to less than a given limit using DFS traversal and state …
Delete Nodes And Return Forest
Delete nodes from a binary tree using array scanning and hash lookup to return the remaining forest efficiently.
Lowest Common Ancestor of Deepest Leaves
Find the lowest common ancestor of the deepest leaves in a binary tree using efficient traversal and state tracking tech…
Binary Tree Coloring Game
A two-player game where players color nodes in a binary tree, aiming to outmaneuver each other by choosing adjacent node…
Maximum Level Sum of a Binary Tree
Find the level of a binary tree where the sum of its nodes is maximal, with an emphasis on binary-tree traversal.
Critical Connections in a Network
Find critical connections in a network of servers, ensuring efficient traversal using depth-first search and Tarjan's al…
Smallest String With Swaps
Find the lexicographically smallest string by swapping characters in given pairs of indices.
Sort Items by Groups Respecting Dependencies
Sort items into groups while respecting dependencies using graph indegree tracking and topological ordering patterns eff…
Remove Sub-Folders from the Filesystem
Remove sub-folders in a filesystem by filtering out folders nested inside other folders.
Number of Closed Islands
Count the number of closed islands in a 2D grid using array traversal and depth-first search efficiently.
Find Elements in a Contaminated Binary Tree
Recover values in a contaminated binary tree and efficiently check for existence using traversal and state tracking tech…
Count Servers that Communicate
Count Servers that Communicate involves identifying servers in a grid that can communicate based on row or column connec…
Deepest Leaves Sum
Find the sum of the deepest leaves in a binary tree by using tree traversal and state tracking techniques.
All Elements in Two Binary Search Trees
Merge elements from two binary search trees and return them sorted in ascending order.
Jump Game III
Jump Game III challenges you to determine if you can reach any zero in an array using jumps defined by array values, tes…
Sum of Nodes with Even-Valued Grandparent
This problem involves calculating the sum of nodes with an even-valued grandparent in a binary tree.
Number of Operations to Make Network Connected
Determine the minimum number of operations required to connect all computers in a network with a limited number of cable…
Delete Leaves With a Given Value
In this problem, you need to delete all leaf nodes in a binary tree with a given target value, performing continuous del…
Maximum Product of Splitted Binary Tree
Maximize the product of sums of two subtrees formed by splitting a binary tree.
Validate Binary Tree Nodes
Validate Binary Tree Nodes problem requires checking if a set of nodes forms a valid binary tree using graph traversal.
Linked List in Binary Tree
Determine if a linked list is represented as a downward path in a binary tree using pointer traversal and recursive chec…
Longest ZigZag Path in a Binary Tree
Find the longest ZigZag path in a binary tree using depth-first search and dynamic programming for precise node state tr…
Maximum Sum BST in Binary Tree
Find the maximum sum of values from any Binary Search Tree (BST) subtree in a binary tree.
Time Needed to Inform All Employees
Calculate the time needed for the head of a company to inform all employees using tree traversal techniques.
Frog Position After T Seconds
The problem asks for the probability that a frog reaches a target vertex after t seconds in a tree graph.
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Find the corresponding node in a cloned binary tree using binary-tree traversal and state tracking.
Balance a Binary Search Tree
This problem requires balancing a binary search tree using in-order traversal and state tracking techniques.
Check if There is a Valid Path in a Grid
Check if there is a valid path from the upper-left to the bottom-right corner of a grid using depth-first search.
Minimum Time to Collect All Apples in a Tree
Minimize the time spent to collect all apples in a tree, considering traversal and state tracking with binary tree techn…
Count Good Nodes in Binary Tree
Count Good Nodes in Binary Tree identifies nodes exceeding all previous values along their path using DFS traversal tech…
Pseudo-Palindromic Paths in a Binary Tree
Count all root-to-leaf paths in a binary tree that can be rearranged to form a palindrome using bitwise state tracking.
Course Schedule IV
Determine if one course is a prerequisite of another using graph indegree tracking and topological ordering efficiently.
Reorder Routes to Make All Paths Lead to the City Zero
Reorder Routes to Make All Paths Lead to the City Zero involves reversing the direction of roads in a tree to ensure all…
Kth Ancestor of a Tree Node
Find the kth ancestor of any node in a tree using efficient binary-tree traversal and dynamic state tracking methods.
Number of Nodes in the Sub-Tree With the Same Label
Compute the number of nodes in each subtree sharing the same label using DFS with hash table aggregation efficiently.
Number of Good Leaf Nodes Pairs
Find the number of good leaf node pairs in a binary tree where the shortest path between them is less than or equal to a…
Detect Cycles in 2D Grid
Detect cycles in a 2D character grid using DFS while carefully tracking parent cells to avoid invalid revisits.
Minimum Number of Days to Disconnect Island
Find the minimum number of days to disconnect an island in a grid using depth-first search.
Throne Inheritance
Throne Inheritance requires modeling a dynamic family tree with births and deaths to determine the kingdom's inheritance…
Lexicographically Smallest String After Applying Operations
Optimize a string through rotations and additions to get the lexicographically smallest possible result using string man…
Path With Minimum Effort
Find the minimum effort required to travel from the top-left to the bottom-right of a grid, considering height differenc…
Minimize Hamming Distance After Swap Operations
Solve Minimize Hamming Distance After Swap Operations by grouping swappable indices and matching value counts inside eac…
Restore the Array From Adjacent Pairs
Restore the Array From Adjacent Pairs reconstructs a sequence using adjacent element pairs. Efficient hash lookups and a…
Tree of Coprimes
Determine the closest coprime ancestor for each node in a tree using efficient traversal and state tracking of node valu…
Count Sub Islands
Identify and count all islands in grid2 that are fully contained within islands of grid1 using DFS traversal efficiently…
Merge BSTs to Create Single BST
This problem asks you to merge multiple BSTs into a single valid BST by performing a series of operations.
Maximum Genetic Difference Query
Find the maximum genetic difference along paths in a tree using array scanning and hash lookups with XOR calculations.
Last Day Where You Can Still Cross
Find the last day to walk from top to bottom in a flooded matrix by using binary search and graph traversal techniques.
Find if Path Exists in Graph
Determine if a valid path exists between two vertices in a bi-directional graph using traversal techniques.
Find All Groups of Farmland
Identify all rectangular farmland groups in a binary matrix using array traversal and depth-first search efficiently.
Operations on Tree
Design a tree data structure that allows locking, unlocking, and upgrading nodes with user-specific actions.
Smallest Missing Genetic Value in Each Subtree
Determine the smallest missing genetic value in each subtree using binary-tree traversal and precise state tracking effi…
Count Nodes With the Highest Score
Find the number of nodes with the highest score in a binary tree, based on subtree sizes and node removal.
Find All People With Secret
Find all people who receive a secret through meetings using graph traversal with depth-first search efficiently and corr…
Step-By-Step Directions From a Binary Tree Node to Another
Find the shortest path between two nodes in a binary tree and output the directions as a string of 'L', 'R', and 'U'.
Valid Arrangement of Pairs
Given pairs of numbers, find a valid arrangement where each pair follows a specific condition.
Detonate the Maximum Bombs
Determine the maximum number of bombs that can be detonated by leveraging chain reactions using graph traversal and DFS …
Maximum Employees to Be Invited to a Meeting
Determine the maximum employees to invite based on favorite adjacency constraints using graph indegree and topological o…
All Ancestors of a Node in a Directed Acyclic Graph
Solve the All Ancestors of a Node in a Directed Acyclic Graph problem using graph traversal techniques like BFS, DFS, an…
Longest Path With Different Adjacent Characters
Find the longest path in a tree where adjacent nodes have different characters using graph DFS and topological reasoning…
Count Nodes Equal to Average of Subtree
Given a binary tree, count nodes where the value equals the average of values in its subtree.
Count Unreachable Pairs of Nodes in an Undirected Graph
Calculate the total number of node pairs in an undirected graph that cannot reach each other using DFS, BFS, or Union Fi…
Minimum Score After Removals on a Tree
Compute the minimum score after removing two edges in a tree using DFS and XOR-based component tracking efficiently.
Number of Increasing Paths in a Grid
Solve Number of Increasing Paths in a Grid by turning cell comparisons into a DAG and counting paths with topological DP…
Evaluate Boolean Binary Tree
Determine the boolean outcome of a full binary tree by evaluating leaf and internal nodes using depth-first traversal.
Find Closest Node to Given Two Nodes
Find the node that minimizes the maximum distance to two given nodes in a directed graph with one outgoing edge per node…
Longest Cycle in a Graph
The problem asks to find the longest cycle in a directed graph with specific edge constraints.
Reachable Nodes With Restrictions
In the 'Reachable Nodes With Restrictions' problem, find the maximum reachable nodes from node 0 in a tree while avoidin…
Amount of Time for Binary Tree to Be Infected
The problem asks to calculate the number of minutes for an infection to spread across all nodes in a binary tree startin…
Reverse Odd Levels of Binary Tree
Reverse the node values at each odd level in a perfect binary tree, preserving the even levels.
Create Components With Same Value
Maximize the number of components in a tree with equal sums by carefully deleting edges using divisor-based logic.
Height of Binary Tree After Subtree Removal Queries
Compute the height of a binary tree efficiently after removing subtrees, using traversal and precomputed node state trac…
Most Profitable Path in a Tree
Solve the 'Most Profitable Path in a Tree' problem using graph traversal and depth-first search techniques to maximize A…
Closest Nodes Queries in a Binary Search Tree
Solve the problem of finding closest nodes in a Binary Search Tree for multiple queries, efficiently handling each query…
Minimum Fuel Cost to Report to the Capital
Calculate the minimum fuel needed for all city representatives to reach the capital using DFS on a tree graph efficientl…
Minimum Score of a Path Between Two Cities
Find the minimum distance in a path connecting two cities using graph traversal strategies efficiently.
Divide Nodes Into the Maximum Number of Groups
Determine the maximum number of groups nodes can form in a graph using depth-first traversal without violating edge conn…
Difference Between Maximum and Minimum Price Sum
Compute the maximum difference between any path price sum in a tree using binary-tree traversal and state tracking effic…
Disconnect Path in a Binary Matrix by at Most One Flip
Determine if a single cell flip can disconnect a path from the top-left to bottom-right in a binary matrix efficiently u…
Count Number of Possible Root Nodes
Given a tree and a set of guesses, find how many nodes can be the root while satisfying the guess constraints.
Check Knight Tour Configuration
Validate a knight's movement configuration on an n x n chessboard to check if it forms a valid Knight's Tour.
Cousins in Binary Tree II
Replace each node in a binary tree with the sum of all its cousins by carefully tracking depth and parent relationships.
Minimize the Total Price of the Trips
Calculate the minimum total cost of multiple trips on a tree by selectively halving node prices using DFS frequency coun…
Maximum Number of Fish in a Grid
Maximize the number of fish that can be caught by performing DFS on an optimal starting point in a grid.
Count the Number of Complete Components
Determine the number of complete connected components in an undirected graph using efficient traversal techniques and gr…
Count Paths That Can Form a Palindrome in a Tree
This problem asks you to count all node pairs in a tree whose path characters can be rearranged into a palindrome using …
Minimum Edge Reversals So Every Node Is Reachable
This problem requires solving a graph traversal with edge reversals to ensure every node is reachable in a tree-like str…
Count Valid Paths in a Tree
Count Valid Paths in a Tree involves finding paths with exactly one prime number in a tree of n nodes.
Maximum Number of K-Divisible Components
Determine the maximum number of connected components in a tree where each component sum is divisible by k using DFS.
Maximum Points After Collecting Coins From All Nodes
Find the maximum points after collecting coins from all nodes of a tree using binary-tree traversal and state tracking.
Maximum Score After Applying Operations on a Tree
Solve Maximum Score After Applying Operations on a Tree by turning healthy-path constraints into subtree DP and forced-v…
Find Number of Coins to Place in Tree Nodes
Determine the exact number of coins to place on each tree node using subtree cost products and DFS tracking.
Count Pairs of Connectable Servers in a Weighted Tree Network
This problem involves counting pairs of connectable servers in a weighted tree network using binary-tree traversal and D…
Find Edges in Shortest Paths
Use two Dijkstra runs to mark exactly which edges can appear on at least one shortest path from 0 to n - 1.
Find Minimum Diameter After Merging Two Trees
Calculate the minimum diameter after merging two trees by strategically connecting nodes to minimize the longest path in…
Check if the Rectangle Corner Is Reachable
Determine if there is a valid path from the bottom-left to top-right of a rectangle while avoiding circles.
Time Taken to Mark All Nodes
Calculate the time taken to mark all nodes in a tree, starting from any node with time t=0.
Count the Number of Good Nodes
Determine how many nodes in a binary tree have all child subtrees of equal size using DFS traversal efficiently.
Remove Methods From Project
Remove suspicious methods in a project that are invoked directly or indirectly from a buggy method using graph traversal…
K-th Largest Perfect Subtree Size in Binary Tree
Find the size of the kth largest perfect subtree in a binary tree using tree traversal and state tracking.
Check if DFS Strings Are Palindromes
Determine if strings formed by DFS traversal of a tree are palindromes using array scanning and hash lookups efficiently…
Find Subtree Sizes After Changes
Calculate the sizes of all subtrees after simultaneous parent changes using array scanning and hash-based counting effic…
Maximize Sum of Weights after Edge Removals
Maximize the sum of edge weights in a tree after removals, using dynamic programming and tree traversal techniques.
Maximize the Number of Target Nodes After Connecting Trees I
Maximize the number of target nodes after connecting two trees using binary tree traversal and state tracking.
Maximize the Number of Target Nodes After Connecting Trees II
Maximize the number of target nodes after connecting two trees by analyzing their structure and target relationships.
Minimum Time to Break Locks I
Solve the Minimum Time to Break Locks I problem using state transition dynamic programming to minimize the time to break…
Maximize Amount After Two Days of Conversions
Compute the maximum currency amount after two days using graph traversal and depth-first search for optimal conversions.
Minimize the Maximum Edge Weight of Graph
Minimize the maximum edge weight in a graph after removing certain edges while ensuring node reachability.
Longest Special Path
Compute the longest downward path in a tree with unique node values using DFS, hash lookup, and careful array scanning.
Longest Special Path II
Find the longest downward path in a tree where node values are mostly distinct, allowing one repeat, using array scannin…
Properties Graph
Find the number of connected components in an undirected graph formed by properties arrays, using array scanning and has…
Shortest Path in a Weighted Tree
Solve the Shortest Path in a Weighted Tree using binary-tree traversal and efficient state tracking for queries.
Unit Conversion I
Solve the unit conversion problem by using graph traversal to compute equivalent unit amounts.
Subtree Inversion Sum
This problem involves calculating the maximum possible subtree inversion sum with dynamic programming and binary-tree tr…
Maximum Sum of Edge Values in a Graph
Maximize the sum of edge values in a connected graph by assigning unique node values and optimizing edge products.
Minimum Weighted Subgraph With the Required Paths II
Solve the Minimum Weighted Subgraph With the Required Paths II problem by leveraging binary-tree traversal and efficient…
Number of Ways to Assign Edge Weights I
Calculate the number of valid edge weight assignments in a tree using DFS and binary-tree traversal with careful state t…
Number of Ways to Assign Edge Weights II
This problem involves assigning edge weights in a tree and calculating the cost of paths based on these weights.
Maximum Profit from Trading Stocks with Discounts
Solve the Maximum Profit from Trading Stocks with Discounts problem using binary-tree traversal and dynamic state tracki…
Maximum Good Subtree Score
Find the maximum sum of values in a tree subtree without repeating any digit across selected nodes using DFS and bitmask…
Find Weighted Median Node in Tree
Given a weighted tree and queries, find the weighted median node for each path between two nodes using binary-tree trave…
Kth Smallest Path XOR Sum
This problem involves finding the kth smallest distinct XOR sum for nodes in a subtree of a tree structure using binary-…
Minimum Increments to Equalize Leaf Paths
Find the minimum number of increments needed to equalize leaf path scores in a tree with different node costs.
Power Grid Maintenance
Determine which power stations remain connected after maintenance using array scanning and hash lookups to track compone…
Count Islands With Total Value Divisible by K
Count the number of islands in a grid where the sum of each island's values is divisible by a given integer k.
Related Patterns
Binary-tree traversal and state tracking
127 linked problems
Graph traversal with depth-first search
43 linked problems
Array plus Depth-First Search
42 linked problems
Array scanning plus hash lookup
20 linked problems
Linked-list pointer manipulation
5 linked problems
State transition dynamic programming
4 linked problems