LeetCodechevron_rightCategorieschevron_rightdepth first search
arrow_downward

depth first search

252 problems
Easy: 36Medium: 148Hard: 68

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

#TitleDifficulty
79

Word Search

Solve Word Search with backtracking by exploring adjacent cells to match a target word in a grid.

Medium
94

Binary Tree Inorder Traversal

Binary Tree Inorder Traversal asks you to visit left subtree, node, then right subtree without losing position while mov…

Easy
98

Validate Binary Search Tree

Validate Binary Search Tree problem checks if a binary tree satisfies BST properties using tree traversal and state trac…

Medium
99

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…

Medium
100

Same Tree

Check whether two binary trees are identical by comparing structure and node values using DFS or BFS traversal strategie…

Easy
101

Symmetric Tree

Determine if a binary tree is symmetric by comparing left and right subtrees using DFS or BFS traversal techniques effic…

Easy
104

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.

Easy
110

Balanced Binary Tree

Determine if a binary tree is height-balanced using tree traversal and state tracking techniques.

Easy
111

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.

Easy
112

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 …

Easy
113

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.

Medium
114

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…

Medium
116

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…

Medium
117

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…

Medium
124

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…

Hard
129

Sum Root to Leaf Numbers

Calculate the sum of all root-to-leaf numbers in a binary tree where each path represents a number.

Medium
130

Surrounded Regions

Transform the matrix in-place by marking regions surrounded by 'X' as 'X', while keeping border-adjacent 'O's intact.

Medium
133

Clone Graph

Clone Graph involves cloning a graph using DFS, focusing on graph traversal and neighbor management using hash tables.

Medium
144

Binary Tree Preorder Traversal

Perform a binary tree preorder traversal by visiting root nodes first, then left and right subtrees, tracking state iter…

Easy
145

Binary Tree Postorder Traversal

Solve Binary Tree Postorder Traversal using state tracking and binary-tree traversal techniques, focusing on Stack, Tree…

Easy
199

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…

Medium
200

Number of Islands

Count the number of distinct islands in a binary grid using array traversal combined with depth-first search exploration…

Medium
210

Course Schedule II

Solve the 'Course Schedule II' problem using graph indegree and topological ordering, utilizing DFS or BFS to find the c…

Medium
211

Design Add and Search Words Data Structure

Build a WordDictionary supporting dynamic word addition and search with wildcard matching efficiently using Trie and DFS…

Medium
226

Invert Binary Tree

Invert Binary Tree swaps every node's left and right children using tree traversal, with recursive DFS or iterative BFS …

Easy
230

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.

Medium
235

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…

Medium
236

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…

Medium
257

Binary Tree Paths

Find all root-to-leaf paths in a binary tree using DFS and backtracking, constructing strings for each complete path eff…

Easy
297

Serialize and Deserialize Binary Tree

This problem asks to serialize and deserialize a binary tree, requiring an efficient approach to handle traversal and st…

Hard
310

Minimum Height Trees

Identify all roots of a tree that produce minimum height using graph indegree analysis and topological trimming.

Medium
329

Longest Increasing Path in a Matrix

Find the length of the longest increasing path in a matrix with given movement constraints using graph techniques.

Hard
332

Reconstruct Itinerary

Reconstruct Itinerary requires building a valid travel route using all tickets once, starting from JFK with lexical orde…

Hard
337

House Robber III

Maximize the loot by robbing non-adjacent houses in a binary tree structure using dynamic programming and DFS.

Medium
341

Flatten Nested List Iterator

Implement an iterator to flatten a nested list of integers, accounting for potential nesting levels.

Medium
365

Water and Jug Problem

Determine if two jugs with given capacities can measure an exact target amount using math and DFS strategies efficiently…

Medium
385

Mini Parser

Deserialize a nested list string using stack-based state management, handling integers and nested lists with depth-first…

Medium
386

Lexicographical Numbers

Generate all numbers from 1 to n in lexicographical order using a depth-first search pattern optimized with trie logic f…

Medium
388

Longest Absolute File Path

Find the length of the longest absolute file path in a filesystem string using stack-based depth tracking efficiently.

Medium
399

Evaluate Division

Compute the results of division queries from given equations using graph traversal and depth-first search efficiently.

Medium
404

Sum of Left Leaves

Compute the total of all left leaves in a binary tree using precise traversal and state tracking techniques for correctn…

Easy
417

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.

Medium
419

Battleships in a Board

