2023-03-13
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Constraints:
• The number of nodes in the tree is in the range
•
Follow up: Could you solve it both recursively and iteratively?
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
-100 <= Node.val <= 100Follow up: Could you solve it both recursively and iteratively?
2023-03-14
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Constraints:
• The number of nodes in the tree is in the range
•
• The depth of the tree will not exceed
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
root of a binary tree containing digits from 0 to 9 only.Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
1 -> 2 -> 3 represents the number 123.Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
0 <= Node.val <= 9• The depth of the tree will not exceed
10.2023-03-15
958. Check Completeness of a Binary Tree
Topic: Tree, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png
Constraints:
• The number of nodes in the tree is in the range
•
958. Check Completeness of a Binary Tree
Topic: Tree, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary tree, determine if it is a complete binary tree.In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between
1 and 2^h nodes inclusive at the last level h.Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
• The number of nodes in the tree is in the range
[1, 100].•
1 <= Node.val <= 10002023-03-16
106. Construct Binary Tree from Inorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/tree.jpg
Example 2:
Constraints:
•
•
•
•
• Each value of
•
•
106. Construct Binary Tree from Inorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays
inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/tree.jpg
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
•
1 <= inorder.length <= 3000•
postorder.length == inorder.length•
-3000 <= inorder[i], postorder[i] <= 3000•
inorder and postorder consist of unique values.• Each value of
postorder also appears in inorder.•
inorder is guaranteed to be the inorder traversal of the tree.•
postorder is guaranteed to be the postorder traversal of the tree.2023-03-17
208. Implement Trie (Prefix Tree)
Topic: Hash Table, String, Design, Trie
Difficulty: Medium
Problem:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
•
•
•
•
Example 1:
Constraints:
•
•
• At most
208. Implement Trie (Prefix Tree)
Topic: Hash Table, String, Design, Trie
Difficulty: Medium
Problem:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
•
Trie() Initializes the trie object.•
void insert(String word) Inserts the string word into the trie.•
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.•
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Constraints:
•
1 <= word.length, prefix.length <= 2000•
word and prefix consist only of lowercase English letters.• At most
3 * 10^4 calls in total will be made to insert, search, and startsWith.2023-03-18
1472. Design Browser History
Topic: Array, Linked List, Stack, Design, Doubly-Linked List, Data Stream
Difficulty: Medium
Problem:
You have a browser of one tab where you start on the
Implement the
•
•
•
•
Example:
Constraints:
•
•
•
•
• At most
1472. Design Browser History
Topic: Array, Linked List, Stack, Design, Doubly-Linked List, Data Stream
Difficulty: Medium
Problem:
You have a browser of one tab where you start on the
homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.Implement the
BrowserHistory class:•
BrowserHistory(string homepage) Initializes the object with the homepage of the browser.•
void visit(string url) Visits url from the current page. It clears up all the forward history.•
string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.•
string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.Example:
Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Explanation:
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
Constraints:
•
1 <= homepage.length <= 20•
1 <= url.length <= 20•
1 <= steps <= 100•
homepage and url consist of '.' or lower case English letters.• At most
5000 calls will be made to visit, back, and forward.2023-03-19
211. Design Add and Search Words Data Structure
Topic: String, Depth-First Search, Design, Trie
Difficulty: Medium
Problem:
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the
•
•
•
Example:
Constraints:
•
•
•
• There will be at most
• At most
211. Design Add and Search Words Data Structure
Topic: String, Depth-First Search, Design, Trie
Difficulty: Medium
Problem:
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the
WordDictionary class:•
WordDictionary() Initializes the object.•
void addWord(word) Adds word to the data structure, it can be matched later.•
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
Constraints:
•
1 <= word.length <= 25•
word in addWord consists of lowercase English letters.•
word in search consist of '.' or lowercase English letters.• There will be at most
3 dots in word for search queries.• At most
10^4 calls will be made to addWord and search.2023-03-20
605. Can Place Flowers
Topic: Array, Greedy
Difficulty: Easy
Problem:
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array
Example 1:
Example 2:
Constraints:
•
•
• There are no two adjacent flowers in
•
605. Can Place Flowers
Topic: Array, Greedy
Difficulty: Easy
Problem:
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array
flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Constraints:
•
1 <= flowerbed.length <= 2 * 10^4•
flowerbed[i] is 0 or 1.• There are no two adjacent flowers in
flowerbed.•
0 <= n <= flowerbed.length2023-03-21
2348. Number of Zero-Filled Subarrays
Topic: Array, Math
Difficulty: Medium
Problem:
Given an integer array
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
2348. Number of Zero-Filled Subarrays
Topic: Array, Math
Difficulty: Medium
Problem:
Given an integer array
nums, return the number of subarrays filled with 0.A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Example 3:
Input: nums = [2,10,2019]
Output: 0
Explanation: There is no subarray filled with 0. Therefore, we return 0.
Constraints:
•
1 <= nums.length <= 10^5•
-10^9 <= nums[i] <= 10^92023-03-22
2492. Minimum Score of a Path Between Two Cities
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given a positive integer
The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities
Note:
• A path is a sequence of roads between two cities.
• It is allowed for a path to contain the same road multiple times, and you can visit cities
• The test cases are generated such that there is at least one path between
Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph11.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph22.png
Constraints:
•
•
•
•
•
•
• There are no repeated edges.
• There is at least one path between
2492. Minimum Score of a Path Between Two Cities
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given a positive integer
n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [a_i, b_i, distance_i] indicates that there is a bidirectional road between cities a_i and b_i with a distance equal to distance_i. The cities graph is not necessarily connected.The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities
1 and n.Note:
• A path is a sequence of roads between two cities.
• It is allowed for a path to contain the same road multiple times, and you can visit cities
1 and n multiple times along the path.• The test cases are generated such that there is at least one path between
1 and n.Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph11.png
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
It can be shown that no other path has less score.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph22.png
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
•
2 <= n <= 10^5•
1 <= roads.length <= 10^5•
roads[i].length == 3•
1 <= a_i, b_i <= n•
a_i != b_i•
1 <= distance_i <= 10^4• There are no repeated edges.
• There is at least one path between
1 and n.2023-03-23
1319. Number of Operations to Make Network Connected
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There are
You are given an initial computer network
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return
Example 1:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png
Example 3:
Constraints:
•
•
•
•
•
• There are no repeated connections.
• No two computers are connected by more than one cable.
1319. Number of Operations to Make Network Connected
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There are
n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a_i, b_i] represents a connection between computers a_i and b_i. Any computer can reach any other computer directly or indirectly through the network.You are given an initial computer network
connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return
-1.Example 1:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Example 3:
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.
Constraints:
•
1 <= n <= 10^5•
1 <= connections.length <= min(n * (n - 1) / 2, 10^5)•
connections[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i• There are no repeated connections.
• No two computers are connected by more than one cable.
2023-03-24
1466. Reorder Routes to Make All Paths Lead to the City Zero
Topic: Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There are
Roads are represented by
This year, there will be a big event in the capital (city
Your task consists of reorienting some roads such that each city can visit the city
It's guaranteed that each city can reach city
Example 1:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png
Example 3:
Constraints:
•
•
•
•
•
1466. Reorder Routes to Make All Paths Lead to the City Zero
Topic: Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
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] = [a_i, b_i] represents a road from city a_i to city b_i.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:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
•
2 <= n <= 5 * 10^4•
connections.length == n - 1•
connections[i].length == 2•
0 <= a_i, b_i <= n - 1•
a_i != b_i2023-03-25
2316. Count Unreachable Pairs of Nodes in an Undirected Graph
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given an integer
Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-3.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-2.png
Constraints:
•
•
•
•
•
• There are no repeated edges.
2316. Count Unreachable Pairs of Nodes in an Undirected Graph
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given an integer
n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [a_i, b_i] denotes that there exists an undirected edge connecting nodes a_i and b_i.Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-3.png
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-2.png
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
Output: 14
Explanation: There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.
Constraints:
•
1 <= n <= 10^5•
0 <= edges.length <= 2 * 10^5•
edges[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i• There are no repeated edges.
2023-03-26
2360. Longest Cycle in a Graph
Topic: Depth-First Search, Graph, Topological Sort
Difficulty: Hard
Problem:
You are given a directed graph of
The graph is represented with a given 0-indexed array
Return the length of the longest cycle in the graph. If no cycle exists, return
A cycle is a path that starts and ends at the same node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png
Constraints:
•
•
•
•
2360. Longest Cycle in a Graph
Topic: Depth-First Search, Graph, Topological Sort
Difficulty: Hard
Problem:
You are given a directed graph of
n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.The graph is represented with a given 0-indexed array
edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.Return the length of the longest cycle in the graph. If no cycle exists, return
-1.A cycle is a path that starts and ends at the same node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png
Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png
Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
•
n == edges.length•
2 <= n <= 10^5•
-1 <= edges[i] < n•
edges[i] != i2023-03-27
64. Minimum Path Sum
Topic: Array, Dynamic Programming, Matrix
Difficulty: Medium
Problem:
Given a
Note: You can only move either down or right at any point in time.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg
Example 2:
Constraints:
•
•
•
•
64. Minimum Path Sum
Topic: Array, Dynamic Programming, Matrix
Difficulty: Medium
Problem:
Given a
m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.Note: You can only move either down or right at any point in time.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
•
m == grid.length•
n == grid[i].length•
1 <= m, n <= 200•
0 <= grid[i][j] <= 1002023-03-28
983. Minimum Cost For Tickets
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array
Train tickets are sold in three different ways:
• a 1-day pass is sold for
• a 7-day pass is sold for
• a 30-day pass is sold for
The passes allow that many days of consecutive travel.
• For example, if we get a 7-day pass on day
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Example 2:
Constraints:
•
•
•
•
•
983. Minimum Cost For Tickets
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array
days. Each day is an integer from 1 to 365.Train tickets are sold in three different ways:
• a 1-day pass is sold for
costs[0] dollars,• a 7-day pass is sold for
costs[1] dollars, and• a 30-day pass is sold for
costs[2] dollars.The passes allow that many days of consecutive travel.
• For example, if we get a 7-day pass on day
2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
Constraints:
•
1 <= days.length <= 365•
1 <= days[i] <= 365•
days is in strictly increasing order.•
costs.length == 3•
1 <= costs[i] <= 10002023-03-29
1402. Reducing Dishes
Topic: Array, Dynamic Programming, Greedy, Sorting
Difficulty: Hard
Problem:
A chef has collected data on the
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e.
Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1402. Reducing Dishes
Topic: Array, Dynamic Programming, Greedy, Sorting
Difficulty: Hard
Problem:
A chef has collected data on the
satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e.
time[i] * satisfaction[i].Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.
Constraints:
•
n == satisfaction.length•
1 <= n <= 500•
-1000 <= satisfaction[i] <= 10002023-03-30
87. Scramble String
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
• Split the string into two non-empty substrings at a random index, i.e., if the string is
• Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
• Apply step 1 recursively on each of the two substrings
Given two strings
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
87. Scramble String
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
• Split the string into two non-empty substrings at a random index, i.e., if the string is
s, divide it to x and y where s = x + y.• Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
s may become s = x + y or s = y + x.• Apply step 1 recursively on each of the two substrings
x and y.Given two strings
s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.Example 1:
Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: One possible scenario applied on s1 is:
"great" --> "gr/eat" // divide at random index.
"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat" which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
Example 2:
Input: s1 = "abcde", s2 = "caebd"
Output: false
Example 3:
Input: s1 = "a", s2 = "a"
Output: true
Constraints:
•
s1.length == s2.length•
1 <= s1.length <= 30•
s1 and s2 consist of lowercase English letters.2023-03-31
1444. Number of Ways of Cutting a Pizza
Topic: Array, Dynamic Programming, Memoization, Matrix
Difficulty: Hard
Problem:
Given a rectangular pizza represented as a
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/04/23/ways_to_cut_apple_1.png
Example 2:
Example 3:
Constraints:
•
•
•
•
•
1444. Number of Ways of Cutting a Pizza
Topic: Array, Dynamic Programming, Memoization, Matrix
Difficulty: Hard
Problem:
Given a rectangular pizza represented as a
rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/04/23/ways_to_cut_apple_1.png
Input: pizza = ["A..","AAA","..."], k = 3
Output: 3
Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
Example 2:
Input: pizza = ["A..","AA.","..."], k = 3
Output: 1
Example 3:
Input: pizza = ["A..","A..","..."], k = 1
Output: 1
Constraints:
•
1 <= rows, cols <= 50•
rows == pizza.length•
cols == pizza[i].length•
1 <= k <= 10•
pizza consists of characters 'A' and '.' only.2023-04-01
704. Binary Search
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array of integers
You must write an algorithm with
Example 1:
Example 2:
Constraints:
•
•
• All the integers in
•
704. Binary Search
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array of integers
nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.You must write an algorithm with
O(log n) runtime complexity.Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
•
1 <= nums.length <= 10^4•
-10^4 < nums[i], target < 10^4• All the integers in
nums are unique.•
nums is sorted in ascending order.2023-04-02
2300. Successful Pairs of Spells and Potions
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given two positive integer arrays
You are also given an integer
Return an integer array
Example 1:
Example 2:
Constraints:
•
•
•
•
•
2300. Successful Pairs of Spells and Potions
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given two positive integer arrays
spells and potions, of length n and m respectively, where spells[i] represents the strength of the i^th spell and potions[j] represents the strength of the j^th potion.You are also given an integer
success. A spell and potion pair is considered successful if the product of their strengths is at least success.Return an integer array
pairs of length n where pairs[i] is the number of potions that will form a successful pair with the i^th spell.Example 1:
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0^th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1^st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2^nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0^th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1^st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2^nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
•
n == spells.length•
m == potions.length•
1 <= n, m <= 10^5•
1 <= spells[i], potions[i] <= 10^5•
1 <= success <= 10^10