2025-02-14
1352. Product of the Last K Numbers
Topic: Array, Math, Design, Data Stream, Prefix Sum
Difficulty: Medium
Problem:
Design an algorithm that accepts a stream of integers and retrieves the product of the last
Implement the
•
•
•
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
Example:
Constraints:
•
•
• At most
• The product of the stream at any point in time will fit in a 32-bit integer.
Follow-up: Can you implement both
1352. Product of the Last K Numbers
Topic: Array, Math, Design, Data Stream, Prefix Sum
Difficulty: Medium
Problem:
Design an algorithm that accepts a stream of integers and retrieves the product of the last
k integers of the stream.Implement the
ProductOfNumbers class:•
ProductOfNumbers() Initializes the object with an empty stream.•
void add(int num) Appends the integer num to the stream.•
int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
Example:
Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
Output
[null,null,null,null,null,null,20,40,0,null,32]
Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // [3]
productOfNumbers.add(0); // [3,0]
productOfNumbers.add(2); // [3,0,2]
productOfNumbers.add(5); // [3,0,2,5]
productOfNumbers.add(4); // [3,0,2,5,4]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8); // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32
Constraints:
•
0 <= num <= 100•
1 <= k <= 4 * 10^4• At most
4 * 10^4 calls will be made to add and getProduct.• The product of the stream at any point in time will fit in a 32-bit integer.
Follow-up: Can you implement both
GetProduct and Add to work in O(1) time complexity instead of O(k) time complexity?2025-02-15
2698. Find the Punishment Number of an Integer
Topic: Math, Backtracking
Difficulty: Medium
Problem:
Given a positive integer
The punishment number of
•
• The decimal representation of
Example 1:
Example 2:
Constraints:
•
2698. Find the Punishment Number of an Integer
Topic: Math, Backtracking
Difficulty: Medium
Problem:
Given a positive integer
n, return the punishment number of n.The punishment number of
n is defined as the sum of the squares of all integers i such that:•
1 <= i <= n• The decimal representation of
i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.Example 1:
Input: n = 10
Output: 182
Explanation: There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement:
- 1 since 1 * 1 = 1
- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9.
- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10.
Hence, the punishment number of 10 is 1 + 81 + 100 = 182
Example 2:
Input: n = 37
Output: 1478
Explanation: There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement:
- 1 since 1 * 1 = 1.
- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1.
- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0.
- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.
Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
Constraints:
•
1 <= n <= 10002025-02-16
1718. Construct the Lexicographically Largest Valid Sequence
Topic: Array, Backtracking
Difficulty: Medium
Problem:
Given an integer
• The integer
• Each integer between
• For every integer
The distance between two numbers on the sequence,
Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
A sequence
Example 1:
Example 2:
Constraints:
•
1718. Construct the Lexicographically Largest Valid Sequence
Topic: Array, Backtracking
Difficulty: Medium
Problem:
Given an integer
n, find a sequence that satisfies all of the following:• The integer
1 occurs once in the sequence.• Each integer between
2 and n occurs twice in the sequence.• For every integer
i between 2 and n, the distance between the two occurrences of i is exactly i.The distance between two numbers on the sequence,
a[i] and a[j], is the absolute difference of their indices, |j - i|.Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
A sequence
a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.Example 1:
Input: n = 3
Output: [3,1,2,3,2]
Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.
Example 2:
Input: n = 5
Output: [5,3,1,4,3,5,2,4,2]
Constraints:
•
1 <= n <= 202025-02-17
1079. Letter Tile Possibilities
Topic: Hash Table, String, Backtracking, Counting
Difficulty: Medium
Problem:
You have
Return the number of possible non-empty sequences of letters you can make using the letters printed on those
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1079. Letter Tile Possibilities
Topic: Hash Table, String, Backtracking, Counting
Difficulty: Medium
Problem:
You have
n tiles, where each tile has one letter tiles[i] printed on it.Return the number of possible non-empty sequences of letters you can make using the letters printed on those
tiles.Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
•
1 <= tiles.length <= 7•
tiles consists of uppercase English letters.2025-02-18
2375. Construct Smallest Number From DI String
Topic: String, Backtracking, Stack, Greedy
Difficulty: Medium
Problem:
You are given a 0-indexed string
A 0-indexed string
•
• If
• If
Return the lexicographically smallest possible string
Example 1:
Example 2:
Constraints:
•
•
2375. Construct Smallest Number From DI String
Topic: String, Backtracking, Stack, Greedy
Difficulty: Medium
Problem:
You are given a 0-indexed string
pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.A 0-indexed string
num of length n + 1 is created using the following conditions:•
num consists of the digits '1' to '9', where each digit is used at most once.• If
pattern[i] == 'I', then num[i] < num[i + 1].• If
pattern[i] == 'D', then num[i] > num[i + 1].Return the lexicographically smallest possible string
num that meets the conditions.Example 1:
Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.
Example 2:
Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.
Constraints:
•
1 <= pattern.length <= 8•
pattern consists of only the letters 'I' and 'D'.2025-02-19
1415. The k-th Lexicographical String of All Happy Strings of Length n
Topic: String, Backtracking
Difficulty: Medium
Problem:
A happy string is a string that:
• consists only of letters of the set
•
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers
Return the kth string of this list or return an empty string if there are less than
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1415. The k-th Lexicographical String of All Happy Strings of Length n
Topic: String, Backtracking
Difficulty: Medium
Problem:
A happy string is a string that:
• consists only of letters of the set
['a', 'b', 'c'].•
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers
n and k, consider a list of all happy strings of length n sorted in lexicographical order.Return the kth string of this list or return an empty string if there are less than
k happy strings of length n.Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9^th string = "cab"
Constraints:
•
1 <= n <= 10•
1 <= k <= 1002025-02-20
1980. Find Unique Binary String
Topic: Array, Hash Table, String, Backtracking
Difficulty: Medium
Problem:
Given an array of strings
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
• All the strings of
1980. Find Unique Binary String
Topic: Array, Hash Table, String, Backtracking
Difficulty: Medium
Problem:
Given an array of strings
nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.Example 1:
Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would also be correct.
Example 2:
Input: nums = ["00","01"]
Output: "11"
Explanation: "11" does not appear in nums. "10" would also be correct.
Example 3:
Input: nums = ["111","011","001"]
Output: "101"
Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.
Constraints:
•
n == nums.length•
1 <= n <= 16•
nums[i].length == n•
nums[i] is either '0' or '1'.• All the strings of
nums are unique.2025-02-21
1261. Find Elements in a Contaminated Binary Tree
Topic: Hash Table, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree
Difficulty: Medium
Problem:
Given a binary tree with the following rules:
1.
2. For any
1. If
2. If
Now the binary tree is contaminated, which means all
Implement the
•
•
Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg
Example 3:
Image: https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg
Constraints:
•
• The height of the binary tree is less than or equal to
• The total number of nodes is between
• Total calls of
•
1261. Find Elements in a Contaminated Binary Tree
Topic: Hash Table, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree
Difficulty: Medium
Problem:
Given a binary tree with the following rules:
1.
root.val == 02. For any
treeNode:1. If
treeNode.val has a value x and treeNode.left != null, then treeNode.left.val == 2 * x + 12. If
treeNode.val has a value x and treeNode.right != null, then treeNode.right.val == 2 * x + 2Now the binary tree is contaminated, which means all
treeNode.val have been changed to -1.Implement the
FindElements class:•
FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.•
bool find(int target) Returns true if the target value exists in the recovered binary tree.Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg
Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]);
findElements.find(1); // return False
findElements.find(2); // return True
Example 2:
Image: https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg
Input
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
Output
[null,true,true,false]
Explanation
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False
Example 3:
Image: https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg
Input
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Output
[null,true,false,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True
Constraints:
•
TreeNode.val == -1• The height of the binary tree is less than or equal to
20• The total number of nodes is between
[1, 10^4]• Total calls of
find() is between [1, 10^4]•
0 <= target <= 10^62025-02-22
1028. Recover a Tree From Preorder Traversal
Topic: String, Tree, Depth-First Search, Binary Tree
Difficulty: Hard
Problem:
We run a preorder depth-first search (DFS) on the
At each node in this traversal, we output
If a node has only one child, that child is guaranteed to be the left child.
Given the output
Example 1:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex3.png
Constraints:
• The number of nodes in the original tree is in the range
•
1028. Recover a Tree From Preorder Traversal
Topic: String, Tree, Depth-First Search, Binary Tree
Difficulty: Hard
Problem:
We run a preorder depth-first search (DFS) on the
root of a binary tree.At each node in this traversal, we output
D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0.If a node has only one child, that child is guaranteed to be the left child.
Given the output
traversal of this traversal, recover the tree and return its root.Example 1:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex1.png
Input: traversal = "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]
Example 2:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex2.png
Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]
Example 3:
Image: https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex3.png
Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]
Constraints:
• The number of nodes in the original tree is in the range
[1, 1000].•
1 <= Node.val <= 10^92025-02-23
889. Construct Binary Tree from Preorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays,
If there exist multiple answers, you can return any of them.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg
Example 2:
Constraints:
•
•
• All the values of
•
•
• All the values of
• It is guaranteed that
889. Construct Binary Tree from Preorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays,
preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.If there exist multiple answers, you can return any of them.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg
Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Example 2:
Input: preorder = [1], postorder = [1]
Output: [1]
Constraints:
•
1 <= preorder.length <= 30•
1 <= preorder[i] <= preorder.length• All the values of
preorder are unique.•
postorder.length == preorder.length•
1 <= postorder[i] <= postorder.length• All the values of
postorder are unique.• It is guaranteed that
preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.2025-02-24
2467. Most Profitable Path in a Tree
Topic: Array, Tree, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There is an undirected tree with
At every node
• the price needed to open the gate at node
• the cash reward obtained on opening the gate at node
The game goes on as follows:
• Initially, Alice is at node
• At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node
• For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
• If the gate is already open, no price will be required, nor will there be any cash reward.
• If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is
• If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node
Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/29/eg1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/29/eg2.png
Constraints:
•
•
•
•
•
•
•
•
•
2467. Most Profitable Path in a Tree
Topic: Array, Tree, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There is an undirected tree with
n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i in the tree.At every node
i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:• the price needed to open the gate at node
i, if amount[i] is negative, or,• the cash reward obtained on opening the gate at node
i, otherwise.The game goes on as follows:
• Initially, Alice is at node
0 and Bob is at node bob.• At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node
0.• For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
• If the gate is already open, no price will be required, nor will there be any cash reward.
• If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is
c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.• If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node
0, he stops moving. Note that these events are independent of each other.Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/29/eg1.png
Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output: 6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/29/eg2.png
Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output: -7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
•
2 <= n <= 10^5•
edges.length == n - 1•
edges[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i•
edges represents a valid tree.•
1 <= bob < n•
amount.length == n•
amount[i] is an even integer in the range [-10^4, 10^4].2025-02-25
1524. Number of Sub-arrays With Odd Sum
Topic: Array, Math, Dynamic Programming, Prefix Sum
Difficulty: Medium
Problem:
Given an array of integers
Since the answer can be very large, return it modulo
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1524. Number of Sub-arrays With Odd Sum
Topic: Array, Math, Dynamic Programming, Prefix Sum
Difficulty: Medium
Problem:
Given an array of integers
arr, return the number of subarrays with an odd sum.Since the answer can be very large, return it modulo
10^9 + 7.Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Constraints:
•
1 <= arr.length <= 10^5•
1 <= arr[i] <= 1002025-02-26
1749. Maximum Absolute Sum of Any Subarray
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given an integer array
Return the maximum absolute sum of any (possibly empty) subarray of
Note that
• If
• If
Example 1:
Example 2:
Constraints:
•
•
1749. Maximum Absolute Sum of Any Subarray
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given an integer array
nums. The absolute sum of a subarray [nums_l, nums_l+1, ..., nums_r-1, nums_r] is abs(nums_l + nums_l+1 + ... + nums_r-1 + nums_r).Return the maximum absolute sum of any (possibly empty) subarray of
nums.Note that
abs(x) is defined as follows:• If
x is a negative integer, then abs(x) = -x.• If
x is a non-negative integer, then abs(x) = x.Example 1:
Input: nums = [1,-3,2,3,-4]
Output: 5
Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.
Example 2:
Input: nums = [2,-5,1,-4,3,-2]
Output: 8
Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
Constraints:
•
1 <= nums.length <= 10^5•
-10^4 <= nums[i] <= 10^42025-02-27
873. Length of Longest Fibonacci Subsequence
Topic: Array, Hash Table, Dynamic Programming
Difficulty: Medium
Problem:
A sequence
•
•
Given a strictly increasing array
A subsequence is derived from another sequence
Example 1:
Example 2:
Constraints:
•
•
873. Length of Longest Fibonacci Subsequence
Topic: Array, Hash Table, Dynamic Programming
Difficulty: Medium
Problem:
A sequence
x_1, x_2, ..., x_n is Fibonacci-like if:•
n >= 3•
x_i + x_i+1 == x_i+2 for all i + 2 <= nGiven a strictly increasing array
arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.A subsequence is derived from another sequence
arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].Example 1:
Input: arr = [1,2,3,4,5,6,7,8]
Output: 5
Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: arr = [1,3,7,11,12,14,18]
Output: 3
Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
Constraints:
•
3 <= arr.length <= 1000•
1 <= arr[i] < arr[i + 1] <= 10^92025-02-28
1092. Shortest Common Supersequence
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
Given two strings
A string
Example 1:
Example 2:
Constraints:
•
•
1092. Shortest Common Supersequence
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
Given two strings
str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.A string
s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.Example 1:
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
Example 2:
Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
Output: "aaaaaaaa"
Constraints:
•
1 <= str1.length, str2.length <= 1000•
str1 and str2 consist of lowercase English letters.2025-03-01
2460. Apply Operations to an Array
Topic: Array, Two Pointers, Simulation
Difficulty: Easy
Problem:
You are given a 0-indexed array
You need to apply
• If
After performing all the operations, shift all the
• For example, the array
Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Example 1:
Example 2:
Constraints:
•
•
2460. Apply Operations to an Array
Topic: Array, Two Pointers, Simulation
Difficulty: Easy
Problem:
You are given a 0-indexed array
nums of size n consisting of non-negative integers.You need to apply
n - 1 operations to this array where, in the i^th operation (0-indexed), you will apply the following on the i^th element of nums:• If
nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.After performing all the operations, shift all the
0's to the end of the array.• For example, the array
[1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Example 1:
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.
Constraints:
•
2 <= nums.length <= 2000•
0 <= nums[i] <= 10002025-03-02
2570. Merge Two 2D Arrays by Summing Values
Topic: Array, Hash Table, Two Pointers
Difficulty: Easy
Problem:
You are given two 2D integer arrays
•
•
Each array contains unique ids and is sorted in ascending order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
• Only ids that appear in at least one of the two arrays should be included in the resulting array.
• Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be
Return the resulting array. The returned array must be sorted in ascending order by id.
Example 1:
Example 2:
Constraints:
•
•
•
• Both arrays contain unique ids.
• Both arrays are in strictly ascending order by id.
2570. Merge Two 2D Arrays by Summing Values
Topic: Array, Hash Table, Two Pointers
Difficulty: Easy
Problem:
You are given two 2D integer arrays
nums1 and nums2.•
nums1[i] = [id_i, val_i] indicate that the number with the id id_i has a value equal to val_i.•
nums2[i] = [id_i, val_i] indicate that the number with the id id_i has a value equal to val_i.Each array contains unique ids and is sorted in ascending order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
• Only ids that appear in at least one of the two arrays should be included in the resulting array.
• Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be
0.Return the resulting array. The returned array must be sorted in ascending order by id.
Example 1:
Input: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
Output: [[1,6],[2,3],[3,2],[4,6]]
Explanation: The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
Example 2:
Input: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]
Output: [[1,3],[2,4],[3,6],[4,3],[5,5]]
Explanation: There are no common ids, so we just include each id with its value in the resulting list.
Constraints:
•
1 <= nums1.length, nums2.length <= 200•
nums1[i].length == nums2[j].length == 2•
1 <= id_i, val_i <= 1000• Both arrays contain unique ids.
• Both arrays are in strictly ascending order by id.
2025-03-03
2161. Partition Array According to Given Pivot
Topic: Array, Two Pointers, Simulation
Difficulty: Medium
Problem:
You are given a 0-indexed integer array
• Every element less than
• Every element equal to
• The relative order of the elements less than
• More formally, consider every
Return
Example 1:
Example 2:
Constraints:
•
•
•
2161. Partition Array According to Given Pivot
Topic: Array, Two Pointers, Simulation
Difficulty: Medium
Problem:
You are given a 0-indexed integer array
nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:• Every element less than
pivot appears before every element greater than pivot.• Every element equal to
pivot appears in between the elements less than and greater than pivot.• The relative order of the elements less than
pivot and the elements greater than pivot is maintained.• More formally, consider every
p_i, p_j where p_i is the new position of the i^th element and p_j is the new position of the j^th element. If i < j and both elements are smaller (or larger) than pivot, then p_i < p_j.Return
nums after the rearrangement.Example 1:
Input: nums = [9,12,5,10,14,3,10], pivot = 10
Output: [9,5,3,10,10,12,14]
Explanation:
The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.
The elements 12 and 14 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.
Example 2:
Input: nums = [-3,4,3,2], pivot = 2
Output: [-3,2,4,3]
Explanation:
The element -3 is less than the pivot so it is on the left side of the array.
The elements 4 and 3 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.
Constraints:
•
1 <= nums.length <= 10^5•
-10^6 <= nums[i] <= 10^6•
pivot equals to an element of nums.2025-03-04
1780. Check if Number is a Sum of Powers of Three
Topic: Math
Difficulty: Medium
Problem:
Given an integer
An integer
Example 1:
Example 2:
Example 3:
Constraints:
•
1780. Check if Number is a Sum of Powers of Three
Topic: Math
Difficulty: Medium
Problem:
Given an integer
n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.An integer
y is a power of three if there exists an integer x such that y == 3^x.Example 1:
Input: n = 12
Output: true
Explanation: 12 = 3^1 + 3^2
Example 2:
Input: n = 91
Output: true
Explanation: 91 = 3^0 + 3^2 + 3^4
Example 3:
Input: n = 21
Output: false
Constraints:
•
1 <= n <= 10^72025-03-05
2579. Count Total Number of Colored Cells
Topic: Math
Difficulty: Medium
Problem:
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer
• At the first minute, color any arbitrary unit cell blue.
• Every minute thereafter, color blue every uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Image: https://assets.leetcode.com/uploads/2023/01/10/example-copy-2.png
Return the number of colored cells at the end of
Example 1:
Example 2:
Constraints:
•
2579. Count Total Number of Colored Cells
Topic: Math
Difficulty: Medium
Problem:
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer
n, indicating that you must do the following routine for n minutes:• At the first minute, color any arbitrary unit cell blue.
• Every minute thereafter, color blue every uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Image: https://assets.leetcode.com/uploads/2023/01/10/example-copy-2.png
Return the number of colored cells at the end of
n minutes.Example 1:
Input: n = 1
Output: 1
Explanation: After 1 minute, there is only 1 blue cell, so we return 1.
Example 2:
Input: n = 2
Output: 5
Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
Constraints:
•
1 <= n <= 10^5