Count the number of non-overlapping battleships on a 2D board using array traversal and depth-first search patterns effi…

Medium
430

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…

Medium
437

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.

Medium
449

Serialize and Deserialize BST

Design an algorithm to serialize and deserialize a binary search tree with efficient traversal and state tracking.

Medium
463

Island Perimeter

Determine the perimeter of an island in a grid of land and water cells using DFS or BFS.

Easy
472

Concatenated Words

Find concatenated words by using dynamic programming and depth-first search to identify valid words made of other words …

Hard
501

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.

Easy
508

Most Frequent Subtree Sum

Identify the most frequent subtree sum in a binary tree using DFS and hash table tracking for efficient state management…

Medium
513

Find Bottom Left Tree Value

Find the leftmost value in the last row of a binary tree using efficient traversal strategies.

Medium
514

Freedom Trail

Determine the minimum rotations and button presses to spell a keyword on a circular dial using state transition dynamic …

Hard
515

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.

Medium
529

Minesweeper

Solve the Minesweeper game by updating revealed squares and handling clicks with Depth-First Search and Array manipulati…

Medium
530

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…

Easy
538

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.

Medium
543

Diameter of Binary Tree

The Diameter of Binary Tree problem involves finding the longest path between any two nodes using tree traversal techniq…

Easy
547

Number of Provinces

Solve Number of Provinces by scanning the adjacency matrix and launching DFS once per unvisited city component.

Medium
559

Maximum Depth of N-ary Tree

Find the maximum depth of an N-ary tree, leveraging tree traversal techniques and state tracking.

Easy
563

Binary Tree Tilt

Calculate the sum of the binary tree's node tilts using tree traversal and state tracking.

Easy
565

Array Nesting

Find the longest nested set in a permutation array using a depth-first traversal, handling cycles efficiently for medium…

Medium
572

Subtree of Another Tree

Determine if one binary tree is an exact subtree of another by comparing structure and node values recursively.

Easy
589

N-ary Tree Preorder Traversal

Solve the N-ary Tree Preorder Traversal problem using depth-first search and stack-based traversal methods.

Easy
590

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 …

Easy
606

Construct String from Binary Tree

Given a binary tree, construct a string representation based on preorder traversal while adhering to specific formatting…

Medium
617

Merge Two Binary Trees

Merge Two Binary Trees requires combining nodes by summing overlapping values while preserving non-null nodes from eithe…

Easy
623

Add One Row to Tree

The problem requires adding a row of nodes to a binary tree at a specified depth.

Medium
637

Average of Levels in Binary Tree

Calculate the average value of nodes on each level of a binary tree using traversal and state tracking.

Easy
652

Find Duplicate Subtrees

Identify all duplicate subtrees in a binary tree by efficiently tracking structure and values with depth-first traversal…

Medium
653

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…

Easy
655

Print Binary Tree

Print Binary Tree requires arranging a binary tree into a visually structured matrix using precise traversal and positio…

Medium
662

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…

Medium
669

Trim a Binary Search Tree

Trim a Binary Search Tree by maintaining its structure while removing nodes outside a given range.

Medium
671

Second Minimum Node In a Binary Tree

Find the second minimum node in a binary tree by traversing the tree and tracking state.

Easy
672

Bulb Switcher II

Compute all unique bulb configurations after a fixed number of presses using math and bit manipulation efficiently.

Medium
676

Implement Magic Dictionary

Design a Magic Dictionary to allow searching with one-character modifications, using Hash Table and String techniques.

Medium
684

Redundant Connection

Identify and remove the redundant edge that causes a cycle in a graph starting as a tree.

Medium
685

Redundant Connection II

Find and remove the redundant connection in a directed graph that was originally a rooted tree.

Hard
687

Longest Univalue Path

Find the longest path in a binary tree where all nodes share the same value using depth-first search efficiently.

Medium
690

Employee Importance

Calculate an employee's total importance including all direct and indirect subordinates using array scanning and hash lo…

Medium
695

Max Area of Island

Find the largest connected land area in a binary grid using array traversal and depth-first search efficiently.

Medium
721

Accounts Merge

Merge accounts by connecting emails and returning each user's sorted email list using array scanning and hash lookup eff…

Medium
733

Flood Fill

Flood Fill is an array and DFS problem where you change connected pixels to a target color efficiently using recursion o…

Easy
743

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.

Medium
749

Contain Virus

