Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Follow up: Can you solve it with time complexity O(height of tree)
?
Example 1:
1 | Input: root = [5,3,6,2,4,null,7], key = 3 |
Example 2:
1 | Input: root = [5,3,6,2,4,null,7], key = 0 |
Example 3:
1 | Input: root = [], key = 0 |
Constraints:
[0, 10^4]
.-10^5 <= Node.val <= 10^5
-10^5 <= key <= 10^5
下面的做法是查找右子树的最小值节点的方法,最小节点就是右子树中的最靠左边的节点。代码使用的递归,最核心的是找到该节点之后的操作,特别是把值进行交换一步很重要,因为我们并没有删除了该最小值节点,所以把最小值的节点赋值成要查找的节点,然后在之后的操作中将会把它删除。
1 | # Definition for a binary tree node. |
Given a non-empty array of unique positive integers A
, consider the following graph:
A.length
nodes, labelled A[0]
to A[A.length - 1]
;A[i]
and A[j]
if and only if A[i]
and A[j]
share a common factor greater than 1.Return the size of the largest connected component in the graph.
Example 1:
1 | Input: [4,6,15,35] |
Example 2:
1 | Input: [20,50,9,63] |
Example 3:
1 | Input: [2,3,6,7,4,12,21,39] |
Note:
1 <= A.length <= 20000
1 <= A[i] <= 100000
For each number, union itself with all its factors.
E.g. 6, union(6,2), union(6,3)
Time complexity: $𝑂(Σ𝑠𝑞𝑟𝑡(𝐴[𝑖]))$
Space complexity: $𝑂(𝑚𝑎𝑥(𝐴))$
1 | class Solution: |
Given an array of integers arr
, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
k
where 1 <= k <= arr.length
.arr[1...k]
.For example, if arr = [3,2,1,4]
and we performed a pancake flip choosing k = 3
, we reverse the sub-array [3,2,1]
, so arr = [1,2,3,4]
after the pancake flip at k = 3
.
Return the k
-values corresponding to a sequence of pancake flips that sort arr
. Any valid answer that sorts the array within 10 * arr.length
flips will be judged as correct.
Example 1:
1 | Input: arr = [3,2,4,1] |
Example 2:
1 | Input: arr = [1,2,3] |
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= arr.length
arr
are unique (i.e. arr
is a permutation of the integers from 1
to arr.length
).煎饼排序: 每次找最大的煎饼,先翻到第一个位置,再翻到最后一个位置,经过2n次,可以得到结果。
1 | class Solution: |
Given the API rand7()
that generates a uniform random integer in the range [1, 7]
, write a function rand10()
that generates a uniform random integer in the range [1, 10]
. You can only call the API rand7()
, and you shouldn’t call any other API. Please do not use a language’s built-in random API.
Each test case will have one internal argument n
, the number of times that your implemented function rand10()
will be called while testing. Note that this is not an argument passed to rand10()
.
Follow up:
rand7()
function?rand7()
?Example 1:
1 | Input: n = 1 |
Example 2:
1 | Input: n = 2 |
Example 3:
1 | Input: n = 3 |
Constraints:
1 <= n <= 10^5
1 | # The rand7() API is already defined for you. |
You are given an array of intervals
, where intervals[i] = [start_i, end_i]
and each start_i
is unique.
The right interval for an interval i
is an interval j
such that start_j >= end_i
and start_j
is minimized.
Return an array of right interval indices for each interval i
. If no right interval exists for interval i
, then put -1
at index i
.
Example 1:
1 | Input: intervals = [[1,2]] |
Example 2:
1 | Input: intervals = [[3,4],[2,3],[1,2]] |
Example 3:
1 | Input: intervals = [[1,4],[2,3],[3,4]] |
Constraints:
1 <= intervals.length <= 2 * 10^4
intervals[i].length == 2
-106 <= start_i <= end_i <= 106
Sort + Binary Search.
First, sorted
every interval by interval[0]
, record a tuple(interval[0], i, interval[1])
.
Second, bisect.bisect_left
every interval by interval[2]
, return index
, record r = index
.
Last, res[i] = interval[r][1] = index
.
1 | class Solution: |
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
1 | n = 15, |
1 | class Solution: |
In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days
. Each day is an integer from 1
to 365
.
Train tickets are sold in 3 different ways:
costs[0]
dollars;costs[1]
dollars;costs[2]
dollars.The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days
.
Example 1:
1 | Input: days = [1,4,6,7,8,20], costs = [2,7,15] |
Example 2:
1 | Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] |
Note:
1 <= days.length <= 365
1 <= days[i] <= 365
days
is in strictly increasing order.costs.length == 3
1 <= costs[i] <= 1000
DP.
1 | dp[i]表示旅行到i天为止需要的最少旅行价格。 |
则递推公式为:
dp[i] = dp[i - 1]
当第i天不用旅行dp[i] = min(dp[i - 1] + costs[0], dp[i - 7] + costs[1], dp[i - 30] + costs[2])
当第i天需要旅行注意一下向前查找的时候是否越界。
1 | class Solution: |
Find the sum of all left leaves in a given binary tree.
Example:
1 |
|
Recursion.
1 | # Definition for a binary tree node. |
Implement the StreamChecker
class as follows:
StreamChecker(words)
: Constructor, init the data structure with the given words.query(letter)
: returns true if and only if for some k >= 1
, the last k
characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.Example:
1 | StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary. |
Note:
1 <= words.length <= 2000
1 <= words[i].length <= 2000
Python by search in Trie [w/ Visualization]
1 | from collections import defaultdict |
Given a list of non-overlapping axis-aligned rectangles rects
, write a function pick
which randomly and uniformily picks an integer point in the space covered by the rectangles.
Note:
i
th rectangle = rects[i] = [x1,y1,x2,y2]
, where [x1, y1]
are the integer coordinates of the bottom-left corner, and [x2, y2]
are the integer coordinates of the top-right corner.2000
.1 <= rects.length <= 100
pick
return a point as an array of integer coordinates [p_x, p_y]
pick
is called at most 10000
times.Example 1:
1 | Input: |
Example 2:
1 | Input: |
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution
‘s constructor has one argument, the array of rectangles rects
. pick
has no arguments. Arguments are always wrapped with a list, even if there aren’t any.
1 | import random |
Given an array A
of non-negative integers, return an array consisting of all the even elements of A
, followed by all the odd elements of A
.
You may return any answer array that satisfies this condition.
Example 1:
1 | Input: [3,1,2,4] |
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
1 | class Solution(object): |
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example 1:
1 | Given 1->2->3->4, reorder it to 1->4->2->3. |
Example 2:
1 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. |
linked list的经典题。
split_list(mid-point finding), reverse_list, merge_list的融合体。
1 | # Definition for singly-linked list. |
A sentence S
is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to “Goat Latin“ (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
"ma"
to the end of the word."ma"
.'a'
to the end of each word per its word index in the sentence, starting with 1."a"
added to the end, the second word gets "aa"
added to the end and so on.Return the final sentence representing the conversion from S
to Goat Latin.
Example 1:
1 | Input: "I speak Goat Latin" |
Example 2:
1 | Input: "The quick brown fox jumped over the lazy dog" |
Notes:
S
contains only uppercase, lowercase and spaces. Exactly one space between each word.1 <= S.length <= 150
.Easy题,但是需要注意一下这题的时间复杂度不是O(n)
,是O(n^2)
!!!
在python中,连接字符串的操作:
+
的时间复杂度是O(n^2)
,join
的时间复杂度是O(n)
.1 | class Solution(object): |
Return all non-negative integers of length N
such that the absolute difference between every two consecutive digits is K
.
Note that every number in the answer must not have leading zeros except for the number 0
itself. For example, 01
has one leading zero and is invalid, but 0
is valid.
You may return the answer in any order.
Example 1:
1 | Input: N = 3, K = 7 |
Example 2:
1 | Input: N = 2, K = 1 |
Note:
1 <= N <= 9
0 <= K <= 9
DFS.
1 | class Solution(object): |
We distribute some number of candies
, to a row of n = num_people
people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n
candies to the last person.
Then, we go back to the start of the row, giving n + 1
candies to the first person, n + 2
candies to the second person, and so on until we give 2 * n
candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length num_people
and sum candies
) that represents the final distribution of candies.
Example 1:
1 | Input: candies = 7, num_people = 4 |
Example 2:
1 | Input: candies = 10, num_people = 3 |
Constraints:
Simulation.
1 | class Solution(object): |
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
1 | Input: [[1,2],[2,3],[3,4],[1,3]] |
Example 2:
1 | Input: [[1,2],[1,2],[1,2]] |
Example 3:
1 | Input: [[1,2],[2,3]] |
Note:
Sort + Greedy.
1 | class Solution(object): |
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa"
is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
1 | Input: |
Greedy.
Intuition:
A palindrome consists of letters with equal partners, plus possibly a unique center (without a partner). The letter i
from the left has its partner i
from the right. For example in 'abcba'
, 'aa'
and 'bb'
are partners, and 'c'
is a unique center.
Imagine we built our palindrome. It consists of as many partnered letters as possible, plus a unique center if possible. This motivates a greedy approach.
Algorithm:
For each letter, say it occurs v
times. We know we have v // 2 * 2
letters that can be partnered for sure. For example, if we have 'aaaaa'
, then we could have 'aaaa'
partnered, which is 5 // 2 * 2 = 4
letters partnered.
At the end, if there was any v % 2 == 1
, then that letter could have been a unique center. Otherwise, every letter was partnered. To perform this check, we will check for v % 2 == 1 and ans % 2 == 0
, the latter meaning we haven’t yet added a unique center to the answer.
1 | class Solution(object): |
Design an Iterator class, which has:
characters
of sorted distinct lowercase English letters and a number combinationLength
as arguments.next()
that returns the next combination of length combinationLength
in lexicographical order.hasNext()
that returns True
if and only if there exists a next combination.Example:
1 | CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator. |
Constraints:
1 <= combinationLength <= characters.length <= 15
10^4
function calls per test.next
are valid.Python built-in itertools.combinations
.
1 | class CombinationIterator(object): |
Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal’s triangle.
Note that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
1 | Input: 3 |
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
DP.
1 | class Solution(object): |
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher’s h-index.
According to the definition of h-index on Wikipedia: “A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each.”
Example:
1 | Input: citations = [3,0,6,1,5] |
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Binary Search.
1 | class Solution(object): |