Sometimes is busy and want to skip a day, but I don’t want to break this continuous game. Let’s continue November LeetCoding Challenge.
Week 1: November 1st - November 7th
Meeting Rooms
Given an array of meeting time intervals
where intervals[i] = [starti, endi]
, determine if a person could attend all meetings.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
0 <= intervals.length <= 10^4
-
intervals.length == 2
-
0 <= starti < endi <= 10^6
Explanation
-
For most interval problems, first we sort all intervals by their start time.
-
The only case two intervals not overlapping is the second interval’s start time is greater than or equal to the first interval’s end time.
-
We can loop over all intervals and checking if the current interval’s start time is less than the previous interval’s end time, then they are overlap, so we return
false
immediately. Outside the loop, that means no interval overlap, so we return true.
Solution
1 |
|
Convert Binary Number in a Linked List to Integer
Given head
which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
The Linked List is not empty.
-
Number of nodes will not exceed
30
. -
Each node’s value is either
0
or1
.
Hint 1:
Traverse the linked list and store all values in a string or array. convert the values obtained to decimal value.
Hint 2:
You can solve the problem in O(1) memory using bits operation. use shift left operation ( « ) and or operation ( | ) to get the decimal value in one operation.
Explanation
- Initialize the result
res
equal to 0. Loop through all linked list elements. For each element, first we left shiftres <<= 1
, then add the current iterated elementres += cur.val
or using the OR operator to or the current iterated elementres |= cur.val
, then update the pointer to the next element.
Solution
1 |
|
Insertion Sort List
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
-
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
-
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
-
It repeats until no input elements remain.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
First create a dummy node, and we need to have a
cur
pointer points at the dummy node, andlstPtr
pointer points at the original list’s node for iterating. -
While
lstPtr
is not null, we starts fromlstPtr
’s node, compare it with everycur.next
’s node in the dummy list starts from the beginning of dummy list, here we also need a while loop to achieve this. Ifcur.next
is null, orcur.next
’s value is greater thanlstPtr
’s value, then we break out this inner while loop, and addlstPtr
’s node to our dummy list.
Solution
1 |
|
Consecutive Characters
Given a string s
, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
1 <= s.length <= 500
-
s
contains only lowercase English letters.
Hint 1:
Keep an array power where power[i] is the maximum power of the i-th character.
Hint 2:
The answer is max(power[i]).
Explanation
-
We can use brute force one iteration to solve this problem.
-
Initially we define the current character
curChar = s[0]
, current countcnt = 1
, and the result isres = 1
. Start looping from the second character to the last character. For each characters[i]
, we compare it withcurChar
. If they are equal, then we just increase the countcnt
. Else, we update theres = max(res, cnt)
, and resetcurChar = s[i]
and reset the countcnt = 1
. -
One edge case is all characters are the same. For example,
s = "cc"
, after the loop, we need to update theres = max(res, cnt)
.
Solution
1 |
|
Minimum Height Trees
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of n
nodes labelled from 0
to n - 1
, and an array of n - 1
edges
where edges[i] = [ai, bi]
indicates that there is an undirected edge between the two nodes ai
and bi
in the tree, you can choose any node of the tree as the root. When you select a node x
as the root, the result tree has height h
. Among all possible rooted trees, those with minimum height (i.e. min(h)
) are called minimum height trees (MHTs).
Return a list of all MHTs’ root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Constraints:
-
1 <= n <= 2 * 10^4
-
edges.length == n - 1
-
0 <= ai, bi < n
-
ai != bi
-
All the pairs
(ai, bi)
are distinct. -
The given input is guaranteed to be a tree and there will be no repeated edges.
Hint 1:
How many MHTs can a graph have at most?
Explanation
-
We can use topological sort to solve this problem. First, we need to create an adjancent list based on the
edges[][]
. Then, loop through the adjacent list and update nodei
’s in degree ininDegree[]
. Then, we add all leaves node (which has only one adjancent node or in degree is 1) to the queue. -
We know that if there is one node, then we can return that node as the result. If there are two nodes, then we can return both nodes as the result. If there are three nodes, we will remove two leaves node, and now we only has one node, and that one node is the result.
-
The queue will contain all leaves nodes. After we add all leaves nodes to the queue, while
n > 2
, we want to delete all leaves node, so we updatedn
to be subtracted the size of the queue. Then poll all the leaves nodes from the queue, iterate these leaves nodes’ neighbors, subtract these neighbor’s indegree by 1. Repeat the above process. Whenn <= 2
, the remain one or two nodes in the queue will be the final result.
Solution
1 |
|
Minimum Cost to Move Chips to The Same Position
We have n
chips, where the position of the ith
chip is position[i]
.
We need to move all the chips to the same position. In one step, we can change the position of the ith
chip from position[i]
to:
-
position[i] + 2
orposition[i] - 2
withcost = 0
. -
position[i] + 1
orposition[i] - 1
withcost = 1
.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
1 |
|
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= position.length <= 100
-
1 <= position[i] <= 10^9
Hint 1:
The first move keeps the parity of the element as it is.
Hint 2:
The second move changes the parity of the element.
Hint 3:
Since the first move is free, if all the numbers have the same parity, the answer would be zero.
Hint 4:
Find the minimum cost to make all the numbers have the same parity.
Explanation
- We can think that first moving all even chips to position 0 and all odd chips to position 1, so this cost is 0. Then we have two piles on position 0 and position 1. Now, the result is the minimum between these two piles.
Solution
1 |
|
Find the Smallest Divisor Given a Threshold
Given an array of integers nums
and an integer threshold
, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold
.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= nums.length <= 5 * 10^4
-
1 <= nums[i] <= 10^6
-
nums.length <= threshold <= 10^6
Hint 1:
Examine every possible number for solution. Choose the largest of them.
Hint 2:
Use binary search to reduce the time complexity.
Explanation
-
Brute force approach would be to try all the possible divisors from 1 to
max(nums)
. -
We can optimize it using binary search method to find the smallest divisor such that the result mentioned above is less than or equal to
threshold
.
Solution
1 |
|
Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
1 |
|
Explanation
- We can use two stacks to store two iterated node’s value respectivly. Also, we create a ListNode
res
to have value 0 initialy. Since stack is Last In First Out, while either of the stack is not empty, we can use a variablesum
to sum the pop value. And updateres.value = sum / 10
. Then, we create a new ListNodehead
to default have valuesum / 10
, then makehead.next = res
, then update theres
pointer to point to thehead
, and updatesum = sum / 10
. When outside of the loop, ifres
has value 0, then we returnhead.next
, else just returnres
.
Solution
1 |
|
Week 2: November 8th - November 14th
Two Sum Less Than K
Given an array A
of integers and integer K
, return the maximum S
such that there exists i < j
with A[i] + A[j] = S
and S < K
. If no i, j
exist satisfying this equation, return -1
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= A.length <= 100
-
1 <= A[i] <= 1000
-
1 <= K <= 2000
Hint 1:
What if we have the array sorted?
Hint 2:
Loop the array and get the value A[i] then we need to find a value A[j] such that A[i] + A[j] < K which means A[j] < K - A[i]. In order to do that we can find that value with a binary search.
Explanation
-
Similar to 167. Two Sum II - Input array is sorted, we can use two pointers approach to solve this problem.
-
First, sort the array. Then create a pointer
left
points to index 0, another pointerright
points to the last index. -
While
left < right
, we calculate thesum = A[left] + A[right]
. Ifsum
is less thanK
, then we update theres
and increaseleft
pointer. Else we decreaseright
pointer.
Solution
1 |
|
Binary Tree Tilt
Given the root
of a binary tree, return the sum of every tree node’s tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0
. The rule is similar if there the node does not have a right child.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
The number of nodes in the tree is in the range
[0, 10^4]
. -
-1000 <= Node.val <= 1000
Hint 1:
Don’t think too much, this is an easy problem. Take some small tree as an example.
Hint 2:
Can a parent node use the values of its child nodes? How will you implement it?
Hint 3:
May be recursion and tree traversal can help you in implementing.
Hint 4:
What about postorder traversal, using values of left and right childs?
Explanation
-
We can also use post-order traversal to solve this problem. In order to find the root node’s tilt, we need to know the left subtree’s sum and the right subtree’s sum. In the method of
getSum
, if we use post-order traversal to find the sum of the tree, we also calculate the left subtree’s sum and right subtree’s sum first then plus the root value. So, in thegetSum
method, after we find out the left subtree and right subtree’s sum and before return the sum, we can calculate the tilt for the root since the root node’s tilt is depends on the left subtree’s sum and right subtree’s sum. -
Using post-order traversal, every node will be a root, in other words, we are iterating every node. We will create a reference pointing to variable
res
to accumulate every node’s tilt.
Solution
1 |
|
Maximum Difference Between Node and Ancestor
Given the root
of a binary tree, find the maximum value V
for which there exist different nodes A
and B
where V = |A.val - B.val|
and A
is an ancestor of B
.
A node A
is an ancestor of B
if either: any child of A
is equal to B
, or any child of A
is an ancestor of B
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
The number of nodes in the tree is in the range
[2, 5000]
. -
0 <= Node.val <= 10^5
Hint 1:
For each subtree, find the minimum value and maximum value of its descendants.
Explanation
-
For each node, we need the minimum and maximum values from the ancestor. So we can use pre-order traversal to pass down the minimum value and maximum value to the current node’s left child and right child.
-
Create a helper function which accept the current node, minimum and maximum values and they both initially set to current node’s value. Inside the helper function, we can use the current node’s value to compare with minimum value and maximum value to get the maximum absolute difference and update the result. Then we update the minimum value and maximum value that compares with the current node’s value. Next, recursively pass down the updated minimum and maximum values to left child and right child. At the end, return the maximum result.
Solution
1 |
|
Flipping an Image
Given a binary matrix A
, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0]
horizontally results in [0, 1, 1]
.
To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
. For example, inverting [0, 1, 1]
results in [1, 0, 0]
.
Example 1:
1 |
|
Example 2:
1 |
|
Notes:
-
1 <= A.length = A[0].length <= 20
-
0 <= A[i][j] <= 1
Explanation
-
We can use brute force to solve this problem.
-
If the current row is
[0, 1, 0]
. Letleft
points to the beginning of index 0 andright
points to the end of index 2. After flipping,A[left] = A[right] = 0
stays the same. Then after inverting, we getA[left] = A[right] = 1
. Therefore, ifA[left] = A[right]
, after flipping and inverting,A[left]
andA[right]
change from 0 to 1, or 1 to 0. -
If the current row is
[1, 0]
. Letleft
points to the beginning of index 0 andright
points to the end of index 1. After flipping, we get[0, 1]
, then after inverting, we get[1, 0]
which is the same as the original array. Therefore, ifA[left]
andA[right]
are different, then after flipping and inverting, they stay the same.
Solution
1 |
|
Valid Square
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
1 |
|
Note:
-
All the input integers are in the range [-10000, 10000].
-
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
-
Input points have no order.
Explanation
- We cannot just find if two points have the same x-axis or y-axis, we also need to think about all 4 lengths will be equal. So, we can iterate every two points and find their distance and store the distance into the set. If the set have element 0, that means there are two points on the same position so we return false. Or if the set does not cantains 2 elemnts, we also return false because in a square 1 distance is the square length, another distance will be the diagonal length.
Solution
1 |
|
Permutations II
Given a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= nums.length <= 8
-
-10 <= nums[i] <= 10
Explanation
-
Similar to 46. Permutations, but this time there are duplicated numbers in the input list, and we don’t want the result list have duplicated sublist.
-
First, we can sort the input list. We still need a temp list for storing the sublist, and a visited array to check whether the element have been visited or not. Inside the helper method, the base case is if the temp list has length equals to the input array, then we add the temp list as sublist into the result list, and return.
-
To remove duplicated elements, under the for loop, we can check if
i > 0 && nums[i] == nums[i-1] && visited[i-1] == false
, then we ignore the currentnums[i]
. From the above example, we want the first 1, second 1, and 2; in this case, when we iterate to the second 1, it satisifyi > 0 && nums[i] == nums[i-1]
, and nowvisited[i-1] = visited[0] = true
. We don’t want the second 1, first 1, and 2; in this case, when we iterate to the second 1, it satisifyi > 0 && nums[i] == nums[i-1]
andvisited[i-1] = visited[0] = false
.
Solution
1 |
|
Populating Next Right Pointers in Each Node
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:
1 |
|
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
.
Follow up:
-
You may only use constant extra space.
-
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
1 |
|
Constraints:
-
The number of nodes in the given tree is less than
4096
. -
-1000 <= node.val <= 1000
Explanation 1
- We can use recursion method here. Since this is a perfect binary tree, if the root node has left node, then it must has right node, so we can check if it has left node first, then connect it with its right node. To connect the right node’s next node, we first check its parent node has next node, if it has, then we can connect the right node’s next to its parent node’s left node.
Solution 1
1 |
|
Explanation 2
- We can use a O(1) space iterative method to solve this problem. We create a
start
pointer that points to the current level’s beginning, acur
pointer that is used to iterate the current level’s node.
Solution 2
1 |
|
Poor Pigs
There are 1000 buckets, one and only one of them is poisonous, while the rest are filled with water. They all look identical. If a pig drinks the poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour?
Answer this question, and write an algorithm for the general case.
General case:
If there are n
buckets and a pig drinking poison will die within m
minutes, how many pigs (x
) you need to figure out the poisonous bucket within p
minutes? There is exactly one bucket with poison.
Note:
-
A pig can be allowed to drink simultaneously on as many buckets as one would like, and the feeding takes no time.
-
After a pig has instantly finished drinking buckets, there has to be a cool down time of m minutes. During this time, only observation is allowed and no feedings at all.
-
Any given bucket can be sampled an infinite number of times (by an unlimited number of pigs).
Hint 1:
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test.
Hint 2:
How many states can we generate with x pigs and T tests?
Hint 3:
Find minimum x
such that (T+1)^x >= N
Explanation
-
For example, if we only have 1 pig, and 15 minutes, how many buckets can we test? The answer is 2 because we let the pig drinks any 1 of the 2 bucket, if it die, then that bucket is poisonous. If it doesn’t die, then another bucket is poisonous.
-
Now if we have 2 pigs and 15 minutes, how many buckets can we test? The answer is 4 because pig1 drinks bucketA, pig2 drinks bucketB, then both pigs drink bucketC. If one pig1 is dead, that means bucketA is poisonous. If pig2 is dead, that means bucketB is poisonous. If both pigs dead, that means bucktC is poisonous. If both pig not dead, that means bucketD is poisonous. Similarlly, 3 pigs and 15 minutes can test 8 buckets, which is 2^3=8.
-
If we only have 15 minutes, that means we can only test one time, it’s a one dimensional array. If we have 2 pigs and 30 minutes, that means we can test two times, it’s a two dimensional array. The buckets we can test is 9. For example:
1
2
3
4
51 2 3 4 5 6 7 8 9
First, we let pig1 drink bucket 1, 2, 3, and pig2 drink bucket 1, 4, 7. After 15 minutes, we let pig1 drink bucket 4, 5, 6, and pig2 drink bucket 2, 5, 8. At the end, if both pig not dead, that means bucket9 is poisonous. If within the first 15minutes, pig1 dead after drinking bucket 1, 2, 3, and pig2 also dead within the first 15minutes. That means bucket1 is poisonous. If within the first 15minutes, pig1 dead, but pig2 not dead, then pig2 drink bucket 2, 5, 8. Now if pig2 also dead, that means bucket2 is poinsonous. The total bucket is
3^2=9
. -
If we have 3 pigs, that means it’s a 3 dimensional array, also within 30 minutes, test 2 times, then the buckets we can test becomes
3^3=27
. -
This problem ask us to calculate the minimun number of pigs to test
n
buckets, so we need to make the dimensional as small as possible, in other words, the row and column be as big as possible. The number of row and column can be calculated as the number of times we can test plus 1. We can calculate the number of times we can test byminutesToTest / minutesToDie
. So, the number of row and columnm
is equal tominutesToTest / minutesToDie + 1
. If we havex
pigs, then the total bucket is equals tot=m^x
. We can calculatex = log(t)/log(m)
.
Solution
1 |
|
Week 3: November 15th - November 21st
Remove Interval
Given a sorted list of disjoint intervals
, each interval intervals[i] = [a, b]
represents the set of real numbers x
such that a <= x < b
.
We remove the intersections between any interval
in intervals and the interval toBeRemoved
.
Return a sorted list of intervals
after all such removals.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= intervals.length <= 10^4
-
-10^9 <= intervals[i][0] < intervals[i][1] <= 10^9
Hint 1:
Solve the problem for every interval alone.
Hint 2:
Divide the problem into cases according to the position of the two intervals.
Explanation
-
We can consider different cases and solve this problem in one loop.
-
Case 1 if
removeStart <= curStart && curEnd <= removeEnd
, then we don’t add any interval.1
2curStart----------curEnd removeStart-------------------------------------removeEnd
-
Case 2 else if
curStart <= removeStart && removeEnd <= curEnd
, then we add two intervals[curStart, removeStart]
and[removeEnd, curEnd]
.1
2curStart-------------------------------------curEnd removeStart----------removeEnd
-
Case 3 else if
curEnd <= removeStart
, then we add an interval[curStart, curEnd]
1
2curStart---------------curEnd removeStart-------removeEnd
-
Case 4 else if
curStart >= removeEnd
, then we add an interval[curStart, curEnd]
1
2curStart---------------curEnd removeStart-------removeEnd
-
Case 5 else if
curStart <= removeStart && curEnd <= removeEnd
, then we add an interval[curStart, removeStart]
.1
2curStart-------------------------curEnd removeStart--------------------------removeEnd
-
Case 6 else if
curStart <= removeend && curEnd >= removeEnd
, then we add an interval[removeEnd, curEnd]
.1
2curStart---------------------------curEnd removeStart------------------------removeEnd
Solution
1 |
|
Range Sum of BST
Given the root
node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high]
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
The number of nodes in the tree is in the range
[1, 2 * 104]
. -
1 <= Node.val <= 10^5
-
1 <= low <= high <= 10^5
-
All
Node.val
are unique.
Explanation
-
First we think of some base cases. If root node is NULL, we return 0. If root node value is not in the range, then it’s either less than
low
or greater thanhigh
. -
If root node value is less than
low
, then we can ignore the root node and its left subtree, so we recursively call the main function withroot.Right
as the new root. Else if root node value is greater thanhigh
, then we can ignore the root node and its right subtree, so we recursively call the main function withroot.Left
as the new root. Else that means root node value is in the range, so we return the sum ofroot.Val
and the results for both recursive functions with the left child node and recursive function with the right child node as the new root.
Solution
1 |
|
Longest Mountain in Array
You may recall that an array arr
is a mountain array if and only if:
-
arr.length >= 3
-
There exists some index
i
(0-indexed) with0 < i < arr.length - 1
such that:-
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
-
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
-
Given an integer array arr
, return the length of the longest subarray, which is a mountain. Return 0
if there is no mountain subarray.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= arr.length <= 10^4
-
0 <= arr[i] <= 10^4
Follow up:
-
Can you solve it using only one pass?
-
Can you solve it in
O(1)
space?
Explanation 1
-
To find a length of the mountain, we need to find a peek point such that number of increasing elements end at the peek point, and number of decreasing elements start from the peek point.
-
We can create two dp arrays. One is
up[i]
which represents number of increasing elements end at indexi
. Another one isdown[i]
which represents number of decreasing elements start from indexi
. We can use 1 loop to fill theup
array, and 1 loop to fill thedown
array. -
The result will be the maximum of
up[i] + down[i] + 1
.
Solution 1
1 |
|
Explanation 2
-
We can save space by using a variable
up
to represent the number of increasing elements for the current mountain, and a variabledown
to represent the number of decreasing elements for the current mountain. We only update the result when bothup
anddown
are greater than 0, in other word,res = max(res, up + down + 1)
. -
How do we reset
up
anddown
for a new mountain? Each iteration, we first check ifdown > 0 && A[i-1] < A[i]
orA[i-1] == A[i]
, then we reset bothup
anddown
to 0.
Solution 2
1 |
|
Mirror Reflection
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0
, 1
, and 2
.
The square room has walls of length p
, and a laser ray from the southwest corner first meets the east wall at a distance q
from the 0
th receptor.
Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)
Example 1:
1 |
|
Note:
-
1 <= p <= 1000
-
0 <= q <= p
Explanation
-
This is a brain teaser or math problem.
-
If
p
is odd number andq
is odd number, then the answer is 1. -
If
p
is odd number andq
is even number, then the answer is 0. -
If
p
is even number andq
is odd number, then the answer is 2. -
There won’t be a case that
p
andq
are both even number. For example, ifp = 4
andq = 2
, then it is the same asp = 2
andq = 1
.
Source: https://www.cnblogs.com/grandyang/p/10646040.html
Solution
1 |
|
Merge Intervals
Given an array of intervals
where intervals[i] = [starti, endi]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= intervals.length <= 10^4
-
intervals[i].length == 2
-
0 <= starti <= endi <= 10^4
Explanation
-
First, sort the interval by their start time.
-
To form an interval, we need a
start
andend
. Initially, we initializestart
is the first interval’s start time,end
is the first interval’s end time. -
Loop from the second interval to the end, if the iterated interval’s start time is greater than
end
, we know they are disjoint. So we add an interval{start, end}
to the result list. Then we updatestart
be the iterated interval’s start time,end
be the interval’s end time. In the next iteration, if the iterated interva’s start time is less thanend
, we only need to updateend
be the maximum of(end, intervals[i][1])
, we don’t need to updatestart
because we already sortedstart
from small to large, and we only need the minimum start and maximum end.
Solution
1 |
|
Decode String
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; 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 won’t be input like 3a
or 2[4]
.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Constraints:
-
1 <= s.length <= 30
-
s
consists of lowercase English letters, digits, and square brackets'[]'
. -
s
is guaranteed to be a valid input. -
All the integers in
s
are in the range[1, 300]
.
Explanation
-
We can also solve it using iteration method. First, we create two stacks.
numSt
andstrSt
, and a repeat countercnt
. -
Then we iterate the string, if the current character is digit, then we update the counter
repeat
. Else if the current character is not digit and not[
or]
, then we add the letter into the resultres
. If current character is[
, then we push the counter intonumSt
, pushres
intostrSt
, and we resetcnt=0
and clear the stringres
. Else if current character is]
, then we pop thenumSt
to get the counterrepeat
, and iteraterepeat
times addingres
to the top of thestrSt
. After that, we pop out thestrSt
and set it tores
.
Solution
1 |
|
Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
1 |
|
Example 2:
1 |
|
Follow up:
-
This is a follow up problem to Search in Rotated Sorted Array, where
nums
may contain duplicates. -
Would this affect the run-time complexity? How and why?
Explanation
- Similar to 33. Search in Rotated Sorted Array, now, we also need to consider the case that
nums[mid] == nums[left] == num[right]
. In this case, we can moveleft
one step forward, so themid
will also move forward, until!(nums[mid] == nums[left] == num[right])
, and now it is the same as 33. Search in Rotated Sorted Array.
Solution
1 |
|
Numbers At Most N Given Digit Set
Given an array of digits
which is sorted in non-decreasing order. You can write numbers using each digits[i]
as many times as we want. For example, if digits = ['1','3','5']
, we may write numbers such as '13'
, '551'
, and '1351315'
.
Return the number of positive integers that can be generated that are less than or equal to a given integer n
.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= digits.length <= 9
-
digits[i].length == 1
-
digits[i]
is a digit from'1'
to'9'
. -
All the values in
digits
are unique. -
digits
is sorted in non-decreasing order. -
1 <= n <= 10^9
Explanation
-
If
n
has 2 digit, then all one digit fromdigits[]
are valid, in other words,res += digits.length
. Ifn
has 3 digit, then all two digit fromdigits[]
are also valid, in other words,res += digits.length ^ 2
. Therefore, ifn
hasnLen
digit, then we can generate all numbers that are1
tonLen - 1
digits fromdigits[]
are valid. -
Now, we need to consider the case that generate all numbers that are
nLen
digits and less than or equal ton
. -
For example, if
digits = ["1", "3", "9"]
andn = 537
. First, we compare withn
’s first digit5
. Fromdigits[]
,1
is less than5
, so we can generate all numbers that start from1
, in other words,res += (nLen - 1 - 0) ^ 2
(ignore the 0 now). Then we check3
is also less than5
, so we can generate all numbers that start from3
, in other words,res += (nLen - 1 - 0)^2
. Then we check9
, which is greater than5
, so we ignore. In this example, we can generate allnLen
digit numbers that start from 1 and 3. -
One more case is if
digits = ["1", "3", "9"]
andn = 345
. First, we compare withn
’s first digit3
. Fromdigits[]
,1
is less than3
, so we can generate all numbers that start from 1. Then we compare3
fromdigits[]
withn
’s first digit3
. They are equal, that means we can generate some numbers that start from3
. So now we compare withn
’s second digit4
. Fromdigits[]
,1
is less than 4, so we can generate all numbers that start from 31, in other words,res += (nLen - 1 - 1)^2
. Then we compare3
fromdigits[]
with4
.3
is less than 4, so we can generate all numbers that start from 33, in other words,res += (nLen - 1 - 1) ^ 2
. Then we compare9
fromdigits[]
with4
,9
is greater than 4, so we ignore. At the end, we can generate allnLen
digits number that are start from1
, start from31
, and start from33
. -
One corner case is if
digits = ["1", "1", "1"]
andn = 111
, then we can only generate one number that arenLen
whch is 111 and its less than or equal ton
.
Solution
1 |
|
Week 4: November 22nd - November 28th
Longest Substring with At Most Two Distinct Characters
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation 1
- First, we can create a HashMap, and use it to store the key is the character, the value is the frequency of the character. Also, we initialize the
left
be 0. Iterate the input string and update the hashmap. While the hashmap has size greater than 2, then we need to decrease the frequency of characters[left]
and increase left by 1. Also if thes[left]
’s frequency is 0, we remove the keys[left]
from the hashmap. Repeat these steps until the hashmap has size less than or equal to 2. Next, we update the result bemax(res, i-left+1)
.
Solution 1
1 |
|
Explanation 2
-
We can optimize the last solution by not using HashMap. First, we create two variables
first
means the first distince character,second
means the second distince character. Also, we initializecurLen
means the current 2 distinct character substring’s length, andcntSecond
means the number of consecutive second characters. -
Iterate the input string’s characters. If the current character is the same as either character
first
or charactersecond
, we updatecurLen = curLen + 1
, else, we updatecurLen = cntSecond + 1
. -
Then, we try to update
cntSecond
. If the current character is the same as charactersecond
, thencntSecond = cntSecond + 1
, elsecntSecond = 1
. -
Next, we try to update
first
andsecond
. If the current character is not the same assecond
, then we updatefirst
be the originalsecond
andsecond
be the current character. -
Next, we update the result
res = max(res, curLen)
.
Solution 2
1 |
|
Unique Morse Code Words
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a"
maps to ".-"
, "b"
maps to "-..."
, "c"
maps to "-.-."
, and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
1 |
|
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, “cab” can be written as “-.-..–…”, (which is the concatenation “-.-.” + “.-“ + “-...
”). We’ll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
1 |
|
Note:
-
The length of
words
will be at most100
. -
Each
words[i]
will have length in range[1, 12]
. -
words[i]
will only consist of lowercase letters.
Explanation
-
We can use brute force to solve this problem.
-
First, we find all words’ morse code, then put them into a set. At the end, we can return the size of the set.
Solution
1 |
|
House Robber III
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
For Tree problem, we usually use recursive method to solve. The thief can have only two options.
-
Get the root val, don’t get
root.left.val
androot.right.val
, but getroot.left.left.val
,root.left.right.val
, androot.right.left.val
,root.right.right.val
. -
Don’t get the root val, but get
root.left.val
androot.right.val
.
-
-
The base case is if
root
is NULL, we return 0. -
We can use a HashMap
hm<TreeNode, Integer>
to store the maximum the thieft can get onroot
. Think of the tree is made by manyroot
.
Solution
1 |
|
Basic Calculator II
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= s.length <= 3 * 10^5
-
s
consists of integers and operators('+', '-', '*', '/')
separated by some number of spaces. -
s
represents a valid expression.
All the integers in the expression are non-negative integers in the range [0, 2^31 - 1]
.
The answer is guaranteed to fit in a 32-bit integer.
Explanation
-
Before we begin, we need to have a
preSign
initialize to+
, a stack to hold the sub result. -
Iterate the string, if the current character is a number, then we update the number be
num = num*10+c
. If the current character is not a number, then check if thepreSign
is plus, we push thenum
to stack; if thepreSign
is minus, then we push-num
to stack; if thepreSign
is multiple, then we pop the stack’s number and multiple tonum
and store this sub result back to stack; if thepreSign
is divide, it’s similar to multiple, but divide thenum
and push back to stack. Also remember to update thepreSign
equal to current character, and resetnum
to 0. -
Sum all sub result from stack and return it as result.
Solution
1 |
|
Smallest Integer Divisible by K
Given a positive integer K
, you need to find the length of the smallest positive integer N
such that N
is divisible by K
, and N
only contains the digit 1
.
Return the length of N
. If there is no such N
, return -1.
Note: N
may not fit in a 64-bit signed integer.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
1 <= K <= 10^5
Hint 1:
11111 = 1111 * 10 + 1 We only need to store remainders modulo K.
Hint 2:
If we never get a remainder of 0, why would that happen, and how would we know that?
Explanation
- This is a math problem and there is a formula to solve this problem.
Solution
1 |
|
Longest Substring with At Least K Repeating Characters
Given a string s
and an integer k
, return the length of the longest substring of s
such that the frequency of each character in this substring is greater than or equal to k
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= s.length <= 10^4
-
s
consists of only lowercase English letters. -
1 <= k <= 10^5
Explanation
-
We can use DFS to solve this problem. First, we get the frequency of characters into a HashMap
freq
. Also, we loop through thefreq
’s key set, if the current character’s frequency is less thank
, then we store the current character into a setsplitSet
. The base case is if thesplitSet
is empty, that means all characters in the input string have frequency equals or greater thank
, so the maximum length will be the full length ofs
. -
Next, we create two variables
start
andcur
both initialize to 0. We loop through the string withcur
, ifs[cur]
is not in thesplitSet
, then we continue for the next iteration. Else ifs[cur]
is in thesplitSet
, that meanss[cur]
cannot be stored into the result, so we recursivly check the result length with substrings[start, cur]
, and compare the returned result length with variablemax
that keeps the maximum result length. Then, we updatestart = cur + 1
sincecur
is pointing to the character that cannot be put into the result string. -
When outside the loop, if
start
andcur
not equals, we need to pass the last substrings[start, len(s)]
to the recursive method and compare its result withmax
. At the end, we returnmax
.
Solution
1 |
|
Partition Equal Subset Sum
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:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= nums.length <= 200
-
1 <= nums[i] <= 100
Explanation
-
Since we want two subsets have the same sum, so the input array’s total sum must be an even number, and both subset must have the target sum equals to
totalSum/2
. -
We can use dynamic programming to solve this problem. Dynamic state is
boolean dp[i]
andi
is between 0 to target inclusive. Ifdp[i]
is true, that means we can choose some numbers from the input array and sum toi
. -
Dynamic init is
dp[0] = true
. -
Dynamic function. For each number in the array, we loop
i
fromtarget
to that number,dp[i]
will be true ifdp[i - num]
is true. For example, if array is[1, 5, 11, 5]
, when we iterate tonum = 5
.dp[i = 6]
will be true becausedp[6-5] = dp[1] = true
, anddp[i = 5]
will be true becausedp[5 - 5] = dp[0] = true
. Also, ifdp[i]
is already true, we keep it as true. Therefore, we havedp[i] = dp[i] || dp[i - num]
. -
Dynamic result is return
dp[target]
.
Solution
1 |
|
Sliding Window Maximum
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:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
1 <= nums.length <= 10^5
-
-10^4 <= nums[i] <= 10^4
-
1 <= k <= nums.length
Hint 1:
How about using a data structure such as deque (double-ended queue)?
Hint 2:
The queue size need not be the same as the window’s size.
Hint 3:
Remove redundant elements and the queue should store only elements that need to be considered.
Explanation
-
We can use a deque to store the index of element, and the deque is sorted from highest to lowest.
-
Iterate the array, if the queue is empty, then we insert the current index to the deque. Else, while the number value on the current index is greater than the tail value of the deque, we pop it. Outside of the while loop, we insert the current index to the deque. So, the deque is sorted descendent.
-
If the current index is greater than or equal to
k-1
, then a window is created, and we add the valuenum[head of the deque]
to the result array. -
If the head of the deque is equal to
currentIndex - k
, that means the head index is outside of the window, so we remove the head.
Solution
1 |
|
Week 5: November 29th - November 30th
Maximum Average Subarray II
You are given an integer array nums
consisting of n
elements, and an integer k
.
Find a contiguous subarray whose length is greater than or equal to k
that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5
will be accepted.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
n == nums.length
-
1 <= k <= n <= 10^4
-
-10^4 <= nums[i] <= 10^4
Explanation 1
-
We can use brute force to solve this problem, but it will TLE.
-
Loop
i
from the beginning of the array ton-k
inclusive, andi
represent the starting index of the subarray that has length at leastk
. Inside the loop, we try to extend the subarray, so we create an inner loop that loopj
fromi
to the last index of the array, andj
represent the ending index of the subarray. Inside this inner loop, we check if the length of the subarray has size equal or greater thank
, then we calculate its average and update the result to get the maximum of the average.
Solution 1
1 |
|
Explanation 2
-
We can use binary search to solve this problem.
-
First, we know that the value of the average could lie between the range (min,max). Here, min and max refer to the minimum and the maximum values out of the given nums array. This is because, the average can’t be lesser than the minimum value and can’t be larger than the maximum value.
-
We will use the
mid
as our guessing result. -
Suppose, there exist j elements, a1,a2,a3…,aj in a subarray within nums such that their average is greater than mid. In this case, we can say that
-
(a_1+a_2+ a_3…+a_j)/j ≥ mid or
-
(a_1+a_2+ a_3…+a_j) ≥ j*mid or
-
(a_1-mid) +(a_2-mid)+ (a_3-mid) …+(a_j-mid) ≥ 0
-
-
The
check
function will return true if there’s a subarray that has length at leastk
and its average is equal or greater thanmid
.
Solution 2
1 |
|
Jump Game III
Given an array of non-negative integers arr
, you are initially positioned at start
index of the array. When you are at index i
, you can jump to i + arr[i]
or i - arr[i]
, check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= arr.length <= 5 * 10^4
-
0 <= arr[i] < arr.length
-
0 <= start < arr.length
Hint 1:
Think of BFS to solve the problem.
Hint 2:
When you reach a position with a value = 0 then return true.
Explanation
- Start from index
start
, we first check ifarr[start]
equals to 0, if it is, then we return true immediately. Else, we checkarr[start - arr[start]]
andarr[start + arr[start]]
. We can use BFS to check all possible routes. If an index is already checked, we do not need to check it again, we can achieve this by marking the visited index’s value as negativearr[curIdx] = -1
.
Solution
1 |
|
The Skyline Problem
A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.
The geometric information of each building is given in the array buildings
where buildings[i] = [lefti, righti, heighti]
:
-
left_i
is the x coordinate of the left edge of the ith building. -
right_i
is the x coordinate of the right edge of the ith building. -
height_i
is the height of the ith building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0
.
The skyline should be represented as a list of “key points” sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]
. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0
and is used to mark the skyline’s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline’s contour.
Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...]
is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= buildings.length <= 10^4
-
0 <= lefti < righti <= 2^31 - 1
-
1 <= height_i <= 2^31 - 1
-
buildings
is sorted byleft_i
in non-decreasing order.
Explanation
-
First, store every column edge
int[x, y]
into a listheight
which is sorted by the edge’sx
position, if two edge has the samex
position, then higher edge, in other words, highery
in front. Note, a rectangle’s start column edge will be both positivex
andy
, ending edge will be positivex
but negative heighty
. In other words,<start, height>
and<end, -height>
. -
We also need a priority queue to store the integer height, and the queue is sorted by higher height in front. Also, the queue will be inserted a
0
first, and we need acur
andpre
to record the pop height from the queue later. -
Iterate the list
height<int[]>
, if the edge’s y position is positive, then we enqueue the y; else, remove the negative y from the queue, in other words, remove the begin edge’s y from the queue. Then, we update thecur
height be the peek of the queue, and check ifcur
is different frompre
, then we get the skinline key point as the iterative edge’s x position as the key point’s x position, key point’s y position will becur
which is the peek height of the queue. After we insert the keypoint to the result list, we update thepre
equal tocur
.
Solution
1 |
|