Contain Virus involves using array-based Depth-First Search to contain viral spread by building walls around infected re…

Hard
753

Cracking the Safe

The Cracking the Safe problem involves finding the shortest password sequence to unlock a safe using graph traversal and…

Hard
756

Pyramid Transition Matrix

The Pyramid Transition Matrix problem requires determining whether a pyramid can be formed with given blocks and valid p…

Medium
765

Couples Holding Hands

This problem requires arranging couples sitting apart in a row with the minimum number of swaps using graph traversal an…

Hard
778

Swim in Rising Water

Solve the problem of swimming through a grid of rising water with a binary search on the valid answer space.

Hard
783

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…

Easy
785

Is Graph Bipartite?

Determine whether an undirected graph can be split into two independent sets using DFS, BFS, or Union Find patterns.

Medium
787

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…

Medium
797

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.

Medium
802

Find Eventual Safe States

Solve the problem of finding eventual safe states in a directed graph using depth-first search and topological sorting.

Medium
814

Binary Tree Pruning

Binary Tree Pruning removes subtrees not containing a 1, applying binary-tree traversal with state tracking.

Medium
827

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…

Hard
834

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 …

Hard
839

Similar String Groups

Determine the number of connected groups of similar strings by swapping at most two letters using array scanning and has…

Hard
841

Keys and Rooms

Determine if all rooms can be visited given keys distributed across a set of interconnected locked rooms using graph tra…

Medium
851

Loud and Rich

Determine the quietest person richer than each individual using graph indegree analysis and topological ordering techniq…

Medium
863

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.

Medium
865

Smallest Subtree with all the Deepest Nodes

Find the smallest subtree that contains all the deepest nodes in a binary tree.

Medium
872

Leaf-Similar Trees

Determine if two binary trees have identical leaf sequences using efficient traversal and state tracking techniques.

Easy
886

Possible Bipartition

Determine if a group of n people with mutual dislikes can be split into two non-conflicting groups using graph traversal…

Medium
897

Increasing Order Search Tree

Rearrange a binary search tree so all nodes follow increasing order with only right children using in-order traversal.

Easy
924

Minimize Malware Spread

Identify which single infected node to remove to minimize total malware spread in a connected network graph efficiently.

Hard
928

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.

Hard
934

Shortest Bridge

Find the minimum flips to connect two separate islands in a binary matrix using Array and DFS techniques efficiently.

Medium
938

Range Sum of BST

Given a BST and a range, calculate the sum of all node values within that range.

Easy
947

Most Stones Removed with Same Row or Column

Maximize the number of stones removed from a 2D plane using graph traversal and DFS.

Medium
951

Flip Equivalent Binary Trees

Determine if two binary trees are flip equivalent by recursively swapping subtrees.

Medium
959

Regions Cut By Slashes

Determine the number of regions in a grid divided by slashes using array scanning and union-find techniques efficiently.

Medium
965

Univalued Binary Tree

Determine if a binary tree is uni-valued using traversal and state tracking techniques.

Easy
968

Binary Tree Cameras

Determine the minimum number of cameras required to monitor every node in a binary tree using efficient DFS and state tr…

Hard
971

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.

Medium
979

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.

Medium
987

Vertical Order Traversal of a Binary Tree

Perform a vertical order traversal of a binary tree, sorting nodes by their values within columns.

Hard
988

Smallest String Starting From Leaf

Determine the lexicographically smallest string from a leaf to root using binary-tree traversal and careful state tracki…

Medium
993

Cousins in Binary Tree

Determine if two nodes in a binary tree are cousins by leveraging binary-tree traversal and state tracking.

Easy
1020

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…

Medium
1022

Sum of Root To Leaf Binary Numbers

Calculate the sum of binary numbers from root to leaf paths in a binary tree.

Easy
1026

Maximum Difference Between Node and Ancestor

Find the maximum absolute difference between a node and its ancestor in a binary tree.

Medium
1028

Recover a Tree From Preorder Traversal

Recover a binary tree from its preorder traversal string by tracking node depth and reconstructing child relationships e…

Hard
1034

Coloring A Border

Given a grid and a starting cell, color all border cells of the connected component using DFS while preserving interior …

Medium
1036

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…

Hard
1038

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…

Medium
1042

Flower Planting With No Adjacent

In this problem, you are tasked with planting flowers in gardens with specific constraints based on graph traversal prin…

Medium
1080

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 …

Medium
1110

Delete Nodes And Return Forest

