This note includes multiple leetcode algorithm problems with my solution
- 1. Swap Nodes in Pairs
- 2. Reverse Linked List II
- 3. Remove Nth Node From End of List
- 4. Valid Parentheses
- 5. Remove All Adjacent Duplicates In String
- 6. Backspace String Compare
- 7. Simplify Path
- 8. Make The String Great
- 9. Moving Average from Data Stream
- 10. Contiguous Array
- 11. Minimum Depth of Binary Tree
- 12. Maximum Depth of Binary Tree
- 13. Maximum Difference Between Node and Ancestor
- 14. Path Sum
- 15. Diameter of Binary Tree
- 16. Count Good Nodes in Binary Tree
- 17. Same Tree
- 18. Lowest Common Ancestor of a Binary Tree
- 19. Binary Tree Right Side View
- 20. Find Largest Value in Each Tree Row
- 21. Deepest Leaves Sum
- 22. Binary Tree Zigzag Level Order Traversal
- 23. Range Sum of BST
- 24. Minimum Absolute Difference in BST
- 25. Validate Binary Search Tree
- 26. Insert into a Binary Search Tree
- 27. Closest Binary Search Tree Value
- 28. Number of Provinces
- 29. Number of Islands
- 30. Reorder Routes to Make All Paths Lead to the City Zero
- 31. Keys and Rooms
- 32. Minimum Number of Vertices to Reach All Nodes
- 33. Find if Path Exists in Graph
- 34. Number of Connected Components in an Undirected Graph
- 35. Max Area of Island
- 36. Reachable Nodes With Restrictions
1. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
Constraints:
- The number of nodes in the list is in the range
[0, 100]
. 0 <= Node.val <= 100
My Solution
1 | /** |
Solution With More Clear Logic
1 | /** |
2. Reverse Linked List II
Given the head
of a singly linked list and two integers left
and right
where left <= right
, reverse the nodes of the list from position left
to position right
, and return the reversed list.
Example 1:
1 | Input: head = [1,2,3,4,5], left = 2, right = 4 |
Example 2:
1 | Input: head = [5], left = 1, right = 1 |
Constraints:
- The number of nodes in the list is
n
. 1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
My Solution
1 | /** |
3. Remove Nth Node From End of List
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
1 | Input: head = [1,2,3,4,5], n = 2 |
Example 2:
1 | Input: head = [1], n = 1 |
Example 3:
1 | Input: head = [1,2], n = 1 |
Constraints:
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
My Solution
1 | /** |
4. Valid Parentheses
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Example 4:
Input: s = “([])”
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
My Solution:
1 | /** |
Solution with more clear code with JavaScript Object
1 | var isValid = function(s) { |
5. Remove All Adjacent Duplicates In String
You are given a string s
consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
1 | Input: s = "abbaca" |
Example 2:
1 | Input: s = "azxxzy" |
Constraints:
1 <= s.length <= 105
s
consists of lowercase English letters.
My Solution
1 | /** |
6. Backspace String Compare
Given two strings s
and t
, return true
if they are equal when both are typed into empty text editors. '#'
means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
1 | Input: s = "ab#c", t = "ad#c" |
Example 2:
1 | Input: s = "ab##", t = "c#d#" |
Example 3:
1 | Input: s = "a#c", t = "b" |
Constraints:
1 <= s.length, t.length <= 200
s
andt
only contain lowercase letters and'#'
characters.
My Solution
1 | /** |
Better Space Complexity Solution with Two Pointer
1 | var backspaceCompare = function(s, t) { |
7. Simplify Path
You are given an absolute path for a Unix-style file system, which always begins with a slash '/'
. Your task is to transform this absolute path into its simplified canonical path.
The rules of a Unix-style file system are as follows:
- A single period
'.'
represents the current directory. - A double period
'..'
represents the previous/parent directory. - Multiple consecutive slashes such as
'//'
and'///'
are treated as a single slash'/'
. - Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example,
'...'
and'....'
are valid directory or file names.
The simplified canonical path should follow these rules:
- The path must start with a single slash
'/'
. - Directories within the path must be separated by exactly one slash
'/'
. - The path must not end with a slash
'/'
, unless it is the root directory. - The path must not have any single or double periods (
'.'
and'..'
) used to denote current or parent directories.
Return the simplified canonical path.
Example 1:
Input: path = “/home/“
Output: “/home”
Explanation:
The trailing slash should be removed.
Example 2:
Input: path = “/home//foo/“
Output: “/home/foo”
Explanation:
Multiple consecutive slashes are replaced by a single one.
Example 3:
Input: path = “/home/user/Documents/../Pictures”
Output: “/home/user/Pictures”
Explanation:
A double period ".."
refers to the directory up a level (the parent directory).
Example 4:
Input: path = “/../“
Output: “/“
Explanation:
Going one level up from the root directory is not possible.
Example 5:
Input: path = “/…/a/../b/c/../d/./“
Output: “/…/b/d”
Explanation:
"..."
is a valid name for a directory in this problem.
Constraints:
1 <= path.length <= 3000
path
consists of English letters, digits, period'.'
, slash'/'
or'_'
.path
is a valid absolute Unix path.
My Solution
1 | /** |
8. Make The String Great
Given a string s
of lower and upper case English letters.
A good string is a string which doesn’t have two adjacent characters s[i]
and s[i + 1]
where:
0 <= i <= s.length - 2
s[i]
is a lower-case letter ands[i + 1]
is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
1 | Input: s = "leEeetcode" |
Example 2:
1 | Input: s = "abBAcC" |
Example 3:
1 | Input: s = "s" |
Constraints:
1 <= s.length <= 100
s
contains only lower and upper case English letters.
My Solution
1 | /** |
9. Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage
class:
MovingAverage(int size)
Initializes the object with the size of the windowsize
.double next(int val)
Returns the moving average of the lastsize
values of the stream.
Example 1:
1 | Input |
Constraints:
1 <= size <= 1000
-105 <= val <= 105
- At most
104
calls will be made tonext
.
My Solution
1 | /** |
10. Contiguous Array
Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of 0
and 1
.
Example 1:
1 | Input: nums = [0,1] |
Example 2:
1 | Input: nums = [0,1,0] |
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
My Solution
1 | /** |
问题的核心
我们需要在一个二进制数组中,找到一个子数组,使得其中的 0
和 1
的数量相等。传统的暴力解法是通过双重循环检查每个子数组,并统计其中的 0
和 1
,这种做法的时间复杂度为 O(n²),在数组较大时会导致超时。
优化思路的核心:累加和法
- 将问题转化为累加和问题:
- 我们可以将
0
视为-1
,将1
仍然视为1
。这样,每当数组中某个子数组的累加和为0
时,就意味着这个子数组中0
和1
的数量是相等的。 - 比如数组
[0, 1]
可以转换为[-1, 1]
,其累加和为0
,所以0
和1
的数量相等。
- 我们可以将
- 使用哈希表来记录累加和的位置:
- 我们可以使用一个哈希表来存储每个累加和第一次出现的位置。如果某个累加和再次出现,则表示从上次该累加和出现的位置到当前索引的子数组和为
0
,即该子数组有相等数量的0
和1
。 - 例如:假设累加和在索引
i
处为5
,而在索引j
处再次为5
,那么从索引i+1
到j
的子数组的累加和为0
,即等数量的0
和1
。
- 我们可以使用一个哈希表来存储每个累加和第一次出现的位置。如果某个累加和再次出现,则表示从上次该累加和出现的位置到当前索引的子数组和为
- 初始化哈希表:
- 我们将累加和
0
初始化为-1
,这是为了处理从数组开头就满足条件的情况。例如,当整个数组从头开始就有相等数量的0
和1
时(即累加和为0
),此时子数组从索引0
开始。
- 我们将累加和
具体实现步骤
- 初始化变量:
- 使用
runningSum
记录当前的累加和。 - 使用
map
作为哈希表来存储每个累加和首次出现的索引。 - 初始化
maxLength
为 0,用来存储最大子数组的长度。
- 使用
- 遍历数组:
- 遍历数组中的每一个元素:
- 如果当前元素为
1
,将runningSum
加1
。 - 如果当前元素为
0
,将runningSum
减1
(因为我们将0
视为-1
)。
- 如果当前元素为
- 对每个元素,检查当前的
runningSum
是否已经在哈希表中存在:- 如果存在,说明从上次出现该累加和的位置到当前位置的子数组的累加和为
0
,即该子数组中的0
和1
数量相等。我们计算该子数组的长度,并更新maxLength
。 - 如果不存在,将当前
runningSum
及其对应的索引存入哈希表,表示这个累加和首次出现。
- 如果存在,说明从上次出现该累加和的位置到当前位置的子数组的累加和为
- 遍历数组中的每一个元素:
- 返回结果:
- 最后返回
maxLength
,即找到的最长子数组的长度。
- 最后返回
11. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
1 | Input: root = [3,9,20,null,null,15,7] |
Example 2:
1 | Input: root = [2,null,3,null,4,null,5,null,6] |
Constraints:
- The number of nodes in the tree is in the range
[0, 105]
. -1000 <= Node.val <= 1000
My Solution
1 | /** |
Better Logic Solution
1 | var minDepth = function(root) { |
12. Maximum Depth of Binary Tree
Given the root
of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
1 | Input: root = [3,9,20,null,null,15,7] |
Example 2:
1 | Input: root = [1,null,2] |
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -100 <= Node.val <= 100
My Solution
1 | /** |
13. Maximum Difference Between Node and Ancestor
Given the root
of a binary tree, find the maximum value v
for which there exist different nodes a
and b
where v = |a.val - b.val|
and a
is an ancestor of b
.
A node a
is an ancestor of b
if either: any child of a
is equal to b
or any child of a
is an ancestor of b
.
Example 1:
1 | Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] |
Example 2:
1 | Input: root = [1,null,2,null,0,3] |
Constraints:
The number of nodes in the tree is in the range
[2, 5000]
.0 <= Node.val <= 105
My Solution
1 | /** |
14. Path Sum
Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
Example 1:
1 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 |
Example 2:
1 | Input: root = [1,2,3], targetSum = 5 |
Example 3:
1 | Input: root = [], targetSum = 0 |
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]
. -1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
My Solution
1 | /** |
15. Diameter of Binary Tree
Given the root
of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
1 | Input: root = [1,2,3,4,5] |
Example 2:
1 | Input: root = [1,2] |
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. -100 <= Node.val <= 100
My Solution
1 | /** |
16. Count Good Nodes in Binary Tree
Given a binary tree root
, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
1 | Input: root = [3,1,4,3,null,1,5] |
Example 2:
1 | Input: root = [3,3,null,4,2] |
Example 3:
1 | Input: root = [1] |
Constraints:
- The number of nodes in the binary tree is in the range
[1, 10^5]
. - Each node’s value is between
[-10^4, 10^4]
.
My Solution
1 | /** |
17. Same Tree
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
1 | Input: p = [1,2,3], q = [1,2,3] |
Example 2:
1 | Input: p = [1,2], q = [1,null,2] |
Example 3:
1 | Input: p = [1,2,1], q = [1,1,2] |
Constraints:
- The number of nodes in both trees is in the range
[0, 100]
. -104 <= Node.val <= 104
My Solution
1 | /** |
Better Logic Solution
1 | var isSameTree = function(p, q) { |
18. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
Example 1:
1 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
Example 2:
1 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
Example 3:
1 | Input: root = [1,2], p = 1, q = 2 |
Constraints:
- The number of nodes in the tree is in the range
[2, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
will exist in the tree.
My Solution
1 | /** |
19. Binary Tree Right Side View
Given the root
of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
1 | Input: root = [1,2,3,null,5,null,4] |
Example 2:
1 | Input: root = [1,null,3] |
Example 3:
1 | Input: root = [] |
Constraints:
- The number of nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
My Solution
1 | /** |
20. Find Largest Value in Each Tree Row
Given the root
of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
1 | Input: root = [1,3,2,5,3,null,9] |
Example 2:
1 | Input: root = [1,2,3] |
Constraints:
- The number of nodes in the tree will be in the range
[0, 104]
. -231 <= Node.val <= 231 - 1
My Solution
1 | /** |
21. Deepest Leaves Sum
Given the root
of a binary tree, return the sum of values of its deepest leaves.
Example 1:
1 | Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] |
Example 2:
1 | Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] |
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. 1 <= Node.val <= 100
My Solution
1 | /** |
Better Solution
1 | var deepestLeavesSum = function(root) { |
22. Binary Tree Zigzag Level Order Traversal
Given the root
of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
1 | Input: root = [3,9,20,null,null,15,7] |
Example 2:
1 | Input: root = [1] |
Example 3:
1 | Input: root = [] |
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -100 <= Node.val <= 100
My Solution
1 | /** |
23. Range Sum of BST
Given the root
node of a binary search tree and two integers low
and high
, return the sum of values of all nodes with a value in the inclusive range [low, high]
.
Example 1:
1 | Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 |
Example 2:
1 | Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 |
Constraints:
- The number of nodes in the tree is in the range
[1, 2 * 104]
. 1 <= Node.val <= 105
1 <= low <= high <= 105
- All
Node.val
are unique.
My Solution
1 | /** |
24. Minimum Absolute Difference in BST
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
1 | Input: root = [4,2,6,1,3] |
Example 2:
1 | Input: root = [1,0,48,null,null,12,49] |
Constraints:
- The number of nodes in the tree is in the range
[2, 104]
. 0 <= Node.val <= 105
My Solution
1 | /** |
25. Validate Binary Search Tree
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
Example 1:
1 | Input: root = [2,1,3] |
Example 2:
1 | Input: root = [5,1,4,null,null,3,6] |
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. -231 <= Node.val <= 231 - 1
My Solution
1 | /** |
26. Insert into a Binary Search Tree
You are given the root
node of a binary search tree (BST) and a value
to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Example 1:
1 | Input: root = [4,2,7,1,3], val = 5 |
Example 2:
1 | Input: root = [40,20,60,10,30,50,70], val = 25 |
Example 3:
1 | Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 |
Constraints:
- The number of nodes in the tree will be in the range
[0, 104]
. -108 <= Node.val <= 108
- All the values
Node.val
are unique. -108 <= val <= 108
- It’s guaranteed that
val
does not exist in the original BST.
My Solution
1 | /** |
Better Solution
1 | /** |
27. Closest Binary Search Tree Value
Given the root
of a binary search tree and a target
value, return the value in the BST that is closest to the target
. If there are multiple answers, print the smallest.
Example 1:
1 | Input: root = [4,2,5,1,3], target = 3.714286 |
Example 2:
1 | Input: root = [1], target = 4.428571 |
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. 0 <= Node.val <= 109
-109 <= target <= 109
My Solution
1 | /** |
28. Number of Provinces
There are n
cities. Some of them are connected, while some are not. If city a
is connected directly with city b
, and city b
is connected directly with city c
, then city a
is connected indirectly with city c
.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n
matrix isConnected
where isConnected[i][j] = 1
if the ith
city and the jth
city are directly connected, and isConnected[i][j] = 0
otherwise.
Return the total number of *provinces***.
Example 1:
1 | Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] |
Example 2:
1 | Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] |
Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
is1
or0
.isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
My Solution
1 | /** |
29. Number of Islands
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
1 | Input: grid = [ |
Example 2:
1 | Input: grid = [ |
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
is'0'
or'1'
.
My Solution
1 | /** |
30. Reorder Routes to Make All Paths Lead to the City Zero
There are n
cities numbered from 0
to n - 1
and n - 1
roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections
where connections[i] = [ai, bi]
represents a road from city ai
to city bi
.
This year, there will be a big event in the capital (city 0
), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0
. Return the minimum number of edges changed.
It’s guaranteed that each city can reach city 0
after reorder.
Example 1:
1 | Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] |
Example 2:
1 | Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] |
Example 3:
1 | Input: n = 3, connections = [[1,0],[2,0]] |
Constraints:
2 <= n <= 5 * 104
connections.length == n - 1
connections[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
My Solution
1 | /** |
31. Keys and Rooms
There are n
rooms labeled from 0
to n - 1
and all the rooms are locked except for room 0
. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms
where rooms[i]
is the set of keys that you can obtain if you visited room i
, return true
if you can visit all the rooms, or false
otherwise.
Example 1:
1 | Input: rooms = [[1],[2],[3],[]] |
Example 2:
1 | Input: rooms = [[1,3],[3,0,1],[2],[0]] |
Constraints:
n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
- All the values of
rooms[i]
are unique.
My Solution
1 | /** |
32. Minimum Number of Vertices to Reach All Nodes
Given a directed acyclic graph, with n
vertices numbered from 0
to n-1
, and an array edges
where edges[i] = [fromi, toi]
represents a directed edge from node fromi
to node toi
.
Find the smallest set of vertices from which all nodes in the graph are reachable. It’s guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
1 | Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]] |
Example 2:
1 | Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]] |
Constraints:
2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi < n
- All pairs
(fromi, toi)
are distinct.
My Solution
The answer is the number of nodes with 0 indegree.
1 | /** |
33. Find if Path Exists in Graph
There is a bi-directional graph with n
vertices, where each vertex is labeled from 0
to n - 1
(inclusive). The edges in the graph are represented as a 2D integer array edges
, where each edges[i] = [ui, vi]
denotes a bi-directional edge between vertex ui
and vertex vi
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source
to vertex destination
.
Given edges
and the integers n
, source
, and destination
, return true
if there is a valid path from source
to destination
, or false
otherwise**.
Example 1:
1 | Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 |
Example 2:
1 | Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5 |
Constraints:
1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
- There are no duplicate edges.
- There are no self edges.
My Solution
1 | /** |
34. Number of Connected Components in an Undirected Graph
You have a graph of n
nodes. You are given an integer n
and an array edges
where edges[i] = [ai, bi]
indicates that there is an edge between ai
and bi
in the graph.
Return the number of connected components in the graph.
Example 1:
1 | Input: n = 5, edges = [[0,1],[1,2],[3,4]] |
Example 2:
1 | Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] |
Constraints:
1 <= n <= 2000
1 <= edges.length <= 5000
edges[i].length == 2
0 <= ai <= bi < n
ai != bi
- There are no repeated edges.
My Solution
1 | /** |
35. Max Area of Island
You are given an m x n
binary matrix grid
. An island is a group of 1
‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
Example 1:
1 | Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] |
Example 2:
1 | Input: grid = [[0,0,0,0,0,0,0,0]] |
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
or1
.
My Solution
1 | /** |
36. Reachable Nodes With Restrictions
There is an undirected tree with n
nodes labeled from 0
to n - 1
and n - 1
edges.
You are given a 2D integer array edges
of length n - 1
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree. You are also given an integer array restricted
which represents restricted nodes.
Return the maximum number of nodes you can reach from node 0
without visiting a restricted node.
Note that node 0
will not be a restricted node.
Example 1:
1 | Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] |
Example 2:
1 | Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] |
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.1 <= restricted.length < n
1 <= restricted[i] < n
- All the values of
restricted
are unique.
My Solution
1 | /** |
- 本文作者: Depasinre
- 本文链接: https:/Depasinre.github.io/2024/10/03/LeetCode-学习-2/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!