In February, it’s Chinese New Year. Even though people have to stay at home, in the evening, I can still hear firework outside. This year, the company gave out a jacket, a fitbit, and a useless laptop camera. Also, every week there’s free meal in Chinatown.
Week 1: March 1st - March 7th
Single-Row Keyboard
There is a special keyboard with all keys in a single row.
Given a string keyboard
of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i
to index j
is |i - j|
.
You want to type a string word
. Write a function to calculate how much time it takes to type it with one finger.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
keyboard.length == 26
-
keyboard
contains each English lowercase letter exactly once in some order. -
1 <= word.length <= 10^4
-
word[i]
is an English lowercase letter.
Hint 1:
Can be the problem divided in parts, so solving each part and sum their solutions it should return the answer? Yes, you only need to divide the problem in finger jumps.
Hint 2:
In each finger jump you need to move your finger from one character to another, you need to know its index.
Hint 3:
Map each character to it’s index.
Hint 4:
Use a hash table to do that.
Explanation
-
We can use brute force to solve this problem. First create a hash map, key is the keyboard character, value is the keyboard character’s index.
-
After we have the map, then loop through each character of the
word
. Initially the finger is on index 0, in other word,curIdx = 0
. We can get each character’s distance byabs(hm[ch] - curIdx)
, then we updatecurIdx
tohm[ch]
.
Solution
1 |
|
Distribute Candies
Alice has n
candies, where the ith
candy is of type candyType[i]
. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2
of the candies she has (n
is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor’s advice.
Given the integer array candyType
of length n
, return the maximum number of different types of candies she can eat if she only eats n / 2
of them.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
n == candyType.length
-
2 <= n <= 10^4
-
n
is even. -
-10^5 <= candyType[i] <= 10^5
Hint 1:
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds.
Hint 2:
What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally.
Hint 3:
Which data structure is the most suitable for finding the number of kinds of candies?
Hint 4:
Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
Explanation
- First, we need to calculate the total kinds of candies by using a hash set. Then, since brother and sister will have same number of candies, in other words, sister can have the maximum kind of candies which is
candies.length / 2
assuming every candies are different kinds. Also, if the number of kindsset.size()
is less thancandies.length / 2
, then sister can only haveset.size()
kinds.
Solution
1 |
|
Set Mismatch
You have a set of integers s
, which originally contains all the numbers from 1
to n
. Unfortunately, due to some error, one of the numbers in s
got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums
representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
2 <= nums.length <= 10^4
-
1 <= nums[i] <= 10^4
Explanation 1
-
We can sort the input array and loop from 1 to n to find out the duplicated number and missing number, or we can also solve this problem by using a set to record the visited number, or a map to record the frequency.
-
To solve this problem in O(1) space, we can modify the input array. When we see a number
num
, we can modify its corresponding indexnum-1
’s number to negative. Before we change it to negative, we check if it’s already negative then that means the currentnum
is duplicated. Else, we set its corresponding index’s number to negative. After that, we loop the input array again, ifnum
is positive, that means we have a missing number which is equal to the current index + 1.
Solution 1
1 |
|
Explanation 2
- We can also solve this problem using cyclic sort to sort the input array. Then loop the array, if
num
is not equal to its corresponding indexidx + 1
, that meansnum
is duplicated, missing number isidx + 1
.
Solution 2
1 |
|
Missing Number
Given an array nums
containing n
distinct numbers in the range [0, n]
, return the only number in the range that is missing from the array.
Follow up: Could you implement a solution using only O(1)
extra space complexity and O(n)
runtime complexity?
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Constraints:
-
n == nums.length
-
1 <= n <= 10^4
-
0 <= nums[i] <= n
-
All the numbers of
nums
are unique.
Explanation 1
- Calculate the input array’s sum, then minums the actual array’s sum, this will gives the missing number.
Solution 1
1 |
|
Explanation 2
-
We can use XOR to solve this problem.
-
We XOR all the numbers in the input array with the actual array’s numbers. The result will be the missing number.
Solution 2
1 |
|
Intersection of Two Linked Lists
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
:
It is guaranteed 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.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
The number of nodes of
listA
is in them
. -
The number of nodes of
listB
is in then
. -
0 <= m, n <= 3 * 10^4
-
1 <= Node.val <= 10^5
-
0 <= skipA <= m
-
0 <= skipB <= n
-
intersectVal
is0
iflistA
andlistB
do not intersect. -
intersectVal == listA[skipA + 1] == listB[skipB + 1]
iflistA
andlistB
intersect.
Follow up: Could you write a solution that runs in O(n)
time and use only O(1)
memory?
Explanation 1
- We can start compaing using two pointers when both list have the same length, so we move forward
diff
steps on the long linked list’s pointer. Then iterate both pointer and compare each node.
Solution 1
1 |
|
Explanation 2
- When we finish iterating one list, we move that pointer start from the beginning of another list. When two pointers meet, that node is the intesection. Because both pointers run the same length, in other word, the sum of lenA and lenB doesn’t change.
Solution 2
1 |
|
Average of Levels in Binary Tree
Given the root
of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10^-5
of the actual answer will be accepted.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
The number of nodes in the tree is in the range
[1, 10^4]
. -
-2^31 <= Node.val <= 2^31 - 1
Explanation
- We can solve this problem using level-order traversal, in other words, BFS. For each level, we use a variable
sum
to sum all the numbers on the same level. After we finish iterating all numbers on the same level, we then calculate the average bysum
divide the numbers of that level.
Solution
1 |
|
Short Encoding of Words
A valid encoding of an array of words
is any reference string s
and array of indices indices
such that:
-
words.length == indices.length
-
The reference string
s
ends with the'#'
character. -
For each index
indices[i]
, the substring ofs
starting fromindices[i]
and up to (but not including) the next'#'
character is equal towords[i]
. -
Given an array of
words
, return the length of the shortest reference strings
possible of any valid encoding ofwords
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= words.length <= 2000
-
1 <= words[i].length <= 7
-
words[i]
consists of only lowercase letters.
Explanation 1
- If there are two string
A
andB
, andB
is the suffix ofA
, then we don’t need to countB
. For example, ifA = "time"
andB = "me"
, then we can skip countingB
. So the goal is to remove words from the list such that no word is a suffix of another. The result would besum(word.length + 1 for word in words)
.
Solution 1
1 |
|
Explanation 2
-
To find whether different words have the same suffix, let’s put them backwards into a trie (prefix tree). For example, if we have
"time"
and"me"
, we will put"emit"
and"em"
into our trie. -
After, the leaves of this trie (nodes with no children) represent words that have no suffix, and we will count
sum(word.length + 1 for word in words)
.
Solution 2
1 |
|
Design HashMap
Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap
class:
-
MyHashMap()
initializes the object with an empty map. -
void put(int key, int value)
inserts a(key, value)
pair into the HashMap. If thekey
already exists in the map, update the correspondingvalue
. -
int get(int key)
returns thevalue
to which the specifiedkey
is mapped, or-1
if this map contains no mapping for thekey
. -
void remove(key)
removes thekey
and its correspondingvalue
if the map contains the mapping for thekey
.
Example 1:
1 |
|
Constraints:
-
0 <= key, value <= 10^6
-
At most
10^4
calls will be made toput
,get
, andremove
.
Follow up: Please do not use the built-in HashMap library.
Explanation 1
- Since the range for keys is
[0, 1000000]
, we can create an array of size1000001
and initialize all elements to -1. Input
method, we can just update thearr[key] = value]
. Inget
method, we can just returnarr[key]
. Inremove
method, we can just updatearr[key] = -1
.
Solution 1
1 |
|
Explanation 2
- We can save space by creating an array of linked node, and the array has size 10000 or 13000 for making the key distribute evenly. If two different keys lie on the same array index, then there’s a collision. Then we need to loop through the linked node and return the previous node of the node that has the same key, so that we can delete the node by
prev.next = prev.next.next
. Input
method, if no node onlst[idx]
, then we need to make a dummy nodelst[idx] = new Node(-1, -1)
so thatprev
is not pointing tonull
.
Solution 2
1 |
|
Week 2: March 8th - March 14th
Strobogrammatic Number
Given a string num
which represents an integer, return true
if num
is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180
degrees (looked at upside down).
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Constraints:
-
1 <= num.length <= 50
-
num
consists of only digits. -
num
does not contain any leading zeros except for zero itself.
Explanation
- Only the following digit can be strobogrammatic, if there’s other digit, then we return false immediately.
1 |
|
-
If the string length is odd, then the middle character must not be
6
or9
. -
We can use two pointers to check if the numbers are matched with its rotated one.
Solution
1 |
|
Remove Palindromic Subsequences
You are given a string s
consisting only of letters 'a'
and 'b'
. In a single step you can remove one palindromic subsequence from s
.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= s.length <= 1000
-
s[i]
is either'a'
or'b'
.
Hint 1:
Use the fact that string contains only 2 characters.
Hint 2:
Are subsequences composed of only one type of letter always palindrome strings ?
Explanation
-
If the string is empty, we return 0.
-
If the string is palindrome, we return 1.
-
Since there are
a
andb
in the string, we can remove sequence of alla
s which cost 1 operation, then remove sequence of allb
s which cost 1 operation, so total 2 operations.
Solution
1 |
|
Add One Row to Tree
Given the root
of a binary tree and two integers val
and depth
, add a row of nodes with value val
at the given depth depth
.
Note that the root
node is at depth 1
.
The adding rule is:
-
Given the integer
depth
, for each not null tree nodecur
at the depthdepth - 1
, create two tree nodes with valueval
ascur
’s left subtree root and right subtree root. -
cur
’s original left subtree should be the left subtree of the new left subtree root. -
cur
’s original right subtree should be the right subtree of the new right subtree root. -
If
depth == 1
that means there is no depthdepth - 1
at all, then create a tree node with valueval
as the new root of the whole original tree, and the original tree is the new root’s left subtree.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
The number of nodes in the tree is in the range
[1, 10^4]
. -
The depth of the tree is in the range
[1, 10^4]
. -
-100 <= Node.val <= 100
-
-10^5 <= val <= 10^5
-
1 <= depth <= the depth of tree + 1
Explanation 1
-
If
d
is equal to 1, then we can just make a new TreeNode and connect its left child to theroot
and we return the new TreeNode. -
Else if
d
is not equal to 1, we can use level-order traversal to solve this problem. First, store the root TreeNode into the queue. Then while the queue is not empty, we decreased
by 1. Poll the nodes from the queue, ifd
is equal to 1, then we need to save the poll node’s left and right child asleft
andright
. Then insert the row of TreeNode with valuev
byp.left = new TreeNode(v)
andp.right = new TreeNode(v)
, then connect back to theleft
andright
byp.left.left = left
andp.right.right = right
. Else ifd
is not equal to 1, then we just add the poll node’s left child and right child into the queue. At the end, we returnroot
.
Solution 1
1 |
|
Explanation 2
- We can also use DFS to solve this problem. We will only add new nodes under the current root node at depth
d-1
.
Solution 2
1 |
|
Integer to Roman
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
1 |
|
For example, 2
is written as II
in Roman numeral, just two one’s added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
-
I
can be placed before V (5) and X (10) to make 4 and 9. -
X
can be placed before L (50) and C (100) to make 40 and 90. -
C
can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
1 <= num <= 3999
Explanation
Character | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
Number | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
-
For example, 1437 in roman is MCDXXXVII. We find out the thousand digit, hundred digit, thenth digit, and single digit’s numbers all can be represented by roman character. 1000 is M, 400 is CD, 30 is XXX, 7 is VII. So, we can get every digit by division 1000, 100, 10, 1, and represent them.
-
We can have 4 groups. 1-3 is one group, 4 is one group, 5-8 is one group, 9 is one group. For example:
-
100 - C
-
200 - CC
-
300 - CCC
-
400 - CD
-
500 - D
-
600 - DC
-
700 - DCC
-
800 - DCCC
-
900 - CM
- We will first create a roman character array
roman{'M', 'D', 'C', 'L', 'X', 'V', 'I'}
and value arrayvalue{1000, 500, 100, 50, 10, 5, 1}
. We will iterate two steps each time, in other words, 1000, then 100, then 10, then 1, so we can divide it to get the digit.
Solution
1 |
|
Coin Change
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
You may assume that you have an infinite number of each kind of coin.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
1 <= coins.length <= 12
-
1 <= coins[i] <= 2^31 - 1
-
0 <= amount <= 10^4
Explanation 1
-
For problems that asking for minimum or maximum number, we can use dynamic programming to solve.
-
Dynamic statis a one dimensional array,
dp[i]
which represents for amounti
, the minimum number of coins we should choose. We will createdp[amount+1]
since we should consideramount=0
. -
Dynamic init is
dp[0] = 0
. Ifamount=0
, then the result should be 0 since we do not need any number of coins to get the amount 0. Otherdp[i]
will all beamount+1
since the maximum number of coins can choose isdp[i]=amount
. We plus one, so thatdp[i]
cannot reachamount+1
. At the end, ifdp[i]
still equal toamount+1
, then it means we cannot formtarget=amount
, so we return-1
. -
Dynamic function is
dp[i] = min(dp[i], dp[ i - coins[j] ] + 1
, andj
means loop from all coins index. For example 1, we need to finddp[11]
, if we choose coinscoins[j]=5
, then if we knowdp[6]
, then we get the result fordp[11] = dp[6] + 1
. -
Dynamic result is if
dp[amount]
still equals toamount+1
, we return-1
. Else, we returndp[amount]
.
Solution 1
1 |
|
Explanation 2
-
We can use memoization to improve the time complexity of the above dynamic programming.
-
We use
memo[i]
to represent for amounti
, the minimum number of coins we choose. The base case if target is less than 0, we return -1. Ifmemo[target]
is not equal to the initialInteger.MAX_VALUE
, then it means we already have the value ofmemo[target]
, so we can just return it. -
We need to loop through all coins, if we choose
coins[j]
, then we recursivly find the resulttemp
of targettarget-coins[j]
. If that resulttemp >= 0
, then we update the resultmemo[target] = min(memo[target], temp+1)
similar to the above solution. -
Outside the loop, if
memo[target]
still equals toMAX_VALUE
, then it means it cannot form the target since alltemp < 0
, somemo[target] = -1
. Else we returnmemo[target]
.
Solution 2
1 |
|
Check If a String Contains All Binary Codes of Size K
Given a binary string s
and an integer k
.
Return True if every binary code of length k
is a substring of s
. Otherwise, return False.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
1 <= s.length <= 5 * 10^5
-
s
consists of 0’s and 1’s only. -
1 <= k <= 20
Hint 1:
We need only to check all sub-strings of length k.
Hint 2:
The number of distinct sub-strings should be exactly 2^k.
Explanation
- We can use sliding window to find all distinct substring of size
k
and put them into a set. If the set has1 << k
distinct substring, then we return true.
Solution
1 |
|
Binary Trees With Factors
Given an array of unique integers, arr
, where each integer arr[i]
is strictly greater than 1
.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node’s value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 10^9 + 7
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= arr.length <= 1000
-
2 <= arr[i] <= 10^9
Explanation
-
We can solve this problem using dynamic programming. Dynamic state is
dp[i]
which represents the number of binary trees we can make for root valuei
. -
Dynamic init is every value in
arr
, we can make at least 1 binary tree, which has only one node. -
Dynamic function is
dp[i] += dp[j] * dp[i / j]
for every valuej
less than valuei
fromarr
. In order to finddp[i]
, first we need to finddp[j]
so we need to sortarr
in the beginning. -
Dynamic result is the sum of all
dp[i]
.
Solution
1 |
|
Swapping Nodes in a Linked List
You are given the head
of a linked list, and an integer k
.
Return the head of the linked list after swapping the values of the kth
node from the beginning and the kth
node from the end (the list is 1-indexed).
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Constraints:
-
The number of nodes in the list is
n
. -
1 <= k <= n <= 10^5
-
0 <= Node.val <= 100
Hint 1:
We can transform the linked list to an array this should ease things up
Hint 2:
After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Explanation
- We can use brute force to solve this problem. First finding the
ith
node from the left and theith
node from the right, then swap their values and returnhead
.
Solution
1 |
|
Week 3: March 15th - March 21st
Construct Binary Tree from String
You need to construct a binary tree from a string consisting of parenthesis and integers.
The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure.
You always start to construct the left child node of the parent first if it exists.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
0 <= s.length <= 3 * 10^4
-
s
consists of digits,'('
,')'
, and'-'
only.
Explanation 1
- We can use recursive method to solve this problem. First character of the input string is not parenthesis, so we can create the
root
node first. When we iterate to a left parenthesis, we find its mathing right parenthesis, then recusivly call the main function with the substring in between these two matching parenthesis. This recusive function will return a TreeNodecurNode
, ifroot
doesn’t have left child, then addcurNode
toroot.left
, else add toroot.right
.
Solution 1
1 |
|
Explanation 2
-
Iterate the input string, when we see character that is not parenthesis, then we record these characters to a string builder
sb
. -
When we see
(
, then make a TreeNodecurNode
fromsb
and push to stack. -
When we see
)
, then make a TreeNodecurNode
fromsb
, andcurNode
’s parent node isst.peek()
. If parent node doesn’t have left child, addcurNode
to its left child, else addcurNode
to its right child. One corner case is two right parenthesis next to each other. For example the last two)
s in4(2(3)(1))
, thensb
is empty, socurNode
isst.pop()
.
Solution 2
1 |
|
Encode and Decode TinyURL
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Explanation 1
-
For the
encode
function, we can create a list to store the url that is going to be encoded, then we return the list’s index. -
For the
decode
function, we can split the url to get its index. Then return the url from the list based on the index.
Solution 1
1 |
|
Explanation 2
-
When we encode, we want to generate 6 random characters for the input url. We can use a HashMap
longToShort
represent the key is the long url, the value is the 6 random characters. So, when we encode a same url, we can use $O(1)$ runtime to get the random 6 characters. -
When we decode, we are providing the 6 random characters at the end of the short url, so we first need to get these 6 random characters. We want to use $O(1)$ runtime to get back the long url, so we need a
shortToLong
HashMap when we doing encoding, and its key is the 6 random characters, its value is the long url before encode. We will update both HashMap when we do encode. -
We can generate the 6 random characters by creating a empty string builder and a dictionary string contains all 10 digits, all 26 lower case letter, and all 26 upper case letters. Then loop 6 times, each time we generate a random integer index between 0 to 61 inclusive to get a random character. If the generated 6 random characters string is inside the HashMap
shortToLong
, then we need to regenerate.
Solution 2
1 |
|
Best Time to Buy and Sell Stock with Transaction Fee
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day, and an integer fee
representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 < prices.length <= 5 * 10^4
-
0 < prices[i], fee < 5 * 10^4
Hint 1:
Consider the first K stock prices. At the end, the only legal states are that you don’t own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
Explanation 1
-
We can use dynamic programming to solve this problem. Dynamic state. In each day, we either sell or not sell, so we create two arrays
sell[i]
andnotSell[i]
. It means at dayi
, the maximum profit of sell and not sell respectivly. -
Dynamic init is at day 1,
sell[0] = 0
,notSell[0] = -prices[0]
. -
Dynamic function. If we sell on day
i
, then the maximum profit onsell[i]
either equals to the previous day’s maximum profitsell[i-1]
or sell on dayi
, in other words,prices[i] + notSell[i-1] - fee
because if sell on dayi
, then on dayi-1
we must not sell. So we getsell[i] = max(sell[i-1], prices[i] + notSell[i-1] - fee)
. -
If we don’t sell on day
i
, then the maximum profit onnotSell[i]
either equals to the previous day’s not sell profitnotSell[i-1]
or buy on dayi
, in other words,sell[i-1]-prices[i]
because we can only buy after sell. So we getnotSell[i] = max(notSell[i-1], sell[i-1] - prices[i])
. -
Dynamic result is the maximum profit we sell on the last day.
Solution 1
1 |
|
Explanation 2
- We can save some space. We notice that current day
i
‘ssell[i]
andnotSell[i]
are only related to dayi-1
. So instead of using an array to hold all day, we can use two variablesell
andnotSell
to representsell[i]
andnotSell[i]
.
Solution 2
1 |
|
Generate Random Point in a Circle
Given the radius and x-y positions of the center of a circle, write a function randPoint
which generates a uniform random point in the circle.
Note:
-
input and output values are in floating-point.
-
radius and x-y position of the center of the circle is passed into the class constructor.
-
a point on the circumference of the circle is considered to be in the circle.
-
randPoint
returns a size 2 array containing x-position and y-position of the random point, in that order.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution
’s constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint
has no arguments. Arguments are always wrapped with a list, even if there aren’t any.
Explanation
-
We can use rejection sampling similar to 470. Implement Rand10() Using Rand7(). We also know the equation for a circle is
(x - a) ^ 2 + (y - b) ^ 2 = r ^ 2
wherea
andb
is the center of the circle. So we need to find outx
andy
. -
We can first find out the minimum x
minX
byx_center - radius
, and the minimum yminY
byy_center - radius
. Then, we generate a random number between 0 to radius * 2, then plus theminX
orminY
with that random number to get thex
andy
. -
After we get the point position, then we check if this point position is inside the circle by the above formula. If this position is outside of the circle, then we repeat to calculate the position’s
x
andy
axises.
Solution
1 |
|
Wiggle Subsequence
Given an integer array nums
, return the length of the longest wiggle sequence.
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
-
For example,
[1, 7, 4, 9, 2, 5]
is a wiggle sequence because the differences(6, -3, 5, -7, 3)
are alternately positive and negative. -
In contrast,
[1, 4, 7, 2, 5]
and[1, 7, 4, 5, 5]
are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. -
A subsequence is obtained by deleting some elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
1 <= nums.length <= 1000
-
0 <= nums[i] <= 1000
Follow up: Could you solve this in O(n)
time?
Explanation 1
-
We can use dynamic programming to solve this problem. First, we create two one dimensional array
p[]
andn[]
. Forp[i]
, it means until indexi
inclusive, the maximum length of the wiggle subsequence that ends with positive difference. Forn[i]
, it means until indexi
inclusive, the maximum length of the wiggle subsequence that ends with negative difference. -
We can loop from index i = 1 to the last index, and for every current index i, we loop from index j = 0 to i-1 inclusive, if
nums[j] < nums[i]
, then it means the last difference untili
inclusive is positive, so we updatep[i] = 1 + n[j]
. 1 means the current numbernums[i]
, we addn[i]
becausen[i]
means until indexi
inclusive, the last difference is negative. For example,[1, 17, 5, 10]
, ifi
is pointing to element 10,j
is pointing to element 5, then we updatep[i]
because[5, 10]
has positive difference. Now, similarlly, ifnums[j] > nums[i]
, we want to updaten[i] = 1 + p[j]
.
Solution 1
1 |
|
Explanation 2
- We can solve it in $O(n)$ runtime. Instead of having two arrays
p[]
andn[]
, we can make them as two variablesp
andn
to record the last difference is positive and negative. We can loop one time, in every iteration, we update eitherp
orn
depends onnums[i] and nums[i-1]
.
Solution 2
1 |
|
Keys and Rooms
There are N
rooms and you start in room 0
. Each room has a distinct number in 0, 1, 2, ..., N-1
, and each room may have some keys to access the next room.
Formally, each room i
has a list of keys rooms[i]
, and each key rooms[i][j]
is an integer in [0, 1, ..., N-1]
where N = rooms.length
. A key rooms[i][j] = v
opens the room with number v
.
Initially, all the rooms start locked (except for room 0
).
You can walk back and forth between rooms freely.
Return true
if and only if you can enter every room.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
-
1 <= rooms.length <= 1000
-
0 <= rooms[i].length <= 1000
-
The number of keys in all rooms combined is at most
3000
.
Explanation 1
- We can use brute force BFS to solve this problem.
Solution 1
1 |
|
Explanation 2
- We can also use DFS to solve this problem.
Solution 2
1 |
|
Design Underground System
Implement the UndergroundSystem
class:
void checkIn(int id, string stationName, int t)
-
A customer with a card id equal to
id
, gets in the stationstationName
at timet
. -
A customer can only be checked into one place at a time.
void checkOut(int id, string stationName, int t)
- A customer with a card id equal to
id
, gets out from the stationstationName
at timet
.
double getAverageTime(string startStation, string endStation)
-
Returns the average time to travel between the
startStation
and theendStation
. -
The average time is computed from all the previous traveling from
startStation
toendStation
that happened directly. -
Call to
getAverageTime
is always valid.
You can assume all calls to checkIn
and checkOut
methods are consistent. If a customer gets in at time t1 at some station, they get out at time t2 with t2 > t1. All events happen in chronological order.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
There will be at most
20000
operations. -
1 <= id, t <= 106
-
All strings consist of uppercase and lowercase English letters, and digits.
-
1 <= stationName.length <= 10
-
Answers within
10^-5
of the actual value will be accepted as correct.
Hint 1:
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Explanation
-
In the
checkIn
method, we create a hashmapcheckinHm
to record the input. The key isid
, the value is a pair of[stationName, checkInTime]
. -
In the
checkOut
method, we need to prepare to calculate the average time between two stations, so we need a route namecheckInStation#checkOutStation
, and its total travel time and total number of travels. So we need a another hashmaprouteHm
, key isrouteName
, value is a pair of[totalTime, totalNumTravel]
. So in thecheckOut
method, we need to record and update these data in this hashmap. -
In the
getAverageTime
method, we can just use therouteHm
to get the currentroute
’s total time divide its total number of travels to get the average time.
Solution
1 |
|
Reordered Power of 2
Starting with a positive integer N
, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true
if and only if we can do this in a way such that the resulting number is a power of 2.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Note:
1 <= N <= 10^9
Explanation 1:**
-
We can generate all permutations of
N
and check each permutation if its power of two. -
To generate permutation, we place any digit into the first position (
start = 0
), then any of the remaining digits into the second position (start = 1
), and so on. -
To check if a number is power of two, while the number is even, we can right shift it until it becomes odd number. Then we check if this odd number equals to 1, then it’s power of two, otherwise it’s not power of two.
Solution 1:**
1 |
|
Explanation 2
- Since the input number has a constraint between
1
to10^9
, we can generate all numbers that is power of two and compare it with the input. Since the input digit can reorder, we can compare by every digit’s frequency.
Solution 2
1 |
|
Week 4: March 22nd - March 28th
Find Smallest Common Element in All Rows
Given a matrix mat
where every row is sorted in strictly increasing order, return the smallest common element in all rows.
If there is no common element, return -1
.
Example 1:
1 |
|
Constraints:
-
1 <= mat.length, mat[i].length <= 500
-
1 <= mat[i][j] <= 10^4
-
mat[i]
is sorted in strictly increasing order.
Hint 1:
Notice that each row has no duplicates.
Hint 2:
Is counting the frequency of elements enough to find the answer?
Hint 3:
Use a data structure to count the frequency of elements.
Hint 4:
Find an element whose frequency equals the number of rows.
Explanation
- We can use brute force to solve this problem. Count the frequency of every number, if there’s a number’s frequency equals to
mat.length
, then we return that number.
Solution
1 |
|
Vowel Spellchecker
Given a wordlist
, we want to implement a spellchecker that converts a query word into a correct word.
For a given query
word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.
-
Example:
wordlist = ["yellow"]
,query = "YellOw"
:correct = "yellow"
-
Example:
wordlist = ["Yellow"]
,query = "yellow"
:correct = "Yellow"
-
Example:
wordlist = ["yellow"]
,query = "yellow"
:correct = "yellow"
Vowel Errors: If after replacing the vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
-
Example:
wordlist = ["YellOw"]
,query = "yollow"
:correct = "YellOw"
-
Example:
wordlist = ["YellOw"]
,query = "yeellow"
:correct = ""
(no match) -
Example:
wordlist = ["YellOw"]
,query = "yllw"
:correct = ""
(no match)
In addition, the spell checker operates under the following precedence rules:
-
When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
-
When the query matches a word up to capitlization, you should return the first such match in the wordlist.
-
When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
-
If the query has no matches in the wordlist, you should return the empty string.
Given some queries
, return a list of words answer
, where answer[i]
is the correct word for query = queries[i]
.
Example 1:
1 |
|
Note:
-
1 <= wordlist.length <= 5000
-
1 <= queries.length <= 5000
-
1 <= wordlist[i].length <= 7
-
1 <= queries[i].length <= 7
-
All strings in
wordlist
andqueries
consist only of english letters.
Explanation
-
We need to consider three cases. First case is when the query is exact match the word, we return the word. Second case is when the query match all characters case insensitively, we return the word. Third case is when the query is replacing all vowels then it matches the word which is also replacing all vowels case insensitively, we return the word.
-
For the first case, we can use a set to hold all the words, then check if the query is in the set. For the second case, we can create a map, key is lower case of word, value is the original word; then check if the query’s lower case is in the map, then we return its corresponding word. For the third case, we can also create a map, key is the lower case of the word after replacing all vowels with a placeholder
#
, value is the original word; then check if the query after replacing all vowels with a same placeholder#
is in the map, then return its corresponding original word. If the query is not matched with all three cases, then we add an empty string to the result array.
Solution
1 |
|
3Sum With Multiplicity
Given an integer array arr
, and an integer target
, return the number of tuples i, j, k
such that i < j < k
and arr[i] + arr[j] + arr[k] == target
.
As the answer can be very large, return it modulo 10^9 + 7
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
3 <= arr.length <= 3000
-
0 <= arr[i] <= 100
-
0 <= target <= 300
Explanation
-
We think of
arr[i]
is the third number, then the resultres
should be adding the frequency of the sum of the first two numbers. We can create a hashmap, the key is the sum of the first two numbers, the value is its frequency. -
Loop through the array, the current element is
arr[i]
, then adding the frequency of the sum of the first two numbers, in other words,res += hm[target-arr[i]]
. Then loopj
from 0 toi
inclusive. Now to prepare the next thrid numberarr[i+1]
, the sum of the first two numbers arearr[j] + arr[i]
and we update its frequency in the hashmap.
Solution
1 |
|
Advantage Shuffle
Given two arrays A
and B
of equal size, the advantage of A
with respect to B
is the number of indices i
for which A[i] > B[i]
.
Return any permutation of A
that maximizes its advantage with respect to B
.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
-
1 <= A.length = B.length <= 10000
-
0 <= A[i] <= 10^9
-
0 <= B[i] <= 10^9
Explanation
- We can use greddy to solve this problem. We always want to satisfy the biggest number of
B
first because that is the hardest number to satisfy. If we can’t find a number fromA
to satisfy the biggest number ofB
, then we use the smallest number fromA
.
Solution
1 |
|
Pacific Atlantic Water Flow
Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
-
The order of returned grid coordinates does not matter.
-
Both m and n are less than 150.
Example:
1 |
|
Explanation
-
We can solve this problem using BFS. We need two visited arrays
pacific[][]
andatlantic[][]
to note down if the elements can reach pacific or atlantic. Initially, we mark the top and left side elements in thepacific[][]
betrue
, right side and bottom side element in theatlantic[][]
betrue
. We also create two queuesqueuePacific
andqueueAtlantic
to initially store top side and left side intoqueuePacific
, right side and bottom side element intoqueueAtlantic
. -
Now, we need two BFS helper method. We pass
matrix[][]
,pacific[][]
oratlantic[][]
asvisitied[][]
, and passqueuePacific
orqueueAtlantic
asqueue
corresponding to theirvisited[][]
. -
Inside the BFS helper method, while the queue is not empty, we pop element out as
temp[]
. We need to loop through four directions and update rowtemp[0]
and columntemp[1]
. If the row or column are not inside the range, orvisited[r][c]
istrue
, or the updatedmatrix[r][c]
is less than the originaltemp[0]
andtemp[1]
’s matrix height, wecontinue
the loop and check the next direction. Else, we update the updated row and col in thevisited[r][c]
betrue
, then push it to thequeue
.
Solution
1 |
|
Word Subsets
We are given two arrays A
and B
of words. Each word is a string of lowercase letters.
Now, say that word b
is a subset of word a
if every letter in b
occurs in a
, including multiplicity. For example, "wrr"
is a subset of "warrior"
, but is not a subset of "world"
.
Now say a word a
from A
is universal if for every b
in B
, b
is a subset of a
.
Return a list of all universal words in A
. You can return the words in any order.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Note:
-
1 <= A.length, B.length <= 10000
-
1 <= A[i].length, B[i].length <= 10
-
A[i]
andB[i]
consist only of lowercase letters. -
All words in
A[i]
are unique: there isn’ti != j
withA[i] == A[j]
.
Explanation
- First we get every characters’ maximum frequency in
B
and record it incount[26]
. Then loop through every worda
fromA
. If any character’s frequency from a worda
have less frequency than its corresponding character fromcount[i]
, then this worda
is not universal, else it’s universal and we add it in the result list.
Solution
1 |
|
Palindromic Substrings
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
- The input string length won’t exceed 1000.
Hint 1:
How can we reuse a previously computed palindrome to compute a larger palindrome?
Hint 2:
If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome?
Hint 3:
Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?
Explanation 1
- Loop through the string, for every character, we think it as the middle. Palindrome has two cases. Case 1 is odd length string, we can initialize two pointers
i
andj
pointing to the same character. Ifs[i] == s[j]
, we increase the result, andi
move left,j
move right, until their pointing character different. Case 2 is even length string, so initialy,i
points at the middle left,j
points at the middle right, and check their character if they are the same. If they are the same, we increase the result and movei
left, movej
right.
Solution 1
1 |
|
Explanation 2
-
We can also use dynamic programming to solve this problem. Dynamic state is a boolean two dimensional array
dp[i][j]
representsstr[i:j]
if it’s palindrome or not. -
Dynamic init, all elements are false.
-
Dynamic function.
dp[i][j]
will be true ifstr[i] == str[j] && (j - i <= 2)
, for examplestr=aba
,str[i=0]=a
andstr[j=2]=a
. What ifj - i > 2
. For example,str=xabax
,str[i=0] = x
,str[j=4]=x
. Ifstr[i] == str[j]
, thendp[i][j]
will be true ifdp[i+1][j-1]
is true, in this case we need to checkdp[i+1=1][j-1=3]
, so we need to loopi
from the right to left, loopj
fromi
to the right. And the dynamic function isdp[i][j] = (s[i] == s[j]) && (j - i <= 2 || dp[i + 1][j - 1])
. -
Dynamic result. Every time, we check the
dp[i][j]
is true, we increase the result counter.
Solution 2
1 |
|
Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.
Note:
-
Input contains only lowercase English letters.
-
Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as “abc” or “zerone” are not permitted.
-
Input length is less than 50,000.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
First, we count the frequency of all characters in the input string. Then, we notice from the English representation of these 10 digits
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
, some character appear only once in a specific English representation. For example,z
only appears inzero
.w,u,x,g
appear only intwo,four,six,eight
respectivly. So these 5 English representation are decided. -
For character
o
, it appears inzero,two,four,one
, since the first three are decided, we can use the frequency of charactero
to subtract the first 3 English representation letter’s frequency in order to get the frequency ofone
. For characterh
, it appears ineight, three
, since the first one is decided, we can calculate the frequency ofthree
. For characterf
, it appears infour, five
, since the first one is decided, we can calculate the frequency offive
. For characters
, it appears insix, seven
, since the first one is decided, we can calculate the frequency ofseven
. For characteri
, it appears insix,eight,five,nine
, since the first three are decided, we can calculate the frequency ofnine
. -
Therefore, we can find the frequency of English representation by following this order:
"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"
.
Solution
1 |
|
Week 5: March 29th - March 31st
Parallel Courses
You are given an integer n
which indicates that we have n
courses, labeled from 1
to n
. You are also given an array relations
where relations[i] = [a, b]
, representing a prerequisite relationship between course a
and course b
: course a
has to be studied before course b
.
In one semester, you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.
Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1
.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= n <= 5000
-
1 <= relations.length <= 5000
-
1 <= a, b <= n
-
a != b
-
All the pairs
[a, b]
are unique.
Hint 1:
Try to think of it as a graph problem. It will be impossible to study all the courses if the graph had a cycle.
Hint 2:
The graph is a directed acyclic graph (DAG). The answer is the longes path in this DAG.
Hint 3:
You can use DP to find the longest path in the DAG.
Explanation
-
This is a topological sorting problem. First, we need to implement a
inDegree[i]
to record how many prerequisites coursei
has. Also we need to implement a hashmaphm[int]int[]
, key is the current course, value is a list of courses that depends on the current course. -
We can use BFS way of topological sorting. First pushing all courses that have zero dependency into a queue. While the queue is not empty, we increase the
semesterCount
, then loopqueue.size()
times, poll out the current course, increase thecourseCount
. Then loop through all the courses that depends on the current course, update theirinDegree[]
. If after update, theinDegree
becomes zero, then we push that course into the queue. -
At the end when the queue is empty, if
courseCount
if not equals ton
, then we return -1, else returnsemesterCount
.
Solution
1 |
|
Flip Binary Tree To Match Preorder Traversal
You are given the root
of a binary tree with n
nodes, where each node is uniquely assigned a value from 1
to n
. You are also given a sequence of n
values voyage
, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage
.
Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage
, return the list [-1]
.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Constraints:
-
The number of nodes in the tree is
n
. -
n == voyage.length
-
1 <= n <= 100
-
1 <= Node.val, voyage[i] <= n
-
All the values in the tree are unique.
-
All the values in
voyage
are unique.
Explanation
- We can use brute force to solve this problem. First checking the root node. If root node is NULL, then return
true
. If root node is not equal tovoyage[globalIdx]
then returnfalse
. Next checking the root node’s left child node. If its not equal tovoyage[globalIdx]
, then we flip it, add the current root node to the list, recursively runhelper(root.right, voyage) && helper(root.left, voyage)
. Else if the root node’s left child equals tovoyage[globalIdx]
, then we just run normal pre-order traversalhelper(root.left, voyage) && helper(root.right, voyage)
. If the helper function returns false, then the result is[-1]
. else we return the result list.
Solution
1 |
|
Russian Doll Envelopes
You are given a 2D array of integers envelopes
where envelopes[i] = [wi, hi]
represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope’s width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
1 |
|
Example 2:
1 |
|
Constraints:
-
1 <= envelopes.length <= 5000
-
envelopes[i].length == 2
-
1 <= wi, hi <= 10^4
Explanation
-
We can use dynamic programming to solve this problem. First, we will sort the envelopes by width ascending, if the width is the same, we sort height ascending.
-
Dynamic state is a one dimensional array
dp[i]
which represents until the ith index envelope (inclusive), the maximum Russian Doll Envelopes it has. -
Dynamic init is all
dp[i]
at least equals to 1, which is itself’s envelope. -
Dynamic function will be
dp[i] = max(dp[i], dp[j] + 1)
for0 <= j < i
and only ifenvelopes[i]
’s width and height is greater thanenvelopes[j]
’s width and height. Every time after we updatedp[i]
, we compare it withres
to updateres
be the maximum. -
Dynamic result will be
res
.
Solution
1 |
|
Stamping The Sequence
You want to form a target
string of lowercase letters.
At the beginning, your sequence is target.length
'?'
marks. You also have a stamp
of lowercase letters.
On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to 10 * target.length
turns.
For example, if the initial sequence is “?????”, and your stamp is "abc"
, then you may make “abc??”, “?abc?”, “??abc” in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)
If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.
For example, if the sequence is “ababc”, and the stamp is "abc"
, then we could return the answer [0, 2]
, corresponding to the moves “?????” -> “abc??” -> “ababc”.
Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length
moves. Any answers specifying more than this number of moves will not be accepted.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
-
1 <= stamp.length <= target.length <= 1000
-
stamp
andtarget
only contain lowercase letters.
Explanation
- The last stamp will replace every characters of
stamp
on thetarget
, so we can think in a reverse way. Let’s take an example to illustrate.Stamp = "abc", Target = "ababcbc"
.
1 |
|
- We will go through the whole
Target
string to find if there exists any substring equals toStamp
. And then replace the whole substring with*
. We can see in the step 1, we replace substringabc
with***
. Then we keep doing the same thing. In the step 2, we replace substring*bc
to***
.*
can match to any character because*
will be override by the next stamp. Finally we get the result and output the reversed result. When the number ofstars
equals totarget.length
, we will return the result. If during one scan, we are not able to replace even one substring with*
, directly return empty array.
Solution
1 |
|
Source: https://leetcode.com/problems/stamping-the-sequence/discuss/201546/12ms-Java-Solution-Beats-100