Delete nodes from a binary tree using array scanning and hash lookup to return the remaining forest efficiently.

Medium
1123

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…

Medium
1145

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…

Medium
1161

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.

Medium
1192

Critical Connections in a Network

Find critical connections in a network of servers, ensuring efficient traversal using depth-first search and Tarjan's al…

Hard
1202

Smallest String With Swaps

Find the lexicographically smallest string by swapping characters in given pairs of indices.

Medium
1203

Sort Items by Groups Respecting Dependencies

Sort items into groups while respecting dependencies using graph indegree tracking and topological ordering patterns eff…

Hard
1233

Remove Sub-Folders from the Filesystem

Remove sub-folders in a filesystem by filtering out folders nested inside other folders.

Medium
1254

Number of Closed Islands

Count the number of closed islands in a 2D grid using array traversal and depth-first search efficiently.

Medium
1261

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…

Medium
1267

Count Servers that Communicate

Count Servers that Communicate involves identifying servers in a grid that can communicate based on row or column connec…

Medium
1302

Deepest Leaves Sum

Find the sum of the deepest leaves in a binary tree by using tree traversal and state tracking techniques.

Medium
1305

All Elements in Two Binary Search Trees

Merge elements from two binary search trees and return them sorted in ascending order.

Medium
1306

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…

Medium
1315

Sum of Nodes with Even-Valued Grandparent

This problem involves calculating the sum of nodes with an even-valued grandparent in a binary tree.

Medium
1319

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…

Medium
1325

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…

Medium
1339

Maximum Product of Splitted Binary Tree

Maximize the product of sums of two subtrees formed by splitting a binary tree.

Medium
1361

Validate Binary Tree Nodes

Validate Binary Tree Nodes problem requires checking if a set of nodes forms a valid binary tree using graph traversal.

Medium
1367

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…

Medium
1372

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…

Medium
1373

Maximum Sum BST in Binary Tree

Find the maximum sum of values from any Binary Search Tree (BST) subtree in a binary tree.

Hard
1376

Time Needed to Inform All Employees

Calculate the time needed for the head of a company to inform all employees using tree traversal techniques.

Medium
1377

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.

Hard
1379

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.

Easy
1382

Balance a Binary Search Tree

This problem requires balancing a binary search tree using in-order traversal and state tracking techniques.

Medium
1391

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.

Medium
1443

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…

Medium
1448

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…

Medium
1457

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.

Medium
1462

Course Schedule IV

Determine if one course is a prerequisite of another using graph indegree tracking and topological ordering efficiently.

Medium
1466

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…

Medium
1483

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.

Hard
1519

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.

Medium
1530

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…

Medium
1559

Detect Cycles in 2D Grid

Detect cycles in a 2D character grid using DFS while carefully tracking parent cells to avoid invalid revisits.

Medium
1568

Minimum Number of Days to Disconnect Island

Find the minimum number of days to disconnect an island in a grid using depth-first search.

Hard
1600

Throne Inheritance

Throne Inheritance requires modeling a dynamic family tree with births and deaths to determine the kingdom's inheritance…

Medium
1625

Lexicographically Smallest String After Applying Operations

Optimize a string through rotations and additions to get the lexicographically smallest possible result using string man…

Medium
1631

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…

Medium
1722

Minimize Hamming Distance After Swap Operations

Solve Minimize Hamming Distance After Swap Operations by grouping swappable indices and matching value counts inside eac…

Medium
1743

Restore the Array From Adjacent Pairs

Restore the Array From Adjacent Pairs reconstructs a sequence using adjacent element pairs. Efficient hash lookups and a…

Medium
1766

Tree of Coprimes

Determine the closest coprime ancestor for each node in a tree using efficient traversal and state tracking of node valu…

Hard
1905

Count Sub Islands

Identify and count all islands in grid2 that are fully contained within islands of grid1 using DFS traversal efficiently…

Medium
1932

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.

Hard
1938

Maximum Genetic Difference Query

Find the maximum genetic difference along paths in a tree using array scanning and hash lookups with XOR calculations.

Hard
1970

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.

Hard
1971

Find if Path Exists in Graph

Determine if a valid path exists between two vertices in a bi-directional graph using traversal techniques.

Easy
1992

Find All Groups of Farmland

Identify all rectangular farmland groups in a binary matrix using array traversal and depth-first search efficiently.

Medium
1993

Operations on Tree

