diff --git a/01-matrix/README.md b/01-matrix/README.md new file mode 100644 index 0000000..ec1fbc2 --- /dev/null +++ b/01-matrix/README.md @@ -0,0 +1,29 @@ +
Given an m x n
binary matrix mat
, return the distance of the nearest 0
for each cell.
The distance between two adjacent cells is 1
.
+
Example 1:
+Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] ++ +
Example 2:
+Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] ++ +
+
Constraints:
+ +m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j]
is either 0
or 1
.0
in mat
.Given an N bit binary number, find the 1's complement of the number. The ones' complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa).
+
Example 1:
+ +Input: +N = 3 +S = 101 +Output: +010 +Explanation: +We get the output by converting 1's in S +to 0 and 0s to 1 ++ +
Example 2:
+ +Input:
+N = 2
+S = 10
+Output:
+01
+Explanation:
+We get the output by converting 1's in S
+to 0 and 0s to 1
+
+
+
+Your Task:
+You don't need to read input or print anything. Your task is to complete the function onesComplement() which takes the binary string S, its size N as input parameters and returns 1's complement of S of size N.
+
Expected Time Complexity: O(N)
+Expected Space Complexity: O(N)
+
Constraints:
+1<=N<=100
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
+ +You can return the answer in any order.
+ ++
Example 1:
+ +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. ++ +
Example 2:
+ +Input: nums = [3,2,4], target = 6 +Output: [1,2] ++ +
Example 3:
+ +Input: nums = [3,3], target = 6 +Output: [0,1] ++ +
+
Constraints:
+ +2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
+Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?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:
+Input: p = [1,2,3], q = [1,2,3] +Output: true ++ +
Example 2:
+Input: p = [1,2], q = [1,null,2] +Output: false ++ +
Example 3:
+Input: p = [1,2,1], q = [1,1,2] +Output: false ++ +
+
Constraints:
+ +[0, 100]
.-104 <= Node.val <= 104
The complement of an integer is the integer you get when you flip all the 0
's to 1
's and all the 1
's to 0
's in its binary representation.
5
is "101"
in binary and its complement is "010"
which is the integer 2
.Given an integer n
, return its complement.
+
Example 1:
+ +Input: n = 5 +Output: 2 +Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. ++ +
Example 2:
+ +Input: n = 7 +Output: 0 +Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. ++ +
Example 3:
+ +Input: n = 10 +Output: 5 +Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. ++ +
+
Constraints:
+ +0 <= n < 109
+
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
+You are given a list of songs where the ith
song has a duration of time[i]
seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60
. Formally, we want the number of indices i
, j
such that i < j
with (time[i] + time[j]) % 60 == 0
.
+
Example 1:
+ +Input: time = [30,20,150,100,40] +Output: 3 +Explanation: Three pairs have a total duration divisible by 60: +(time[0] = 30, time[2] = 150): total duration 180 +(time[1] = 20, time[3] = 100): total duration 120 +(time[1] = 20, time[4] = 40): total duration 60 ++ +
Example 2:
+ +Input: time = [60,60,60] +Output: 3 +Explanation: All three pairs have a total duration of 120, which is divisible by 60. ++ +
+
Constraints:
+ +1 <= time.length <= 6 * 104
1 <= time[i] <= 500
A conveyor belt has packages that must be shipped from one port to another within days
days.
The ith
package on the conveyor belt has a weight of weights[i]
. Each day, we load the ship with packages on the conveyor belt (in the order given by weights
). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days
days.
+
Example 1:
+ +Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 +Output: 15 +Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: +1st day: 1, 2, 3, 4, 5 +2nd day: 6, 7 +3rd day: 8 +4th day: 9 +5th day: 10 + +Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. ++ +
Example 2:
+ +Input: weights = [3,2,2,4,1,4], days = 3 +Output: 6 +Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: +1st day: 3, 2 +2nd day: 2, 4 +3rd day: 1, 4 ++ +
Example 3:
+ +Input: weights = [1,2,3,1,1], days = 4 +Output: 3 +Explanation: +1st day: 1 +2nd day: 2 +3rd day: 3 +4th day: 1, 1 ++ +
+
Constraints:
+ +1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
Given the root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
+
Example 1:
+Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] ++ +
Example 2:
+ +Input: root = [1] +Output: [[1]] ++ +
Example 3:
+ +Input: root = [] +Output: [] ++ +
+
Constraints:
+ +[0, 2000]
.-1000 <= Node.val <= 1000
You are given the root
of a binary tree where each node has a value 0
or 1
. Each root-to-leaf path represents a binary number starting with the most significant bit.
0 -> 1 -> 1 -> 0 -> 1
, then this could represent 01101
in binary, which is 13
.For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.
+ +The test cases are generated so that the answer fits in a 32-bits integer.
+ ++
Example 1:
+Input: root = [1,0,1,0,1,0,1] +Output: 22 +Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 ++ +
Example 2:
+ +Input: root = [0] +Output: 0 ++ +
+
Constraints:
+ +[1, 1000]
.Node.val
is 0
or 1
.A company is planning to interview 2n
people. Given the array costs
where costs[i] = [aCosti, bCosti]
, the cost of flying the ith
person to city a
is aCosti
, and the cost of flying the ith
person to city b
is bCosti
.
Return the minimum cost to fly every person to a city such that exactly n
people arrive in each city.
+
Example 1:
+ +Input: costs = [[10,20],[30,200],[400,50],[30,20]] +Output: 110 +Explanation: +The first person goes to city A for a cost of 10. +The second person goes to city A for a cost of 30. +The third person goes to city B for a cost of 50. +The fourth person goes to city B for a cost of 20. + +The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. ++ +
Example 2:
+ +Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] +Output: 1859 ++ +
Example 3:
+ +Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]] +Output: 3086 ++ +
+
Constraints:
+ +2 * n == costs.length
2 <= costs.length <= 100
costs.length
is even.1 <= aCosti, bCosti <= 1000
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:
+Input: root = [3,9,20,null,null,15,7] +Output: [[3],[20,9],[15,7]] ++ +
Example 2:
+ +Input: root = [1] +Output: [[1]] ++ +
Example 3:
+ +Input: root = [] +Output: [] ++ +
+
Constraints:
+ +[0, 2000]
.-100 <= Node.val <= 100
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:
+Input: root = [3,9,20,null,null,15,7] +Output: 3 ++ +
Example 2:
+ +Input: root = [1,null,2] +Output: 2 ++ +
+
Constraints:
+ +[0, 104]
.-100 <= Node.val <= 100
On an infinite plane, a robot initially stands at (0, 0)
and faces north. The robot can receive one of three instructions:
"G"
: go straight 1 unit;"L"
: turn 90 degrees to the left;"R"
: turn 90 degrees to the right.The robot performs the instructions
given in order, and repeats them forever.
Return true
if and only if there exists a circle in the plane such that the robot never leaves the circle.
+
Example 1:
+ +Input: instructions = "GGLLGG" +Output: true +Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). +When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.+ +
Example 2:
+ +Input: instructions = "GG" +Output: false +Explanation: The robot moves north indefinitely.+ +
Example 3:
+ +Input: instructions = "GL" +Output: true +Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...+ +
+
Constraints:
+ +1 <= instructions.length <= 100
instructions[i]
is 'G'
, 'L'
or, 'R'
.You are given an array of integers stones
where stones[i]
is the weight of the ith
stone.
We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x
and y
with x <= y
. The result of this smash is:
x == y
, both stones are destroyed, andx != y
, the stone of weight x
is destroyed, and the stone of weight y
has new weight y - x
.At the end of the game, there is at most one stone left.
+ +Return the smallest possible weight of the left stone. If there are no stones left, return 0
.
+
Example 1:
+ +Input: stones = [2,7,4,1,8,1] +Output: 1 +Explanation: +We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, +we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, +we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, +we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. ++ +
Example 2:
+ +Input: stones = [31,26,33,21,40] +Output: 5 ++ +
+
Constraints:
+ +1 <= stones.length <= 30
1 <= stones[i] <= 100
Given two integer arrays preorder
and inorder
where preorder
is the preorder traversal of a binary tree and inorder
is the inorder traversal of the same tree, construct and return the binary tree.
+
Example 1:
+Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] +Output: [3,9,20,null,null,15,7] ++ +
Example 2:
+ +Input: preorder = [-1], inorder = [-1] +Output: [-1] ++ +
+
Constraints:
+ +1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
and inorder
consist of unique values.inorder
also appears in preorder
.preorder
is guaranteed to be the preorder traversal of the tree.inorder
is guaranteed to be the inorder traversal of the tree.Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
+ ++
Example 1:
+Input: nums = [-10,-3,0,5,9] +Output: [0,-3,9,-10,null,5] +Explanation: [0,-10,5,null,-3,null,9] is also accepted: ++ ++
Example 2:
+Input: nums = [1,3] +Output: [3,1] +Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. ++ +
+
Constraints:
+ +1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in a strictly increasing order.There is a car with capacity
empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity
and an array trips
where trip[i] = [numPassengersi, fromi, toi]
indicates that the ith
trip has numPassengersi
passengers and the locations to pick them up and drop them off are fromi
and toi
respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true
if it is possible to pick up and drop off all passengers for all the given trips, or false
otherwise.
+
Example 1:
+ +Input: trips = [[2,1,5],[3,3,7]], capacity = 4 +Output: false ++ +
Example 2:
+ +Input: trips = [[2,1,5],[3,3,7]], capacity = 5 +Output: true ++ +
+
Constraints:
+ +1 <= trips.length <= 1000
trips[i].length == 3
1 <= numPassengersi <= 100
0 <= fromi < toi <= 1000
1 <= capacity <= 105
You are given an integer array height
of length n
. There are n
vertical lines drawn such that the two endpoints of the ith
line are (i, 0)
and (i, height[i])
.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
+ +Return the maximum amount of water a container can store.
+ +Notice that you may not slant the container.
+ ++
Example 1:
+Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 +Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. ++ +
Example 2:
+ +Input: height = [1,1] +Output: 1 ++ +
+
Constraints:
+ +n == height.length
2 <= n <= 105
0 <= height[i] <= 104
Given a binary tree, determine if it is height-balanced.
+ +For this problem, a height-balanced binary tree is defined as:
+ +++ +a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
+
+
Example 1:
+Input: root = [3,9,20,null,null,15,7] +Output: true ++ +
Example 2:
+Input: root = [1,2,2,3,3,null,null,4,4] +Output: false ++ +
Example 3:
+ +Input: root = [] +Output: true ++ +
+
Constraints:
+ +[0, 5000]
.-104 <= Node.val <= 104
A string is a valid parentheses string (denoted VPS) if and only if it consists of "("
and ")"
characters only, and:
AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.We can similarly define the nesting depth depth(S)
of any VPS S
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.For example, ""
, "()()"
, and "()(()())"
are VPS's (with nesting depths 0, 1, and 2), and ")("
and "(()"
are not VPS's.
+ +
Given a VPS seq, split it into two disjoint subsequences A
and B
, such that A
and B
are VPS's (and A.length + B.length = seq.length
).
Now choose any such A
and B
such that max(depth(A), depth(B))
is the minimum possible value.
Return an answer
array (of length seq.length
) that encodes such a choice of A
and B
: answer[i] = 0
if seq[i]
is part of A
, else answer[i] = 1
. Note that even though multiple answers may exist, you may return any of them.
+
Example 1:
+ +Input: seq = "(()())" +Output: [0,1,1,1,1,0] ++ +
Example 2:
+ +Input: seq = "()(())()" +Output: [0,0,0,1,1,0,1,1] ++ +
+
Constraints:
+ +1 <= seq.size <= 10000
Given the root
of a binary tree, flatten the tree into a "linked list":
TreeNode
class where the right
child pointer points to the next node in the list and the left
child pointer is always null
.+
Example 1:
+Input: root = [1,2,5,3,4,null,6] +Output: [1,null,2,null,3,null,4,null,5,null,6] ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
Example 3:
+ +Input: root = [0] +Output: [0] ++ +
+
Constraints:
+ +[0, 2000]
.-100 <= Node.val <= 100
+Follow up: Can you flatten the tree in-place (with
O(1)
extra space)?Given two strings s
and t
, return the number of distinct subsequences of s
which equals t
.
A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
The test cases are generated so that the answer fits on a 32-bit signed integer.
+ ++
Example 1:
+ +Input: s = "rabbbit", t = "rabbit" +Output: 3 +Explanation: +As shown below, there are 3 ways you can generate "rabbit" from S. ++ +rabbbit
+rabbbit
+rabbbit
+
Example 2:
+ +Input: s = "babgbag", t = "bag" +Output: 5 +Explanation: +As shown below, there are 5 ways you can generate "bag" from S. ++ +babgbag
+babgbag
+babgbag
+babgbag
+babgbag
+
Constraints:
+ +1 <= s.length, t.length <= 1000
s
and t
consist of English letters.You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
+ +struct Node { + int val; + Node *left; + Node *right; + Node *next; +} ++ +
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
+
Example 1:
+Input: root = [1,2,3,4,5,6,7] +Output: [1,#,2,3,#,4,5,6,7,#] +Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
+
Constraints:
+ +[0, 212 - 1]
.-1000 <= Node.val <= 1000
+
Follow-up:
+ +Given an integer numRows
, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
++
Example 1:
+Input: numRows = 5 +Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] +
Example 2:
+Input: numRows = 1 +Output: [[1]] ++
+
Constraints:
+ +1 <= numRows <= 30
Given a triangle
array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i
on the current row, you may move to either index i
or index i + 1
on the next row.
+
Example 1:
+ +Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] +Output: 11 +Explanation: The triangle looks like: + 2 + 3 4 + 6 5 7 +4 1 8 3 +The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). ++ +
Example 2:
+ +Input: triangle = [[-10]] +Output: -10 ++ +
+
Constraints:
+ +1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
+Follow up: Could you do this using only
O(n)
extra space, where n
is the total number of rows in the triangle?You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
+ +Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
+
Example 1:
+ +Input: prices = [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. +Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. ++ +
Example 2:
+ +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0. ++ +
+
Constraints:
+ +1 <= prices.length <= 105
0 <= prices[i] <= 104
You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
+ +Find and return the maximum profit you can achieve.
+ ++
Example 1:
+ +Input: prices = [7,1,5,3,6,4] +Output: 7 +Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. +Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. +Total profit is 4 + 3 = 7. ++ +
Example 2:
+ +Input: prices = [1,2,3,4,5] +Output: 4 +Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. +Total profit is 4. ++ +
Example 3:
+ +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. ++ +
+
Constraints:
+ +1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
Given an integer n
, your task is to count how many strings of length n
can be formed under the following rules:
'a'
, 'e'
, 'i'
, 'o'
, 'u'
)'a'
may only be followed by an 'e'
.'e'
may only be followed by an 'a'
or an 'i'
.'i'
may not be followed by another 'i'
.'o'
may only be followed by an 'i'
or a 'u'
.'u'
may only be followed by an 'a'.
Since the answer may be too large, return it modulo 10^9 + 7.
+
Example 1:
+ +Input: n = 1 +Output: 5 +Explanation: All possible strings are: "a", "e", "i" , "o" and "u". ++ +
Example 2:
+ +Input: n = 2 +Output: 10 +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". ++ +
Example 3:
+ +Input: n = 5 +Output: 68+ +
+
Constraints:
+ +1 <= n <= 2 * 10^4
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
+ +Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
+ ++
Example 1:
+ +Input: prices = [3,3,5,0,0,3,1,4] +Output: 6 +Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. +Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.+ +
Example 2:
+ +Input: prices = [1,2,3,4,5] +Output: 4 +Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. +Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. ++ +
Example 3:
+ +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transaction is done, i.e. max profit = 0. ++ +
+
Constraints:
+ +1 <= prices.length <= 105
0 <= prices[i] <= 105
Given a string s of '('
, ')'
and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '('
or ')'
, in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
+ +AB
(A
concatenated with B
), where A
and B
are valid strings, or(A)
, where A
is a valid string.+
Example 1:
+ +Input: s = "lee(t(c)o)de)" +Output: "lee(t(c)o)de" +Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. ++ +
Example 2:
+ +Input: s = "a)b(c)d" +Output: "ab(c)d" ++ +
Example 3:
+ +Input: s = "))((" +Output: "" +Explanation: An empty string is also valid. ++ +
+
Constraints:
+ +1 <= s.length <= 105
s[i]
is either'('
, ')'
, or lowercase English letter.
A transformation sequence from word beginWord
to word endWord
using a dictionary wordList
is a sequence of words beginWord -> s1 -> s2 -> ... -> sk
such that:
si
for 1 <= i <= k
is in wordList
. Note that beginWord
does not need to be in wordList
.sk == endWord
Given two words, beginWord
and endWord
, and a dictionary wordList
, return all the shortest transformation sequences from beginWord
to endWord
, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]
.
+
Example 1:
+ +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] +Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] +Explanation: There are 2 shortest transformation sequences: +"hit" -> "hot" -> "dot" -> "dog" -> "cog" +"hit" -> "hot" -> "lot" -> "log" -> "cog" ++ +
Example 2:
+ +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] +Output: [] +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. ++ +
+
Constraints:
+ +1 <= beginWord.length <= 5
endWord.length == beginWord.length
1 <= wordList.length <= 500
wordList[i].length == beginWord.length
beginWord
, endWord
, and wordList[i]
consist of lowercase English letters.beginWord != endWord
wordList
are unique.A transformation sequence from word beginWord
to word endWord
using a dictionary wordList
is a sequence of words beginWord -> s1 -> s2 -> ... -> sk
such that:
si
for 1 <= i <= k
is in wordList
. Note that beginWord
does not need to be in wordList
.sk == endWord
Given two words, beginWord
and endWord
, and a dictionary wordList
, return the number of words in the shortest transformation sequence from beginWord
to endWord
, or 0
if no such sequence exists.
+
Example 1:
+ +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] +Output: 5 +Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. ++ +
Example 2:
+ +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] +Output: 0 +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. ++ +
+
Constraints:
+ +1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord
, endWord
, and wordList[i]
consist of lowercase English letters.beginWord != endWord
wordList
are unique.Given an array of integers nums
and an integer threshold
, we will choose a positive integer divisor
, divide all the array by it, and sum the division's result. Find the smallest divisor
such that the result mentioned above is less than or equal to threshold
.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3
and 10/2 = 5
).
The test cases are generated so that there will be an answer.
+ ++
Example 1:
+ +Input: nums = [1,2,5,9], threshold = 6 +Output: 5 +Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. +If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). ++ +
Example 2:
+ +Input: nums = [44,22,33,11,1], threshold = 5 +Output: 44 ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106
Given an array intervals
where intervals[i] = [li, ri]
represent the interval [li, ri)
, remove all intervals that are covered by another interval in the list.
The interval [a, b)
is covered by the interval [c, d)
if and only if c <= a
and b <= d
.
Return the number of remaining intervals.
+ ++
Example 1:
+ +Input: intervals = [[1,4],[3,6],[2,8]] +Output: 2 +Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. ++ +
Example 2:
+ +Input: intervals = [[1,4],[2,3]] +Output: 1 ++ +
+
Constraints:
+ +1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= li <= ri <= 105
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
+ +Return a sorted list of all the integers in the range [low, high]
inclusive that have sequential digits.
+
Example 1:
+Input: low = 100, high = 300 +Output: [123,234] +
Example 2:
+Input: low = 1000, high = 13000 +Output: [1234,2345,3456,4567,5678,6789,12345] ++
+
Constraints:
+ +10 <= low <= high <= 10^9
Given two binary search trees root1
and root2
, return a list containing all the integers from both trees sorted in ascending order.
+
Example 1:
+Input: root1 = [2,1,4], root2 = [1,0,3] +Output: [0,1,1,2,3,4] ++ +
Example 2:
+Input: root1 = [1,null,8], root2 = [8,1] +Output: [1,1,8,8] ++ +
+
Constraints:
+ +[0, 5000]
.-105 <= Node.val <= 105
Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
A palindrome string is a string that reads the same backward as forward.
+ ++
Example 1:
+Input: s = "aab" +Output: [["a","a","b"],["aa","b"]] +
Example 2:
+Input: s = "a" +Output: [["a"]] ++
+
Constraints:
+ +1 <= s.length <= 16
s
contains only lowercase English letters.Given a reference of a node in a connected undirected graph.
+ +Return a deep copy (clone) of the graph.
+ +Each node in the graph contains a value (int
) and a list (List[Node]
) of its neighbors.
class Node { + public int val; + public List<Node> neighbors; +} ++ +
+ +
Test case format:
+ +For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1
, the second node with val == 2
, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
+ +The given node will always be the first node with val = 1
. You must return the copy of the given node as a reference to the cloned graph.
+
Example 1:
+Input: adjList = [[2,4],[1,3],[2,4],[1,3]] +Output: [[2,4],[1,3],[2,4],[1,3]] +Explanation: There are 4 nodes in the graph. +1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). +3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). ++ +
Example 2:
+Input: adjList = [[]] +Output: [[]] +Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. ++ +
Example 3:
+ +Input: adjList = [] +Output: [] +Explanation: This an empty graph, it does not have any nodes. ++ +
+
Constraints:
+ +[0, 100]
.1 <= Node.val <= 100
Node.val
is unique for each node.You are given an m x n
binary matrix mat
of 1
's (representing soldiers) and 0
's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1
's will appear to the left of all the 0
's in each row.
A row i
is weaker than a row j
if one of the following is true:
i
is less than the number of soldiers in row j
.i < j
.Return the indices of the k
weakest rows in the matrix ordered from weakest to strongest.
+
Example 1:
+ +Input: mat = +[[1,1,0,0,0], + [1,1,1,1,0], + [1,0,0,0,0], + [1,1,0,0,0], + [1,1,1,1,1]], +k = 3 +Output: [2,0,3] +Explanation: +The number of soldiers in each row is: +- Row 0: 2 +- Row 1: 4 +- Row 2: 1 +- Row 3: 2 +- Row 4: 5 +The rows ordered from weakest to strongest are [2,0,3,1,4]. ++ +
Example 2:
+ +Input: mat = +[[1,0,0,0], + [1,1,1,1], + [1,0,0,0], + [1,0,0,0]], +k = 2 +Output: [0,2] +Explanation: +The number of soldiers in each row is: +- Row 0: 1 +- Row 1: 4 +- Row 2: 1 +- Row 3: 1 +The rows ordered from weakest to strongest are [0,2,3,1]. ++ +
+
Constraints:
+ +m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j]
is either 0 or 1.There are n
gas stations along a circular route, where the amount of gas at the ith
station is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from the ith
station to its next (i + 1)th
station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas
and cost
, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1
. If there exists a solution, it is guaranteed to be unique
+
Example 1:
+ +Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] +Output: 3 +Explanation: +Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 4. Your tank = 4 - 1 + 5 = 8 +Travel to station 0. Your tank = 8 - 2 + 1 = 7 +Travel to station 1. Your tank = 7 - 3 + 2 = 6 +Travel to station 2. Your tank = 6 - 4 + 3 = 5 +Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. +Therefore, return 3 as the starting index. ++ +
Example 2:
+ +Input: gas = [2,3,4], cost = [3,4,3] +Output: -1 +Explanation: +You can't start at station 0 or 1, as there is not enough gas to travel to the next station. +Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 0. Your tank = 4 - 3 + 2 = 3 +Travel to station 1. Your tank = 3 - 3 + 3 = 3 +You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. +Therefore, you can't travel around the circuit once no matter where you start. ++ +
+
Constraints:
+ +gas.length == n
cost.length == n
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
Given n
orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
+ +Since the answer may be too large, return it modulo 10^9 + 7.
+ ++
Example 1:
+ +Input: n = 1 +Output: 1 +Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. ++ +
Example 2:
+ +Input: n = 2 +Output: 6 +Explanation: All possible orders: +(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). +This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. ++ +
Example 3:
+ +Input: n = 3 +Output: 90 ++ +
+
Constraints:
+ +1 <= n <= 500
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
+ ++
Example 1:
+Input: nums = [2,2,1] +Output: 1 +
Example 2:
+Input: nums = [4,1,2,1,2] +Output: 4 +
Example 3:
+Input: nums = [1] +Output: 1 ++
+
Constraints:
+ +1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
A linked list of length n
is given such that each node contains an additional random pointer, which could point to any node in the list, or null
.
Construct a deep copy of the list. The deep copy should consist of exactly n
brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next
and random
pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X
and Y
in the original list, where X.random --> Y
, then for the corresponding two nodes x
and y
in the copied list, x.random --> y
.
Return the head of the copied linked list.
+ +The linked list is represented in the input/output as a list of n
nodes. Each node is represented as a pair of [val, random_index]
where:
val
: an integer representing Node.val
random_index
: the index of the node (range from 0
to n-1
) that the random
pointer points to, or null
if it does not point to any node.Your code will only be given the head
of the original linked list.
+
Example 1:
+Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] +Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] ++ +
Example 2:
+Input: head = [[1,1],[2,1]] +Output: [[1,1],[2,1]] ++ +
Example 3:
+ +Input: head = [[3,null],[3,0],[3,null]] +Output: [[3,null],[3,0],[3,null]] ++ +
+
Constraints:
+ +0 <= n <= 1000
-104 <= Node.val <= 104
Node.random
is null
or is pointing to some node in the linked list.Design a stack which supports the following operations.
+ +Implement the CustomStack
class:
CustomStack(int maxSize)
Initializes the object with maxSize
which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize
.void push(int x)
Adds x
to the top of the stack if the stack hasn't reached the maxSize
.int pop()
Pops and returns the top of stack or -1 if the stack is empty.void inc(int k, int val)
Increments the bottom k
elements of the stack by val
. If there are less than k
elements in the stack, just increment all the elements in the stack.+
Example 1:
+ +Input +["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] +[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] +Output +[null,null,null,2,null,null,null,null,null,103,202,201,-1] +Explanation +CustomStack customStack = new CustomStack(3); // Stack is Empty [] +customStack.push(1); // stack becomes [1] +customStack.push(2); // stack becomes [1, 2] +customStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1] +customStack.push(2); // stack becomes [1, 2] +customStack.push(3); // stack becomes [1, 2, 3] +customStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4 +customStack.increment(5, 100); // stack becomes [101, 102, 103] +customStack.increment(2, 100); // stack becomes [201, 202, 103] +customStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202] +customStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201] +customStack.pop(); // return 201 --> Return top of the stack 101, stack becomes [] +customStack.pop(); // return -1 --> Stack is empty return -1. ++ +
+
Constraints:
+ +1 <= maxSize <= 1000
1 <= x <= 1000
1 <= k <= 1000
0 <= val <= 100
1000
calls will be made to each method of increment
, push
and pop
each separately.Given a string s
and a dictionary of strings wordDict
, return true
if s
can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
+ ++
Example 1:
+ +Input: s = "leetcode", wordDict = ["leet","code"] +Output: true +Explanation: Return true because "leetcode" can be segmented as "leet code". ++ +
Example 2:
+ +Input: s = "applepenapple", wordDict = ["apple","pen"] +Output: true +Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". +Note that you are allowed to reuse a dictionary word. ++ +
Example 3:
+ +Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] +Output: false ++ +
+
Constraints:
+ +1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
and wordDict[i]
consist of only lowercase English letters.wordDict
are unique.Given head
, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter.
Return true
if there is a cycle in the linked list. Otherwise, return false
.
+
Example 1:
+Input: head = [3,2,0,-4], pos = 1 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). ++ +
Example 2:
+Input: head = [1,2], pos = 0 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. ++ +
Example 3:
+Input: head = [1], pos = -1 +Output: false +Explanation: There is no cycle in the linked list. ++ +
+
Constraints:
+ +[0, 104]
.-105 <= Node.val <= 105
pos
is -1
or a valid index in the linked-list.+
Follow up: Can you solve it using O(1)
(i.e. constant) memory?
Given the head
of a linked list, return the node where the cycle begins. If there is no cycle, return null
.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to (0-indexed). It is -1
if there is no cycle. Note that pos
is not passed as a parameter.
Do not modify the linked list.
+ ++
Example 1:
+Input: head = [3,2,0,-4], pos = 1 +Output: tail connects to node index 1 +Explanation: There is a cycle in the linked list, where tail connects to the second node. ++ +
Example 2:
+Input: head = [1,2], pos = 0 +Output: tail connects to node index 0 +Explanation: There is a cycle in the linked list, where tail connects to the first node. ++ +
Example 3:
+Input: head = [1], pos = -1 +Output: no cycle +Explanation: There is no cycle in the linked list. ++ +
+
Constraints:
+ +[0, 104]
.-105 <= Node.val <= 105
pos
is -1
or a valid index in the linked-list.+
Follow up: Can you solve it using O(1)
(i.e. constant) memory?
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints
.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k
cards.
Your score is the sum of the points of the cards you have taken.
+ +Given the integer array cardPoints
and the integer k
, return the maximum score you can obtain.
+
Example 1:
+ +Input: cardPoints = [1,2,3,4,5,6,1], k = 3 +Output: 12 +Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. ++ +
Example 2:
+ +Input: cardPoints = [2,2,2], k = 2 +Output: 4 +Explanation: Regardless of which two cards you take, your score will always be 4. ++ +
Example 3:
+ +Input: cardPoints = [9,7,7,9,7,7,9], k = 7 +Output: 55 +Explanation: You have to take all the cards. Your score is the sum of points of all cards. ++ +
+
Constraints:
+ +1 <= cardPoints.length <= 105
1 <= cardPoints[i] <= 104
1 <= k <= cardPoints.length
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
+
Example 1:
+Input: root = [1,null,2,3] +Output: [1,2,3] ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
Example 3:
+ +Input: root = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100]
.-100 <= Node.val <= 100
+
Follow up: Recursive solution is trivial, could you do it iteratively?
+Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
+ +Implement the LRUCache
class:
LRUCache(int capacity)
Initialize the LRU cache with positive size capacity
.int get(int key)
Return the value of the key
if the key exists, otherwise return -1
.void put(int key, int value)
Update the value of the key
if the key
exists. Otherwise, add the key-value
pair to the cache. If the number of keys exceeds the capacity
from this operation, evict the least recently used key.The functions get
and put
must each run in O(1)
average time complexity.
+
Example 1:
+ +Input +["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] +Output +[null, null, null, 1, null, -1, null, -1, 3, 4] + +Explanation +LRUCache lRUCache = new LRUCache(2); +lRUCache.put(1, 1); // cache is {1=1} +lRUCache.put(2, 2); // cache is {1=1, 2=2} +lRUCache.get(1); // return 1 +lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} +lRUCache.get(2); // returns -1 (not found) +lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} +lRUCache.get(1); // return -1 (not found) +lRUCache.get(3); // return 3 +lRUCache.get(4); // return 4 ++ +
+
Constraints:
+ +1 <= capacity <= 3000
0 <= key <= 104
0 <= value <= 105
* 105
calls will be made to get
and put
.You are given a rectangular cake of size h x w
and two arrays of integers horizontalCuts
and verticalCuts
where:
horizontalCuts[i]
is the distance from the top of the rectangular cake to the ith
horizontal cut and similarly, andverticalCuts[j]
is the distance from the left of the rectangular cake to the jth
vertical cut.Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts
and verticalCuts
. Since the answer can be a large number, return this modulo 109 + 7
.
+
Example 1:
+Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] +Output: 4 +Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. ++ +
Example 2:
+Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] +Output: 6 +Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. ++ +
Example 3:
+ +Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] +Output: 9 ++ +
+
Constraints:
+ +2 <= h, w <= 109
1 <= horizontalCuts.length <= min(h - 1, 105)
1 <= verticalCuts.length <= min(w - 1, 105)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
horizontalCuts
are distinct.verticalCuts
are distinct.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.5000
calls will be made to visit
, back
, and forward
.Given the head
of a linked list, return the list after sorting it in ascending order.
+
Example 1:
+Input: head = [4,2,1,3] +Output: [1,2,3,4] ++ +
Example 2:
+Input: head = [-1,5,3,4,0] +Output: [-1,0,3,4,5] ++ +
Example 3:
+ +Input: head = [] +Output: [] ++ +
+
Constraints:
+ +[0, 5 * 104]
.-105 <= Node.val <= 105
+
Follow up: Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
Alice and Bob take turns playing a game, with Alice starting first.
+ +Initially, there are n
stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
+ +Given a positive integer n
, return true
if and only if Alice wins the game otherwise return false
, assuming both players play optimally.
+
Example 1:
+ +Input: n = 1 +Output: true +Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.+ +
Example 2:
+ +Input: n = 2 +Output: false +Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). ++ +
Example 3:
+ +Input: n = 4 +Output: true +Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). ++ +
+
Constraints:
+ +1 <= n <= 105
Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times. For example, the array nums = [0,1,2,4,5,6,7]
might become:
[4,5,6,7,0,1,2]
if it was rotated 4
times.[0,1,2,4,5,6,7]
if it was rotated 7
times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
+
Example 1:
+ +Input: nums = [3,4,5,1,2] +Output: 1 +Explanation: The original array was [1,2,3,4,5] rotated 3 times. ++ +
Example 2:
+ +Input: nums = [4,5,6,7,0,1,2] +Output: 0 +Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. ++ +
Example 3:
+ +Input: nums = [11,13,15,17] +Output: 11 +Explanation: The original array was [11,13,15,17] and it was rotated 4 times. ++ +
+
Constraints:
+ +n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums
are unique.nums
is sorted and rotated between 1
and n
times.Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times. For example, the array nums = [0,1,4,4,5,6,7]
might become:
[4,5,6,7,0,1,4]
if it was rotated 4
times.[0,1,4,4,5,6,7]
if it was rotated 7
times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
+ ++
Example 1:
+Input: nums = [1,3,5] +Output: 1 +
Example 2:
+Input: nums = [2,2,2,0,1] +Output: 0 ++
+
Constraints:
+ +n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums
is sorted and rotated between 1
and n
times.+
Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums
may contain duplicates. Would this affect the runtime complexity? How and why?
+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
+ +Implement the MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the element val
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.You must implement a solution with O(1)
time complexity for each function.
+
Example 1:
+ +Input +["MinStack","push","push","push","getMin","pop","top","getMin"] +[[],[-2],[0],[-3],[],[],[],[]] + +Output +[null,null,null,null,-3,null,0,-2] + +Explanation +MinStack minStack = new MinStack(); +minStack.push(-2); +minStack.push(0); +minStack.push(-3); +minStack.getMin(); // return -3 +minStack.pop(); +minStack.top(); // return 0 +minStack.getMin(); // return -2 ++ +
+
Constraints:
+ +-231 <= val <= 231 - 1
pop
, top
and getMin
operations will always be called on non-empty stacks.3 * 104
calls will be made to push
, pop
, top
, and getMin
.In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n
empty baskets, the ith
basket is at position[i]
, Morty has m
balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x
and y
is |x - y|
.
Given the integer array position
and the integer m
. Return the required force.
+
Example 1:
+Input: position = [1,2,3,4,7], m = 3 +Output: 3 +Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. ++ +
Example 2:
+ +Input: position = [5,4,3,2,1,1000000000], m = 2 +Output: 999999999 +Explanation: We can use baskets 1 and 1000000000. ++ +
+
Constraints:
+ +n == position.length
2 <= n <= 105
1 <= position[i] <= 109
position
are distinct.2 <= m <= position.length
Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
For example, the following two linked lists begin to intersect at node c1
:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
+ +Note that the linked lists must retain their original structure after the function returns.
+ +Custom Judge:
+ +The inputs to the judge are given as follows (your program is not given these inputs):
+ +intersectVal
- The value of the node where the intersection occurs. This is 0
if there is no intersected node.listA
- The first linked list.listB
- The second linked list.skipA
- The number of nodes to skip ahead in listA
(starting from the head) to get to the intersected node.skipB
- The number of nodes to skip ahead in listB
(starting from the head) to get to the intersected node.The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
+
Example 1:
+Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 +Output: Intersected at '8' +Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. ++ +
Example 2:
+Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 +Output: Intersected at '2' +Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. ++ +
Example 3:
+Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 +Output: No intersection +Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. +Explanation: The two lists do not intersect, so return null. ++ +
+
Constraints:
+ +listA
is in the m
.listB
is in the n
.1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA < m
0 <= skipB < n
intersectVal
is 0
if listA
and listB
do not intersect.intersectVal == listA[skipA] == listB[skipB]
if listA
and listB
intersect.+Follow up: Could you write a solution that runs in
O(m + n)
time and use only O(1)
memory?A peak element is an element that is strictly greater than its neighbors.
+ +Given an integer array nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞
.
You must write an algorithm that runs in O(log n)
time.
+
Example 1:
+ +Input: nums = [1,2,3,1] +Output: 2 +Explanation: 3 is a peak element and your function should return the index number 2.+ +
Example 2:
+ +Input: nums = [1,2,1,3,5,6,4] +Output: 5 +Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.+ +
+
Constraints:
+ +1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all valid i
.Given two version numbers, version1
and version2
, compare them.
Version numbers consist of one or more revisions joined by a dot '.'
. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33
and 0.1
are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1
and 001
are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0
. For example, version 1.0
is less than version 1.1
because their revision 0s are the same, but their revision 1s are 0
and 1
respectively, and 0 < 1
.
Return the following:
+ +version1 < version2
, return -1
.version1 > version2
, return 1
.0
.+
Example 1:
+ +Input: version1 = "1.01", version2 = "1.001" +Output: 0 +Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". ++ +
Example 2:
+ +Input: version1 = "1.0", version2 = "1.0.0" +Output: 0 +Explanation: version1 does not specify revision 2, which means it is treated as "0". ++ +
Example 3:
+ +Input: version1 = "0.1", version2 = "1.1" +Output: -1 +Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. ++ +
+
Constraints:
+ +1 <= version1.length, version2.length <= 500
version1
and version2
only contain digits and '.'
.version1
and version2
are valid version numbers.version1
and version2
can be stored in a 32-bit integer.You are given an m x n
integer grid accounts
where accounts[i][j]
is the amount of money the ith
customer has in the jth
bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
+ ++
Example 1:
+ +Input: accounts = [[1,2,3],[3,2,1]] +Output: 6 +Explanation: ++ +1st customer has wealth = 1 + 2 + 3 = 6 +
2nd customer has wealth = 3 + 2 + 1 = 6 +
Both customers are considered the richest with a wealth of 6 each, so return 6. +
Example 2:
+ +Input: accounts = [[1,5],[7,3],[3,5]] +Output: 10 +Explanation: +1st customer has wealth = 6 +2nd customer has wealth = 10 +3rd customer has wealth = 8 +The 2nd customer is the richest with a wealth of 10.+ +
Example 3:
+ +Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] +Output: 17 ++ +
+
Constraints:
+ +m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
You are given an array nums
of n
positive integers.
You can perform two types of operations on any element of the array any number of times:
+ +2
.
+
+ [1,2,3,4]
, then you can do this operation on the last element, and the array will be [1,2,3,2].
2
.
+ [1,2,3,4]
, then you can do this operation on the first element, and the array will be [2,2,3,4].
The deviation of the array is the maximum difference between any two elements in the array.
+ +Return the minimum deviation the array can have after performing some number of operations.
+ ++
Example 1:
+ +Input: nums = [1,2,3,4] +Output: 1 +Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. ++ +
Example 2:
+ +Input: nums = [4,1,5,20,3] +Output: 3 +Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. ++ +
Example 3:
+ +Input: nums = [2,10,8] +Output: 3 ++ +
+
Constraints:
+ +n == nums.length
2 <= n <= 105
1 <= nums[i] <= 109
Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
+
Example 1:
+Input: nums = [3,2,3] +Output: 3 +
Example 2:
+Input: nums = [2,2,1,1,1,2,2] +Output: 2 ++
+
Constraints:
+ +n == nums.length
1 <= n <= 5 * 104
-231 <= nums[i] <= 231 - 1
+Follow-up: Could you solve the problem in linear time and in
O(1)
space?Given a string columnTitle
that represents the column title as appear in an Excel sheet, return its corresponding column number.
For example:
+ +A -> 1 +B -> 2 +C -> 3 +... +Z -> 26 +AA -> 27 +AB -> 28 +... ++ +
+
Example 1:
+ +Input: columnTitle = "A" +Output: 1 ++ +
Example 2:
+ +Input: columnTitle = "AB" +Output: 28 ++ +
Example 3:
+ +Input: columnTitle = "ZY" +Output: 701 ++ +
+
Constraints:
+ +1 <= columnTitle.length <= 7
columnTitle
consists only of uppercase English letters.columnTitle
is in the range ["A", "FXSHRXW"]
.You are given an integer array nums
where the ith
bag contains nums[i]
balls. You are also given an integer maxOperations
.
You can perform the following operation at most maxOperations
times:
5
balls can become two new bags of 1
and 4
balls, or two new bags of 2
and 3
balls.Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.
+ +Return the minimum possible penalty after performing the operations.
+ ++
Example 1:
+ +Input: nums = [9], maxOperations = 2 +Output: 3 +Explanation: +- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3]. +- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3]. +The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. ++ +
Example 2:
+ +Input: nums = [2,4,8,2], maxOperations = 4 +Output: 2 +Explanation: +- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2]. +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2]. +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2]. +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2]. +The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2. ++ +
Example 3:
+ +Input: nums = [7,17], maxOperations = 2 +Output: 7 ++ +
+
Constraints:
+ +1 <= nums.length <= 105
1 <= maxOperations, nums[i] <= 109
Given a list of non-negative integers nums
, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
+ ++
Example 1:
+ +Input: nums = [10,2] +Output: "210" ++ +
Example 2:
+ +Input: nums = [3,30,34,5,9] +Output: "9534330" ++ +
+
Constraints:
+ +1 <= nums.length <= 100
0 <= nums[i] <= 109
Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
, b
, c
, and d
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
+ ++
Example 1:
+ +Input: nums = [1,0,-1,0,-2,2], target = 0 +Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] ++ +
Example 2:
+ +Input: nums = [2,2,2,2,2], target = 8 +Output: [[2,2,2,2]] ++ +
+
Constraints:
+ +1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
There are n
friends that are playing a game. The friends are sitting in a circle and are numbered from 1
to n
in clockwise order. More formally, moving clockwise from the ith
friend brings you to the (i+1)th
friend for 1 <= i < n
, and moving clockwise from the nth
friend brings you to the 1st
friend.
The rules of the game are as follows:
+ +1st
friend.k
friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.2
starting from the friend immediately clockwise of the friend who just lost and repeat.Given the number of friends, n
, and an integer k
, return the winner of the game.
+
Example 1:
+Input: n = 5, k = 2 +Output: 3 +Explanation: Here are the steps of the game: +1) Start at friend 1. +2) Count 2 friends clockwise, which are friends 1 and 2. +3) Friend 2 leaves the circle. Next start is friend 3. +4) Count 2 friends clockwise, which are friends 3 and 4. +5) Friend 4 leaves the circle. Next start is friend 5. +6) Count 2 friends clockwise, which are friends 5 and 1. +7) Friend 1 leaves the circle. Next start is friend 3. +8) Count 2 friends clockwise, which are friends 3 and 5. +9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.+ +
Example 2:
+ +Input: n = 6, k = 5 +Output: 1 +Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. ++ +
+
Constraints:
+ +1 <= k <= n <= 500
Given an array, rotate the array to the right by k
steps, where k
is non-negative.
+
Example 1:
+ +Input: nums = [1,2,3,4,5,6,7], k = 3 +Output: [5,6,7,1,2,3,4] +Explanation: +rotate 1 steps to the right: [7,1,2,3,4,5,6] +rotate 2 steps to the right: [6,7,1,2,3,4,5] +rotate 3 steps to the right: [5,6,7,1,2,3,4] ++ +
Example 2:
+ +Input: nums = [-1,-100,3,99], k = 2 +Output: [3,99,-1,-100] +Explanation: +rotate 1 steps to the right: [99,-1,-100,3] +rotate 2 steps to the right: [3,99,-1,-100] ++ +
+
Constraints:
+ +1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
+
Follow up:
+ +O(1)
extra space?You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
+ +You may assume the two numbers do not contain any leading zero, except the number 0 itself.
+ ++
Example 1:
+Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +Explanation: 342 + 465 = 807. ++ +
Example 2:
+ +Input: l1 = [0], l2 = [0] +Output: [0] ++ +
Example 3:
+ +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] ++ +
+
Constraints:
+ +[1, 100]
.0 <= Node.val <= 9
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
+ ++
Example 1:
+ +Input: s = "()" +Output: true ++ +
Example 2:
+ +Input: s = "()[]{}" +Output: true ++ +
Example 3:
+ +Input: s = "(]" +Output: false ++ +
+
Constraints:
+ +1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
+
Example 1:
+Input: head = [1,2,6,3,4,5,6], val = 6 +Output: [1,2,3,4,5] ++ +
Example 2:
+ +Input: head = [], val = 1 +Output: [] ++ +
Example 3:
+ +Input: head = [7,7,7,7], val = 7 +Output: [] ++ +
+
Constraints:
+ +[0, 104]
.1 <= Node.val <= 50
0 <= val <= 50
Given the head
of a singly linked list, reverse the list, and return the reversed list.
+
Example 1:
+Input: head = [1,2,3,4,5] +Output: [5,4,3,2,1] ++ +
Example 2:
+Input: head = [1,2] +Output: [2,1] ++ +
Example 3:
+ +Input: head = [] +Output: [] ++ +
+
Constraints:
+ +[0, 5000]
.-5000 <= Node.val <= 5000
+
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
+Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
+
Example 1:
+ +Input: target = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: The subarray [4,3] has the minimal length under the problem constraint. ++ +
Example 2:
+ +Input: target = 4, nums = [1,4,4] +Output: 1 ++ +
Example 3:
+ +Input: target = 11, nums = [1,1,1,1,1,1,1,1] +Output: 0 ++ +
+
Constraints:
+ +1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
+Follow up: If you have figured out the
O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
+ +Return the head of the merged linked list.
+ ++
Example 1:
+Input: list1 = [1,2,4], list2 = [1,3,4] +Output: [1,1,2,3,4,4] ++ +
Example 2:
+ +Input: list1 = [], list2 = [] +Output: [] ++ +
Example 3:
+ +Input: list1 = [], list2 = [0] +Output: [0] ++ +
+
Constraints:
+ +[0, 50]
.-100 <= Node.val <= 100
list1
and list2
are sorted in non-decreasing order.You are given a 0-indexed array of n
integers differences
, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1)
. More formally, call the hidden sequence hidden
, then we have that differences[i] = hidden[i + 1] - hidden[i]
.
You are further given two integers lower
and upper
that describe the inclusive range of values [lower, upper]
that the hidden sequence can contain.
differences = [1, -3, 4]
, lower = 1
, upper = 6
, the hidden sequence is a sequence of length 4
whose elements are in between 1
and 6
(inclusive).
+
+ [3, 4, 1, 5]
and [4, 5, 2, 6]
are possible hidden sequences.[5, 6, 3, 7]
is not possible since it contains an element greater than 6
.[1, 2, 3, 4]
is not possible since the differences are not correct.Return the number of possible hidden sequences there are. If there are no possible sequences, return 0
.
+
Example 1:
+ +Input: differences = [1,-3,4], lower = 1, upper = 6 +Output: 2 +Explanation: The possible hidden sequences are: +- [3, 4, 1, 5] +- [4, 5, 2, 6] +Thus, we return 2. ++ +
Example 2:
+ +Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5 +Output: 4 +Explanation: The possible hidden sequences are: +- [-3, 0, -4, 1, 2, 0] +- [-2, 1, -3, 2, 3, 1] +- [-1, 2, -2, 3, 4, 2] +- [0, 3, -1, 4, 5, 3] +Thus, we return 4. ++ +
Example 3:
+ +Input: differences = [4,-7,2], lower = 3, upper = 6 +Output: 0 +Explanation: There are no possible hidden sequences. Thus, we return 0. ++ +
+
Constraints:
+ +n == differences.length
1 <= n <= 105
-105 <= differences[i] <= 105
-105 <= lower <= upper <= 105
You are given a 0-indexed integer array nums
representing the contents of a pile, where nums[0]
is the topmost element of the pile.
In one move, you can perform either of the following:
+ +You are also given an integer k
, which denotes the total number of moves to be made.
Return the maximum value of the topmost element of the pile possible after exactly k
moves. In case it is not possible to obtain a non-empty pile after k
moves, return -1
.
+
Example 1:
+ +Input: nums = [5,2,2,4,0,6], k = 4 +Output: 5 +Explanation: +One of the ways we can end with 5 at the top of the pile after 4 moves is as follows: +- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6]. +- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6]. +- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6]. +- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6]. +Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves. ++ +
Example 2:
+ +Input: nums = [2], k = 1 +Output: -1 +Explanation: +In the first move, our only option is to pop the topmost element of the pile. +Since it is not possible to obtain a non-empty pile after one move, we return -1. ++ +
+
Constraints:
+ +1 <= nums.length <= 105
0 <= nums[i], k <= 109
You are given a 0-indexed string text
and another 0-indexed string pattern
of length 2
, both of which consist of only lowercase English letters.
You can add either pattern[0]
or pattern[1]
anywhere in text
exactly once. Note that the character can be added even at the beginning or at the end of text
.
Return the maximum number of times pattern
can occur as a subsequence of the modified text
.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
+ ++
Example 1:
+ +Input: text = "abdcdbc", pattern = "ac" +Output: 4 +Explanation: +If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4. +Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc". +However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal. +It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character. ++ +
Example 2:
+ +Input: text = "aabb", pattern = "ab" +Output: 6 +Explanation: +Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb". ++ +
+
Constraints:
+ +1 <= text.length <= 105
pattern.length == 2
text
and pattern
consist only of lowercase English letters.Given an m x n
binary matrix
filled with 0
's and 1
's, find the largest square containing only 1
's and return its area.
+
Example 1:
+Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] +Output: 4 ++ +
Example 2:
+Input: matrix = [["0","1"],["1","0"]] +Output: 1 ++ +
Example 3:
+ +Input: matrix = [["0"]] +Output: 0 ++ +
+
Constraints:
+ +m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
is '0'
or '1'
.Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push
, top
, pop
, and empty
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returns true
if the stack is empty, false
otherwise.Notes:
+ +push to back
, peek/pop from front
, size
and is empty
operations are valid.+
Example 1:
+ +Input +["MyStack", "push", "push", "top", "pop", "empty"] +[[], [1], [2], [], [], []] +Output +[null, null, null, 2, 2, false] + +Explanation +MyStack myStack = new MyStack(); +myStack.push(1); +myStack.push(2); +myStack.top(); // return 2 +myStack.pop(); // return 2 +myStack.empty(); // return False ++ +
+
Constraints:
+ +1 <= x <= 9
100
calls will be made to push
, pop
, top
, and empty
.pop
and top
are valid.+
Follow-up: Can you implement the stack using only one queue?
+Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
+
Example 1:
+ +Input: nums = [3,2,3] +Output: [3] ++ +
Example 2:
+ +Input: nums = [1] +Output: [1] ++ +
Example 3:
+ +Input: nums = [1,2] +Output: [1,2] ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 104
-109 <= nums[i] <= 109
+
Follow up: Could you solve the problem in linear time and in O(1)
space?
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
+ ++
Example 1:
+ +Input: lists = [[1,4,5],[1,3,4],[2,6]] +Output: [1,1,2,3,4,4,5,6] +Explanation: The linked-lists are: +[ + 1->4->5, + 1->3->4, + 2->6 +] +merging them into one sorted list: +1->1->2->3->4->4->5->6 ++ +
Example 2:
+ +Input: lists = [] +Output: [] ++ +
Example 3:
+ +Input: lists = [[]] +Output: [] ++ +
+
Constraints:
+ +k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
is sorted in ascending order.lists[i].length
won't exceed 10^4
.Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
+
Example 1:
+ +Input: n = 1 +Output: true +Explanation: 20 = 1 ++ +
Example 2:
+ +Input: n = 16 +Output: true +Explanation: 24 = 16 ++ +
Example 3:
+ +Input: n = 3 +Output: false ++ +
+
Constraints:
+ +-231 <= n <= 231 - 1
+Follow up: Could you solve it without loops/recursion?
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes element x to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returns true
if the queue is empty, false
otherwise.Notes:
+ +push to top
, peek/pop from top
, size
, and is empty
operations are valid.+
Example 1:
+ +Input +["MyQueue", "push", "push", "peek", "pop", "empty"] +[[], [1], [2], [], [], []] +Output +[null, null, null, 1, 1, false] + +Explanation +MyQueue myQueue = new MyQueue(); +myQueue.push(1); // queue is: [1] +myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) +myQueue.peek(); // return 1 +myQueue.pop(); // return 1, queue is [2] +myQueue.empty(); // return false ++ +
+
Constraints:
+ +1 <= x <= 9
100
calls will be made to push
, pop
, peek
, and empty
.pop
and peek
are valid.+
Follow-up: Can you implement the queue such that each operation is amortized O(1)
time complexity? In other words, performing n
operations will take overall O(n)
time even if one of those operations may take longer.
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:
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 +Output: 3 +Explanation: The LCA of nodes 5 and 1 is 3. ++ +
Example 2:
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 +Output: 5 +Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. ++ +
Example 3:
+ +Input: root = [1,2], p = 1, q = 2 +Output: 1 ++ +
+
Constraints:
+ +[2, 105]
.-109 <= Node.val <= 109
Node.val
are unique.p != q
p
and q
will exist in the tree.Write a function to delete a node in a singly-linked list. You will not be given access to the head
of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
+ ++
Example 1:
+Input: head = [4,5,1,9], node = 5 +Output: [4,1,9] +Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. ++ +
Example 2:
+Input: head = [4,5,1,9], node = 1 +Output: [4,5,9] +Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. ++ +
+
Constraints:
+ +[2, 1000]
.-1000 <= Node.val <= 1000
node
to be deleted is in the list and is not a tail nodeGiven an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
+
Example 1:
+Input: nums = [1,2,3,4] +Output: [24,12,8,6] +
Example 2:
+Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] ++
+
Constraints:
+ +2 <= nums.length <= 105
-30 <= nums[i] <= 30
nums
is guaranteed to fit in a 32-bit integer.+
Follow up: Can you solve the problem in O(1)
extra space complexity? (The output array does not count as extra space for space complexity analysis.)
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
+ ++
Example 1:
+ +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 +Output: [3,3,5,5,6,7] +Explanation: +Window position Max +--------------- ----- +[1 3 -1] -3 5 3 6 7 3 + 1 [3 -1 -3] 5 3 6 7 3 + 1 3 [-1 -3 5] 3 6 7 5 + 1 3 -1 [-3 5 3] 6 7 5 + 1 3 -1 -3 [5 3 6] 7 6 + 1 3 -1 -3 5 [3 6 7] 7 ++ +
Example 2:
+ +Input: nums = [1], k = 1 +Output: [1] ++ +
+
Constraints:
+ +1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
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] ++ +
Example 2:
+ +Input: head = [] +Output: [] ++ +
Example 3:
+ +Input: head = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100]
.0 <= Node.val <= 100
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
Example 1:
+Input: s = "anagram", t = "nagaram" +Output: true +
Example 2:
+Input: s = "rat", t = "car" +Output: false ++
+
Constraints:
+ +1 <= s.length, t.length <= 5 * 104
s
and t
consist of lowercase English letters.+
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
+Given the head
of a linked list, reverse the nodes of the list k
at a time, and return the modified list.
k
is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k
then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
+ ++
Example 1:
+Input: head = [1,2,3,4,5], k = 2 +Output: [2,1,4,3,5] ++ +
Example 2:
+Input: head = [1,2,3,4,5], k = 3 +Output: [3,2,1,4,5] ++ +
+
Constraints:
+ +n
.1 <= k <= n <= 5000
0 <= Node.val <= 1000
+
Follow-up: Can you solve the problem in O(1)
extra memory space?
Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
+
Example 1:
+ +Input: num = 38 +Output: 2 +Explanation: The process is +38 --> 3 + 8 --> 11 +11 --> 1 + 1 --> 2 +Since 2 has only one digit, return it. ++ +
Example 2:
+ +Input: num = 0 +Output: 0 ++ +
+
Constraints:
+ +0 <= num <= 231 - 1
+
Follow up: Could you do it without any loop/recursion in O(1)
runtime?
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
Return k
after placing the final result in the first k
slots of nums
.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
+ +Custom Judge:
+ +The judge will test your solution with the following code:
+ +int[] nums = [...]; // Input array +int[] expectedNums = [...]; // The expected answer with correct length + +int k = removeDuplicates(nums); // Calls your implementation + +assert k == expectedNums.length; +for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; +} ++ +
If all assertions pass, then your solution will be accepted.
+ ++
Example 1:
+ +Input: nums = [1,1,2] +Output: 2, nums = [1,2,_] +Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). ++ +
Example 2:
+ +Input: nums = [0,0,1,1,1,2,2,3,3,4] +Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] +Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
+ ++
Example 1:
+Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] +
Example 2:
+Input: nums = [0] +Output: [0] ++
+
Constraints:
+ +1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
+Follow up: Could you minimize the total number of operations done?
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive.
There is only one repeated number in nums
, return this repeated number.
You must solve the problem without modifying the array nums
and uses only constant extra space.
+
Example 1:
+ +Input: nums = [1,3,4,2,2] +Output: 2 ++ +
Example 2:
+ +Input: nums = [3,1,3,4,2] +Output: 3 ++ +
+
Constraints:
+ +1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums
appear only once except for precisely one integer which appears two or more times.+
Follow up:
+ +nums
?You are given a string s
and an array of strings words
of the same length. Return all starting indices of substring(s) in s
that is a concatenation of each word in words
exactly once, in any order, and without any intervening characters.
You can return the answer in any order.
+ ++
Example 1:
+ +Input: s = "barfoothefoobarman", words = ["foo","bar"] +Output: [0,9] +Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively. +The output order does not matter, returning [9,0] is fine too. ++ +
Example 2:
+ +Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] +Output: [] ++ +
Example 3:
+ +Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] +Output: [6,9,12] ++ +
+
Constraints:
+ +1 <= s.length <= 104
1 <= words.length <= 5000
1 <= words[i].length <= 30
s
and words[i]
consist of lowercase English letters.Given an integer array nums
, handle multiple queries of the following types:
nums
.nums
between indices left
and right
inclusive where left <= right
.Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.void update(int index, int val)
Updates the value of nums[index]
to be val
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]
).+
Example 1:
+ +Input +["NumArray", "sumRange", "update", "sumRange"] +[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]] +Output +[null, 9, null, 8] + +Explanation +NumArray numArray = new NumArray([1, 3, 5]); +numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 +numArray.update(1, 2); // nums = [1, 2, 5] +numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
0 <= index < nums.length
-100 <= val <= 100
0 <= left <= right < nums.length
3 * 104
calls will be made to update
and sumRange
.Given a string s
, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
+
Example 1:
+ +Input: s = "bcabc" +Output: "abc" ++ +
Example 2:
+ +Input: s = "cbacdcbc" +Output: "acdb" ++ +
+
Constraints:
+ +1 <= s.length <= 104
s
consists of lowercase English letters.+
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
+Given an integer n
, return true
if it is a power of three. Otherwise, return false
.
An integer n
is a power of three, if there exists an integer x
such that n == 3x
.
+
Example 1:
+ +Input: n = 27 +Output: true ++ +
Example 2:
+ +Input: n = 0 +Output: false ++ +
Example 3:
+ +Input: n = 9 +Output: true ++ +
+
Constraints:
+ +-231 <= n <= 231 - 1
+Follow up: Could you solve it without loops/recursion?
There is an integer array nums
sorted in ascending order (with distinct values).
Prior to being passed to your function, nums
is possibly rotated at an unknown pivot index k
(1 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,5,6,7]
might be rotated at pivot index 3
and become [4,5,6,7,0,1,2]
.
Given the array nums
after the possible rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not in nums
.
You must write an algorithm with O(log n)
runtime complexity.
+
Example 1:
+Input: nums = [4,5,6,7,0,1,2], target = 0 +Output: 4 +
Example 2:
+Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 +
Example 3:
+Input: nums = [1], target = 0 +Output: -1 ++
+
Constraints:
+ +1 <= nums.length <= 5000
-104 <= nums[i] <= 104
nums
are unique.nums
is an ascending array that is possibly rotated.-104 <= target <= 104
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
+
Example 1:
+Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] +
Example 2:
+Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] +
Example 3:
+Input: nums = [], target = 0 +Output: [-1,-1] ++
+
Constraints:
+ +0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
is a non-decreasing array.-109 <= target <= 109
Given an integer n
, return true
if it is a power of four. Otherwise, return false
.
An integer n
is a power of four, if there exists an integer x
such that n == 4x
.
+
Example 1:
+Input: n = 16 +Output: true +
Example 2:
+Input: n = 5 +Output: false +
Example 3:
+Input: n = 1 +Output: true ++
+
Constraints:
+ +-231 <= n <= 231 - 1
+Follow up: Could you solve it without loops/recursion?
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
+
Example 1:
+Input: s = ["h","e","l","l","o"] +Output: ["o","l","l","e","h"] +
Example 2:
+Input: s = ["H","a","n","n","a","h"] +Output: ["h","a","n","n","a","H"] ++
+
Constraints:
+ +1 <= s.length <= 105
s[i]
is a printable ascii character.Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
+
Example 1:
+Input: s = "hello" +Output: "holle" +
Example 2:
+Input: s = "leetcode" +Output: "leotcede" ++
+
Constraints:
+ +1 <= s.length <= 3 * 105
s
consist of printable ASCII characters.Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
+
Example 1:
+Input: nums = [1,1,1,2,2,3], k = 2 +Output: [1,2] +
Example 2:
+Input: nums = [1], k = 1 +Output: [1] ++
+
Constraints:
+ +1 <= nums.length <= 105
k
is in the range [1, the number of unique elements in the array]
.+
Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
+ +You must write an algorithm with O(log n)
runtime complexity.
+
Example 1:
+ +Input: nums = [1,3,5,6], target = 5 +Output: 2 ++ +
Example 2:
+ +Input: nums = [1,3,5,6], target = 2 +Output: 1 ++ +
Example 3:
+ +Input: nums = [1,3,5,6], target = 7 +Output: 4 ++ +
+
Constraints:
+ +1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
Write a program to solve a Sudoku puzzle by filling the empty cells.
+ +A sudoku solution must satisfy all of the following rules:
+ +1-9
must occur exactly once in each row.1-9
must occur exactly once in each column.1-9
must occur exactly once in each of the 9 3x3
sub-boxes of the grid.The '.'
character indicates empty cells.
+
Example 1:
+Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] +Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] +Explanation: The input board is shown above and the only valid solution is shown below: + ++ ++
+
Constraints:
+ +board.length == 9
board[i].length == 9
board[i][j]
is a digit or '.'
.The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
+ +countAndSay(1) = "1"
countAndSay(n)
is the way you would "say" the digit string from countAndSay(n-1)
, which is then converted into a different digit string.To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.
+ +For example, the saying and conversion for digit string "3322251"
:
Given a positive integer n
, return the nth
term of the count-and-say sequence.
+
Example 1:
+ +Input: n = 1 +Output: "1" +Explanation: This is the base case. ++ +
Example 2:
+ +Input: n = 4 +Output: "1211" +Explanation: +countAndSay(1) = "1" +countAndSay(2) = say "1" = one 1 = "11" +countAndSay(3) = say "11" = two 1's = "21" +countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" ++ +
+
Constraints:
+ +1 <= n <= 30
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
+ +Implement the Solution
class:
Solution(ListNode head)
Initializes the object with the integer array nums.int getRandom()
Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen.+
Example 1:
+Input +["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] +[[[1, 2, 3]], [], [], [], [], []] +Output +[null, 1, 3, 2, 2, 3] + +Explanation +Solution solution = new Solution([1, 2, 3]); +solution.getRandom(); // return 1 +solution.getRandom(); // return 3 +solution.getRandom(); // return 2 +solution.getRandom(); // return 2 +solution.getRandom(); // return 3 +// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. ++ +
+
Constraints:
+ +[1, 104]
.-104 <= Node.val <= 104
104
calls will be made to getRandom
.+
Follow up:
+ +Given an array of distinct integers candidates
and a target integer target
, return a list of all unique combinations of candidates
where the chosen numbers sum to target
. You may return the combinations in any order.
The same number may be chosen from candidates
an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target
is less than 150
combinations for the given input.
+
Example 1:
+ +Input: candidates = [2,3,6,7], target = 7 +Output: [[2,2,3],[7]] +Explanation: +2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. +7 is a candidate, and 7 = 7. +These are the only two combinations. ++ +
Example 2:
+ +Input: candidates = [2,3,5], target = 8 +Output: [[2,2,2,2],[2,3,3],[3,5]] ++ +
Example 3:
+ +Input: candidates = [2], target = 1 +Output: [] ++ +
+
Constraints:
+ +1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidates
are distinct.1 <= target <= 500
Given an encoded string, return its decoded string.
+ +The encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times. Note that k
is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k
. For example, there will not be input like 3a
or 2[4]
.
The test cases are generated so that the length of the output will never exceed 105
.
+
Example 1:
+ +Input: s = "3[a]2[bc]" +Output: "aaabcbc" ++ +
Example 2:
+ +Input: s = "3[a2[c]]" +Output: "accaccacc" ++ +
Example 3:
+ +Input: s = "2[abc]3[cd]ef" +Output: "abcabccdcdcdef" ++ +
+
Constraints:
+ +1 <= s.length <= 30
s
consists of lowercase English letters, digits, and square brackets '[]'
.s
is guaranteed to be a valid input.s
are in the range [1, 300]
.Given a positive integer n
, you can apply one of the following operations:
n
is even, replace n
with n / 2
.n
is odd, replace n
with either n + 1
or n - 1
.Return the minimum number of operations needed for n
to become 1
.
+
Example 1:
+ +Input: n = 8 +Output: 3 +Explanation: 8 -> 4 -> 2 -> 1 ++ +
Example 2:
+ +Input: n = 7 +Output: 4 +Explanation: 7 -> 8 -> 4 -> 2 -> 1 +or 7 -> 6 -> 3 -> 2 -> 1 ++ +
Example 3:
+ +Input: n = 4 +Output: 2 ++ +
+
Constraints:
+ +1 <= n <= 231 - 1
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
+
Example 1:
+ +Input: nums = [-1,2,1,-4], target = 1 +Output: 2 +Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). ++ +
+
Constraints:
+ +3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
+ ++
Example 1:
+Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +
Example 2:
+Input: nums = [] +Output: [] +
Example 3:
+Input: nums = [0] +Output: [] ++
+
Constraints:
+ +0 <= nums.length <= 3000
-105 <= nums[i] <= 105
Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
+
Example 1:
+ +Input: nums1 = [1,3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1,2,3] and median is 2. ++ +
Example 2:
+ +Input: nums1 = [1,2], nums2 = [3,4] +Output: 2.50000 +Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. ++ +
+
Constraints:
+ +nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sum to target
.
Each number in candidates
may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
+ ++
Example 1:
+ +Input: candidates = [10,1,2,7,6,1,5], target = 8 +Output: +[ +[1,1,6], +[1,2,5], +[1,7], +[2,6] +] ++ +
Example 2:
+ +Input: candidates = [2,5,2,1,2], target = 5 +Output: +[ +[1,2,2], +[5] +] ++ +
+
Constraints:
+ +1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
Given string num representing a non-negative integer num
, and an integer k
, return the smallest possible integer after removing k
digits from num
.
+
Example 1:
+ +Input: num = "1432219", k = 3 +Output: "1219" +Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. ++ +
Example 2:
+ +Input: num = "10200", k = 1 +Output: "200" +Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. ++ +
Example 3:
+ +Input: num = "10", k = 2 +Output: "0" +Explanation: Remove all the digits from the number and it is left with nothing which is 0. ++ +
+
Constraints:
+ +1 <= k <= num.length <= 105
num
consists of only digits.num
does not have any leading zeros except for the zero itself.Given an array nums
which consists of non-negative integers and an integer m
, you can split the array into m
non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m
subarrays.
+
Example 1:
+ +Input: nums = [7,2,5,10,8], m = 2 +Output: 18 +Explanation: +There are four ways to split nums into two subarrays. +The best way is to split it into [7,2,5] and [10,8], +where the largest sum among the two subarrays is only 18. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5], m = 2 +Output: 9 ++ +
Example 3:
+ +Input: nums = [1,4,4], m = 3 +Output: 4 ++ +
+
Constraints:
+ +1 <= nums.length <= 1000
0 <= nums[i] <= 106
1 <= m <= min(50, nums.length)
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger
). You must also not convert the inputs to integers directly.
+
Example 1:
+ +Input: num1 = "11", num2 = "123" +Output: "134" ++ +
Example 2:
+ +Input: num1 = "456", num2 = "77" +Output: "533" ++ +
Example 3:
+ +Input: num1 = "0", num2 = "0" +Output: "0" ++ +
+
Constraints:
+ +1 <= num1.length, num2.length <= 104
num1
and num2
consist of only digits.num1
and num2
don't have any leading zeros except for the zero itself.Given a non-empty array nums
containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
+
Example 1:
+ +Input: nums = [1,5,11,5] +Output: true +Explanation: The array can be partitioned as [1, 5, 5] and [11]. ++ +
Example 2:
+ +Input: nums = [1,2,3,5] +Output: false +Explanation: The array cannot be partitioned into equal sum subsets. ++ +
+
Constraints:
+ +1 <= nums.length <= 200
1 <= nums[i] <= 100
Given two strings s
and p
, return an array of all the start indices of p
's anagrams in s
. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
Example 1:
+ +Input: s = "cbaebabacd", p = "abc" +Output: [0,6] +Explanation: +The substring with start index = 0 is "cba", which is an anagram of "abc". +The substring with start index = 6 is "bac", which is an anagram of "abc". ++ +
Example 2:
+ +Input: s = "abab", p = "ab" +Output: [0,1,2] +Explanation: +The substring with start index = 0 is "ab", which is an anagram of "ab". +The substring with start index = 1 is "ba", which is an anagram of "ab". +The substring with start index = 2 is "ab", which is an anagram of "ab". ++ +
+
Constraints:
+ +1 <= s.length, p.length <= 3 * 104
s
and p
consist of lowercase English letters.Given an integer array nums
of length n
where all the integers of nums
are in the range [1, n]
and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n)
time and uses only constant extra space.
+
Example 1:
+Input: nums = [4,3,2,7,8,2,3,1] +Output: [2,3] +
Example 2:
+Input: nums = [1,1,2] +Output: [1] +
Example 3:
+Input: nums = [1] +Output: [] ++
+
Constraints:
+ +n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
nums
appears once or twice.Given an array of non-negative integers nums
, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
+ +Your goal is to reach the last index in the minimum number of jumps.
+ +You can assume that you can always reach the last index.
+ ++
Example 1:
+ +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. ++ +
Example 2:
+ +Input: nums = [2,3,0,1,4] +Output: 2 ++ +
+
Constraints:
+ +1 <= nums.length <= 104
0 <= nums[i] <= 1000
Given four integer arrays nums1
, nums2
, nums3
, and nums4
all of length n
, return the number of tuples (i, j, k, l)
such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
+
Example 1:
+ +Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] +Output: 2 +Explanation: +The two tuples are: +1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 +2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 ++ +
Example 2:
+ +Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] +Output: 1 ++ +
+
Constraints:
+ +n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
There are buckets
buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest
minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
+ +minutesToDie
minutes. You may not feed any other pigs during this time.minutesToDie
minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.Given buckets
, minutesToDie
, and minutesToTest
, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
+
Example 1:
+Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60 +Output: 5 +
Example 2:
+Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 +Output: 2 +
Example 3:
+Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 +Output: 2 ++
+
Constraints:
+ +1 <= buckets <= 1000
1 <= minutesToDie <= minutesToTest <= 100
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
+
Example 1:
+Input: nums = [1,2,3] +Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] +
Example 2:
+Input: nums = [0,1] +Output: [[0,1],[1,0]] +
Example 3:
+Input: nums = [1] +Output: [[1]] ++
+
Constraints:
+ +1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums
are unique.