Design a tree data structure that allows locking, unlocking, and upgrading nodes with user-specific actions.

Medium
2003

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…

Hard
2049

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.

Medium
2092

Find All People With Secret

Find all people who receive a secret through meetings using graph traversal with depth-first search efficiently and corr…

Hard
2096

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

Medium
2097

Valid Arrangement of Pairs

Given pairs of numbers, find a valid arrangement where each pair follows a specific condition.

Hard
2101

Detonate the Maximum Bombs

Determine the maximum number of bombs that can be detonated by leveraging chain reactions using graph traversal and DFS …

Medium
2127

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…

Hard
2192

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…

Medium
2246

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…

Hard
2265

Count Nodes Equal to Average of Subtree

Given a binary tree, count nodes where the value equals the average of values in its subtree.

Medium
2316

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…

Medium
2322

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.

Hard
2328

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…

Hard
2331

Evaluate Boolean Binary Tree

Determine the boolean outcome of a full binary tree by evaluating leaf and internal nodes using depth-first traversal.

Easy
2359

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…

Medium
2360

Longest Cycle in a Graph

The problem asks to find the longest cycle in a directed graph with specific edge constraints.

Hard
2368

Reachable Nodes With Restrictions

In the 'Reachable Nodes With Restrictions' problem, find the maximum reachable nodes from node 0 in a tree while avoidin…

Medium
2385

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…

Medium
2415

Reverse Odd Levels of Binary Tree

Reverse the node values at each odd level in a perfect binary tree, preserving the even levels.

Medium
2440

Create Components With Same Value

Maximize the number of components in a tree with equal sums by carefully deleting edges using divisor-based logic.

Hard
2458

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…

Hard
2467

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…

Medium
2476

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…

Medium
2477

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…

Medium
2492

Minimum Score of a Path Between Two Cities

Find the minimum distance in a path connecting two cities using graph traversal strategies efficiently.

Medium
2493

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…

Hard
2538

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…

Hard
2556

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…

Medium
2581

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.

Hard
2596

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.

Medium
2641

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.

Medium
2646

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…

Hard
2658

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.

Medium
2685

Count the Number of Complete Components

Determine the number of complete connected components in an undirected graph using efficient traversal techniques and gr…

Medium
2791

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 …

Hard
2858

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…

Hard
2867

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.

Hard
2872

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.

Hard
2920

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.

Hard
2925

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…

Medium
2973

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.

Hard
3067

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…

Medium
3123

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.

Hard
3203

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…

Hard
3235

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.

Hard
3241

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.

Hard
3249

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.

Medium
3310

Remove Methods From Project

Remove suspicious methods in a project that are invoked directly or indirectly from a buggy method using graph traversal…

Medium
3319

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.

Medium
3327

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…

Hard
3331

Find Subtree Sizes After Changes

Calculate the sizes of all subtrees after simultaneous parent changes using array scanning and hash-based counting effic…

Medium
3367

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.

Hard
3372

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.

Medium
3373

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.

Hard
3376

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…

Medium
3387

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.

Medium
3419

Minimize the Maximum Edge Weight of Graph

Minimize the maximum edge weight in a graph after removing certain edges while ensuring node reachability.

Medium
3425

Longest Special Path

Compute the longest downward path in a tree with unique node values using DFS, hash lookup, and careful array scanning.

Hard
3486

Longest Special Path II

Find the longest downward path in a tree where node values are mostly distinct, allowing one repeat, using array scannin…

Hard
3493

Properties Graph

Find the number of connected components in an undirected graph formed by properties arrays, using array scanning and has…

Medium
3515

Shortest Path in a Weighted Tree

Solve the Shortest Path in a Weighted Tree using binary-tree traversal and efficient state tracking for queries.

Hard
3528

Unit Conversion I

Solve the unit conversion problem by using graph traversal to compute equivalent unit amounts.

Medium
3544

Subtree Inversion Sum

This problem involves calculating the maximum possible subtree inversion sum with dynamic programming and binary-tree tr…

Hard
3547

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.

Hard
3553

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…

Hard
3558

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…

Medium
3559

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.

Hard
3562

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…

Hard
3575

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…

Hard
3585

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…

Hard
3590

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-…

Hard
3593

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.

Medium
3607

Power Grid Maintenance

Determine which power stations remain connected after maintenance using array scanning and hash lookups to track compone…

Medium
3619

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.

Medium

Related Patterns

Depth-First Search LeetCode Problems: 252 Solutions