task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
maximum-product-of-three-numbers | def maximumProduct(nums: List[int]) -> int:
"""
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
>>> maximumProduct(nums = [1,2,3])
>>> 6
Example 2:
>>> maximumProduct(nums = [1,2,3,4])
>>> 24
Example 3:
>>> maximumProduct(nums = [-1,-2,-3])
>>> -6
"""
|
k-inverse-pairs-array | def kInversePairs(n: int, k: int) -> int:
"""
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].
Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.
Example 1:
>>> kInversePairs(n = 3, k = 0)
>>> 1
Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
Example 2:
>>> kInversePairs(n = 3, k = 1)
>>> 2
Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
"""
|
course-schedule-iii | def scheduleCourse(courses: List[List[int]]) -> int:
"""
There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.
You will start on the 1st day and you cannot take two or more courses simultaneously.
Return the maximum number of courses that you can take.
Example 1:
>>> scheduleCourse(courses = [[100,200],[200,1300],[1000,1250],[2000,3200]])
>>> 3
Explanation:
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
Example 2:
>>> scheduleCourse(courses = [[1,2]])
>>> 1
Example 3:
>>> scheduleCourse(courses = [[3,2],[4,3]])
>>> 0
"""
|
smallest-range-covering-elements-from-k-lists | def smallestRange(nums: List[List[int]]) -> List[int]:
"""
You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.
Example 1:
>>> smallestRange(nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]])
>>> [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].
Example 2:
>>> smallestRange(nums = [[1,2,3],[1,2,3],[1,2,3]])
>>> [1,1]
"""
|
sum-of-square-numbers | def judgeSquareSum(c: int) -> bool:
"""
Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
>>> judgeSquareSum(c = 5)
>>> true
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
>>> judgeSquareSum(c = 3)
>>> false
"""
|
find-the-derangement-of-an-array | def findDerangement(n: int) -> int:
"""
In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.
You are given an integer n. There is originally an array consisting of n integers from 1 to n in ascending order, return the number of derangements it can generate. Since the answer may be huge, return it modulo 109 + 7.
Example 1:
>>> findDerangement(n = 3)
>>> 2
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Example 2:
>>> findDerangement(n = 2)
>>> 1
"""
|
exclusive-time-of-functions | def exclusiveTime(n: int, logs: List[str]) -> List[int]:
"""
On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.
Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.
Example 1:
>>> exclusiveTime(n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"])
>>> [3,4]
Explanation:
Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.
Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.
Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.
So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.
Example 2:
>>> exclusiveTime(n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"])
>>> [8]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls itself again.
Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.
Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.
So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.
Example 3:
>>> exclusiveTime(n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"])
>>> [7,1]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls function 1.
Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.
Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time.
So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.
"""
|
average-of-levels-in-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfLevels(root: Optional[TreeNode]) -> List[float]:
"""
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:
>>> __init__(root = [3,9,20,null,null,15,7])
>>> [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].
Example 2:
>>> __init__(root = [3,9,20,15,7])
>>> [3.00000,14.50000,11.00000]
"""
|
shopping-offers | def shoppingOffers(price: List[int], special: List[List[int]], needs: List[int]) -> int:
"""
In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
>>> shoppingOffers(price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2])
>>> 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Example 2:
>>> shoppingOffers(price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1])
>>> 11
Explanation: The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
"""
|
decode-ways-ii | def numDecodings(s: str) -> int:
"""
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> numDecodings(s = "*")
>>> 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "*".
Example 2:
>>> numDecodings(s = "1*")
>>> 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Example 3:
>>> numDecodings(s = "2*")
>>> 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
"""
|
solve-the-equation | def solveEquation(equation: str) -> str:
"""
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.
Example 1:
>>> solveEquation(equation = "x+5-3+x=6+x-2")
>>> "x=2"
Example 2:
>>> solveEquation(equation = "x=x")
>>> "Infinite solutions"
Example 3:
>>> solveEquation(equation = "2x=x")
>>> "x=0"
"""
|
maximum-average-subarray-i | def findMaxAverage(nums: List[int], k: int) -> float:
"""
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is 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:
>>> findMaxAverage(nums = [1,12,-5,-6,50,3], k = 4)
>>> 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
>>> findMaxAverage(nums = [5], k = 1)
>>> 5.00000
"""
|
maximum-average-subarray-ii | def findMaxAverage(nums: List[int], k: int) -> float:
"""
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:
>>> findMaxAverage(nums = [1,12,-5,-6,50,3], k = 4)
>>> 12.75000
Explanation:
- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75
- When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8
- When the length is 6, averages are [9.16667] and the maximum average is 9.16667
The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75
Note that we do not consider the subarrays of length < 4.
Example 2:
>>> findMaxAverage(nums = [5], k = 1)
>>> 5.00000
"""
|
set-mismatch | def findErrorNums(nums: List[int]) -> List[int]:
"""
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:
>>> findErrorNums(nums = [1,2,2,4])
>>> [2,3]
Example 2:
>>> findErrorNums(nums = [1,1])
>>> [1,2]
"""
|
maximum-length-of-pair-chain | def findLongestChain(pairs: List[List[int]]) -> int:
"""
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
>>> findLongestChain(pairs = [[1,2],[2,3],[3,4]])
>>> 2
Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
>>> findLongestChain(pairs = [[1,2],[7,8],[4,5]])
>>> 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
"""
|
palindromic-substrings | def countSubstrings(s: str) -> int:
"""
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
>>> countSubstrings(s = "abc")
>>> 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
>>> countSubstrings(s = "aaa")
>>> 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
"""
|
replace-words | def replaceWords(dictionary: List[str], sentence: str) -> str:
"""
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
>>> replaceWords(dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery")
>>> "the cat was rat by the bat"
Example 2:
>>> replaceWords(dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs")
>>> "a a b c"
"""
|
dota2-senate | def predictPartyVictory(senate: str) -> str:
"""
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".
Example 1:
>>> predictPartyVictory(senate = "RD")
>>> "Radiant"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
>>> predictPartyVictory(senate = "RDD")
>>> "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in round 1.
And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
"""
|
2-keys-keyboard | def minSteps(n: int) -> int:
"""
There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.
Example 1:
>>> minSteps(n = 3)
>>> 3
Explanation: Initially, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
Example 2:
>>> minSteps(n = 1)
>>> 0
"""
|
4-keys-keyboard | def maxA(n: int) -> int:
"""
Imagine you have a special keyboard with the following keys:
A: Print one 'A' on the screen.
Ctrl-A: Select the whole screen.
Ctrl-C: Copy selection to buffer.
Ctrl-V: Print buffer on screen appending it after what has already been printed.
Given an integer n, return the maximum number of 'A' you can print on the screen with at most n presses on the keys.
Example 1:
>>> maxA(n = 3)
>>> 3
Explanation: We can at most get 3 A's on screen by pressing the following key sequence:
A, A, A
Example 2:
>>> maxA(n = 7)
>>> 9
Explanation: We can at most get 9 A's on screen by pressing following key sequence:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
"""
|
two-sum-iv-input-is-a-bst | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(root: Optional[TreeNode], k: int) -> bool:
"""
Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.
Example 1:
>>> __init__(root = [5,3,6,2,4,null,7], k = 9)
>>> true
Example 2:
>>> __init__(root = [5,3,6,2,4,null,7], k = 28)
>>> false
"""
|
maximum-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(nums: List[int]) -> Optional[TreeNode]:
"""
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
Example 1:
>>> __init__(nums = [3,2,1,6,0,5])
>>> [6,3,5,null,2,0,null,null,1]
Explanation: The recursive calls are as follow:
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
- The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
- Empty array, so no child.
- The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
Example 2:
>>> __init__(nums = [3,2,1])
>>> [3,null,2,null,1]
"""
|
print-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def printTree(root: Optional[TreeNode]) -> List[List[str]]:
"""
Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns n should be equal to 2height+1 - 1.
Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
Continue this process until all the nodes in the tree have been placed.
Any empty cells should contain the empty string "".
Return the constructed matrix res.
Example 1:
>>> __init__(root = [1,2])
>>>
[["","1",""],
["2","",""]]
Example 2:
>>> __init__(root = [1,2,3,null,4])
>>>
[["","","","1","","",""],
["","2","","","","3",""],
["","","4","","","",""]]
"""
|
coin-path | def cheapestJump(coins: List[int], maxJump: int) -> List[int]:
"""
You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can jump to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you visit index i. In addition to that, if you are currently at index i, you can only jump to any index i + k where i + k <= n and k is a value in the range [1, maxJump].
You are initially positioned at index 1 (coins[1] is not -1). You want to find the path that reaches index n with the minimum cost.
Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the lexicographically smallest such path. If it is not possible to reach index n, return an empty array.
A path p1 = [Pa1, Pa2, ..., Pax] of length x is lexicographically smaller than p2 = [Pb1, Pb2, ..., Pbx] of length y, if and only if at the first j where Paj and Pbj differ, Paj < Pbj; when no such j exists, then x < y.
Example 1:
>>> cheapestJump(coins = [1,2,4,-1,2], maxJump = 2)
>>> [1,3,5]
Example 2:
>>> cheapestJump(coins = [1,2,4,-1,2], maxJump = 1)
>>> []
"""
|
robot-return-to-origin | def judgeCircle(moves: str) -> bool:
"""
There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).
Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.
Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
Example 1:
>>> judgeCircle(moves = "UD")
>>> true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
Example 2:
>>> judgeCircle(moves = "LL")
>>> false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
"""
|
find-k-closest-elements | def findClosestElements(arr: List[int], k: int, x: int) -> List[int]:
"""
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
>>> findClosestElements(arr = [1,2,3,4,5], k = 4, x = 3)
>>> [1,2,3,4]
Example 2:
>>> findClosestElements(arr = [1,1,2,3,4,5], k = 4, x = -1)
>>> [1,1,2,3]
"""
|
split-array-into-consecutive-subsequences | def isPossible(nums: List[int]) -> bool:
"""
You are given an integer array nums that is sorted in non-decreasing order.
Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:
Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
All subsequences have a length of 3 or more.
Return true if you can split nums according to the above conditions, or false otherwise.
A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).
Example 1:
>>> isPossible(nums = [1,2,3,3,4,5])
>>> true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5
Example 2:
>>> isPossible(nums = [1,2,3,3,4,4,5,5])
>>> true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5
Example 3:
>>> isPossible(nums = [1,2,3,4,4,5])
>>> false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
"""
|
remove-9 | def newInteger(n: int) -> int:
"""
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...].
Given an integer n, return the nth (1-indexed) integer in the new sequence.
Example 1:
>>> newInteger(n = 9)
>>> 10
Example 2:
>>> newInteger(n = 10)
>>> 11
"""
|
image-smoother | def imageSmoother(img: List[List[int]]) -> List[List[int]]:
"""
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.
Example 1:
>>> imageSmoother(img = [[1,1,1],[1,0,1],[1,1,1]])
>>> [[0,0,0],[0,0,0],[0,0,0]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Example 2:
>>> imageSmoother(img = [[100,200,100],[200,50,200],[100,200,100]])
>>> [[137,141,137],[141,138,141],[137,141,137]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
"""
|
maximum-width-of-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is guaranteed that the answer will in the range of a 32-bit signed integer.
Example 1:
>>> __init__(root = [1,3,2,5,3,null,9])
>>> 4
Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
Example 2:
>>> __init__(root = [1,3,2,5,null,null,9,6,null,7])
>>> 7
Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
Example 3:
>>> __init__(root = [1,3,2,5])
>>> 2
Explanation: The maximum width exists in the second level with length 2 (3,2).
"""
|
equal-tree-partition | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEqualTree(root: Optional[TreeNode]) -> bool:
"""
Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.
Example 1:
>>> __init__(root = [5,10,10,null,null,2,3])
>>> true
Example 2:
>>> __init__(root = [1,2,10,null,null,2,20])
>>> false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
"""
|
strange-printer | def strangePrinter(s: str) -> int:
"""
There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
>>> strangePrinter(s = "aaabbb")
>>> 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
>>> strangePrinter(s = "aba")
>>> 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
"""
|
non-decreasing-array | def checkPossibility(nums: List[int]) -> bool:
"""
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
>>> checkPossibility(nums = [4,2,3])
>>> true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
>>> checkPossibility(nums = [4,2,1])
>>> false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
"""
|
path-sum-iv | def pathSum(nums: List[int]) -> int:
"""
If the depth of a tree is smaller than 5, then this tree can be represented by an array of three-digit integers. You are given an ascending array nums consisting of three-digit integers representing a binary tree with a depth smaller than 5, where for each integer:
The hundreds digit represents the depth d of this node, where 1 <= d <= 4.
The tens digit represents the position p of this node within its level, where 1 <= p <= 8, corresponding to its position in a full binary tree.
The units digit represents the value v of this node, where 0 <= v <= 9.
Return the sum of all paths from the root towards the leaves.
It is guaranteed that the given array represents a valid connected binary tree.
Example 1:
>>> pathSum(nums = [113,215,221])
>>> 12
Explanation:
The tree that the list represents is shown.
The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:
>>> pathSum(nums = [113,221])
>>> 4
Explanation:
The tree that the list represents is shown.
The path sum is (3 + 1) = 4.
"""
|
beautiful-arrangement-ii | def constructArray(n: int, k: int) -> List[int]:
"""
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
Return the list answer. If there multiple valid answers, return any of them.
Example 1:
>>> constructArray(n = 3, k = 1)
>>> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
Example 2:
>>> constructArray(n = 3, k = 2)
>>> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
"""
|
kth-smallest-number-in-multiplication-table | def findKthNumber(m: int, n: int, k: int) -> int:
"""
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).
Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.
Example 1:
>>> findKthNumber(m = 3, n = 3, k = 5)
>>> 3
Explanation: The 5th smallest number is 3.
Example 2:
>>> findKthNumber(m = 2, n = 3, k = 6)
>>> 6
Explanation: The 6th smallest number is 6.
"""
|
trim-a-binary-search-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
"""
Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
>>> __init__(root = [1,0,2], low = 1, high = 2)
>>> [1,null,2]
Example 2:
>>> __init__(root = [3,0,4,null,2,null,null,1], low = 1, high = 3)
>>> [3,2,null,1]
"""
|
maximum-swap | def maximumSwap(num: int) -> int:
"""
You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
>>> maximumSwap(num = 2736)
>>> 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
>>> maximumSwap(num = 9973)
>>> 9973
Explanation: No swap.
"""
|
second-minimum-node-in-a-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(root: Optional[TreeNode]) -> int:
"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
>>> __init__(root = [2,2,5,null,null,5,7])
>>> 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
>>> __init__(root = [2,2,2])
>>> -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
"""
|
bulb-switcher-ii | def flipLights(n: int, presses: int) -> int:
"""
There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:
Button 1: Flips the status of all the bulbs.
Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...).
Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...).
Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...).
You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.
Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.
Example 1:
>>> flipLights(n = 1, presses = 1)
>>> 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
Example 2:
>>> flipLights(n = 2, presses = 1)
>>> 3
Explanation: Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
Example 3:
>>> flipLights(n = 3, presses = 1)
>>> 4
Explanation: Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
"""
|
number-of-longest-increasing-subsequence | def findNumberOfLIS(nums: List[int]) -> int:
"""
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
>>> findNumberOfLIS(nums = [1,3,5,4,7])
>>> 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
>>> findNumberOfLIS(nums = [2,2,2,2,2])
>>> 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
"""
|
longest-continuous-increasing-subsequence | def findLengthOfLCIS(nums: List[int]) -> int:
"""
Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example 1:
>>> findLengthOfLCIS(nums = [1,3,5,4,7])
>>> 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
>>> findLengthOfLCIS(nums = [2,2,2,2,2])
>>> 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
"""
|
cut-off-trees-for-golf-event | def cutOffTree(forest: List[List[int]]) -> int:
"""
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:
0 means the cell cannot be walked through.
1 represents an empty cell that can be walked through.
A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.
In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.
You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).
Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.
Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.
Example 1:
>>> cutOffTree(forest = [[1,2,3],[0,0,4],[7,6,5]])
>>> 6
Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
Example 2:
>>> cutOffTree(forest = [[1,2,3],[0,0,0],[7,6,5]])
>>> -1
Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.
Example 3:
>>> cutOffTree(forest = [[2,3,4],[0,0,5],[8,7,6]])
>>> 6
Explanation: You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
"""
|
valid-parenthesis-string | def checkValidString(s: str) -> bool:
"""
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
Example 1:
>>> checkValidString(s = "()")
>>> true
Example 2:
>>> checkValidString(s = "(*)")
>>> true
Example 3:
>>> checkValidString(s = "(*))")
>>> true
"""
|
24-game | def judgePoint24(cards: List[int]) -> bool:
"""
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.
You are restricted with the following rules:
The division operator '/' represents real division, not integer division.
For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator.
For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed.
You cannot concatenate numbers together
For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid.
Return true if you can get such expression that evaluates to 24, and false otherwise.
Example 1:
>>> judgePoint24(cards = [4,1,8,7])
>>> true
Explanation: (8-4) * (7-1) = 24
Example 2:
>>> judgePoint24(cards = [1,2,1,2])
>>> false
"""
|
valid-palindrome-ii | def validPalindrome(s: str) -> bool:
"""
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
>>> validPalindrome(s = "aba")
>>> true
Example 2:
>>> validPalindrome(s = "abca")
>>> true
Explanation: You could delete the character 'c'.
Example 3:
>>> validPalindrome(s = "abc")
>>> false
"""
|
next-closest-time | def nextClosestTime(time: str) -> str:
"""
Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.
Example 1:
>>> nextClosestTime(time = "19:34")
>>> "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.
It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example 2:
>>> nextClosestTime(time = "23:59")
>>> "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22.
It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.
"""
|
baseball-game | def calPoints(operations: List[str]) -> int:
"""
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
An integer x.
Record a new score of x.
'+'.
Record a new score that is the sum of the previous two scores.
'D'.
Record a new score that is the double of the previous score.
'C'.
Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
Example 1:
>>> calPoints(ops = ["5","2","C","D","+"])
>>> 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
Example 2:
>>> calPoints(ops = ["5","-2","4","C","D","9","+","+"])
>>> 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
Example 3:
>>> calPoints(ops = ["1","C"])
>>> 0
Explanation:
"1" - Add 1 to the record, record is now [1].
"C" - Invalidate and remove the previous score, record is now [].
Since the record is empty, the total sum is 0.
"""
|
k-empty-slots | def kEmptySlots(bulbs: List[int], k: int) -> int:
"""
You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. We turn on exactly one bulb every day until all bulbs are on after n days.
You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day, we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.
Given an integer k, return the minimum day number such that there exists two turned on bulbs that have exactly k bulbs between them that are all turned off. If there isn't such day, return -1.
Example 1:
>>> kEmptySlots(bulbs = [1,3,2], k = 1)
>>> 2
Explanation:
On the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]
On the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]
On the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]
We return 2 because on the second day, there were two on bulbs with one off bulb between them.
Example 2:
>>> kEmptySlots(bulbs = [1,2,3], k = 1)
>>> -1
"""
|
redundant-connection | def findRedundantConnection(edges: List[List[int]]) -> List[int]:
"""
In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
>>> findRedundantConnection(edges = [[1,2],[1,3],[2,3]])
>>> [2,3]
Example 2:
>>> findRedundantConnection(edges = [[1,2],[2,3],[3,4],[1,4],[1,5]])
>>> [1,4]
"""
|
redundant-connection-ii | def findRedundantDirectedConnection(edges: List[List[int]]) -> List[int]:
"""
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.
Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
Example 1:
>>> findRedundantDirectedConnection(edges = [[1,2],[1,3],[2,3]])
>>> [2,3]
Example 2:
>>> findRedundantDirectedConnection(edges = [[1,2],[2,3],[3,4],[4,1],[1,5]])
>>> [4,1]
"""
|
repeated-string-match | def repeatedStringMatch(a: str, b: str) -> int:
"""
Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
Example 1:
>>> repeatedStringMatch(a = "abcd", b = "cdabcdab")
>>> 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Example 2:
>>> repeatedStringMatch(a = "a", b = "aa")
>>> 2
"""
|
longest-univalue-path | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def longestUnivaluePath(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
>>> __init__(root = [5,4,5,1,1,null,5])
>>> 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Example 2:
>>> __init__(root = [1,4,5,4,4,null,5])
>>> 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).
"""
|
knight-probability-in-chessboard | def knightProbability(n: int, k: int, row: int, column: int) -> float:
"""
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly k moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.
Example 1:
>>> knightProbability(n = 3, k = 2, row = 0, column = 0)
>>> 0.06250
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
Example 2:
>>> knightProbability(n = 1, k = 0, row = 0, column = 0)
>>> 1.00000
"""
|
maximum-sum-of-3-non-overlapping-subarrays | def maxSumOfThreeSubarrays(nums: List[int], k: int) -> List[int]:
"""
Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example 1:
>>> maxSumOfThreeSubarrays(nums = [1,2,1,2,6,7,5,1], k = 2)
>>> [0,3,5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically smaller.
Example 2:
>>> maxSumOfThreeSubarrays(nums = [1,2,1,2,1,2,1,2,1], k = 2)
>>> [0,2,4]
"""
|
stickers-to-spell-word | def minStickers(stickers: List[str], target: str) -> int:
"""
We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
>>> minStickers(stickers = ["with","example","science"], target = "thehat")
>>> 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
>>> minStickers(stickers = ["notice","possible"], target = "basicbasic")
>>> -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
"""
|
top-k-frequent-words | def topKFrequent(words: List[str], k: int) -> List[str]:
"""
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
>>> topKFrequent(words = ["i","love","leetcode","i","love","coding"], k = 2)
>>> ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
>>> topKFrequent(words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4)
>>> ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
"""
|
binary-number-with-alternating-bits | def hasAlternatingBits(n: int) -> bool:
"""
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
>>> hasAlternatingBits(n = 5)
>>> true
Explanation: The binary representation of 5 is: 101
Example 2:
>>> hasAlternatingBits(n = 7)
>>> false
Explanation: The binary representation of 7 is: 111.
Example 3:
>>> hasAlternatingBits(n = 11)
>>> false
Explanation: The binary representation of 11 is: 1011.
"""
|
number-of-distinct-islands | def numDistinctIslands(grid: List[List[int]]) -> int:
"""
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.
Return the number of distinct islands.
Example 1:
>>> numDistinctIslands(grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]])
>>> 1
Example 2:
>>> numDistinctIslands(grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]])
>>> 3
"""
|
max-area-of-island | def maxAreaOfIsland(grid: List[List[int]]) -> int:
"""
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Example 1:
>>> maxAreaOfIsland(grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]])
>>> 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
>>> maxAreaOfIsland(grid = [[0,0,0,0,0,0,0,0]])
>>> 0
"""
|
count-binary-substrings | def countBinarySubstrings(s: str) -> int:
"""
Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
>>> countBinarySubstrings(s = "00110011")
>>> 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
>>> countBinarySubstrings(s = "10101")
>>> 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
"""
|
degree-of-an-array | def findShortestSubArray(nums: List[int]) -> int:
"""
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
>>> findShortestSubArray(nums = [1,2,2,3,1])
>>> 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
>>> findShortestSubArray(nums = [1,2,2,3,1,4,2])
>>> 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
"""
|
partition-to-k-equal-sum-subsets | def canPartitionKSubsets(nums: List[int], k: int) -> bool:
"""
Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
>>> canPartitionKSubsets(nums = [4,3,2,3,5,2,1], k = 4)
>>> true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
>>> canPartitionKSubsets(nums = [1,2,3,4], k = 3)
>>> false
"""
|
falling-squares | def fallingSquares(positions: List[List[int]]) -> List[int]:
"""
There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
Example 1:
>>> fallingSquares(positions = [[1,2],[2,3],[6,1]])
>>> [2,5,5]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of [2, 5, 5].
Example 2:
>>> fallingSquares(positions = [[100,100],[200,100]])
>>> [100,100]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of [100, 100].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
"""
|
search-in-a-binary-search-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
"""
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
Example 1:
>>> __init__(root = [4,2,7,1,3], val = 2)
>>> [2,1,3]
Example 2:
>>> __init__(root = [4,2,7,1,3], val = 5)
>>> []
"""
|
insert-into-a-binary-search-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
"""
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Example 1:
>>> __init__(root = [4,2,7,1,3], val = 5)
>>> [4,2,7,1,3,5]
Explanation: Another accepted tree is:
Example 2:
>>> __init__(root = [40,20,60,10,30,50,70], val = 25)
>>> [40,20,60,10,30,50,70,null,null,25]
Example 3:
>>> __init__(root = [4,2,7,1,3,null,null,null,null,null,null], val = 5)
>>> [4,2,7,1,3,5]
"""
|
binary-search | def search(nums: List[int], target: int) -> int:
"""
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
>>> search(nums = [-1,0,3,5,9,12], target = 9)
>>> 4
Explanation: 9 exists in nums and its index is 4
Example 2:
>>> search(nums = [-1,0,3,5,9,12], target = 2)
>>> -1
Explanation: 2 does not exist in nums so return -1
"""
|
to-lower-case | def toLowerCase(s: str) -> str:
"""
Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
Example 1:
>>> toLowerCase(s = "Hello")
>>> "hello"
Example 2:
>>> toLowerCase(s = "here")
>>> "here"
Example 3:
>>> toLowerCase(s = "LOVELY")
>>> "lovely"
"""
|
number-of-distinct-islands-ii | def numDistinctIslands2(grid: List[List[int]]) -> int:
"""
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).
Return the number of distinct islands.
Example 1:
>>> numDistinctIslands2(grid = [[1,1,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,1,1]])
>>> 1
Explanation: The two islands are considered the same because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.
Example 2:
>>> numDistinctIslands2(grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]])
>>> 1
"""
|
minimum-ascii-delete-sum-for-two-strings | def minimumDeleteSum(s1: str, s2: str) -> int:
"""
Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
>>> minimumDeleteSum(s1 = "sea", s2 = "eat")
>>> 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
>>> minimumDeleteSum(s1 = "delete", s2 = "leet")
>>> 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d] + 101[e] + 101[e] to the sum.
Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
"""
|
subarray-product-less-than-k | def numSubarrayProductLessThanK(nums: List[int], k: int) -> int:
"""
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
>>> numSubarrayProductLessThanK(nums = [10,5,2,6], k = 100)
>>> 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
>>> numSubarrayProductLessThanK(nums = [1,2,3], k = 0)
>>> 0
"""
|
best-time-to-buy-and-sell-stock-with-transaction-fee | def maxProfit(prices: List[int], fee: int) -> int:
"""
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).
The transaction fee is only charged once for each stock purchase and sale.
Example 1:
>>> maxProfit(prices = [1,3,2,8,4,9], fee = 2)
>>> 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
>>> maxProfit(prices = [1,3,7,5,10,3], fee = 3)
>>> 6
"""
|
1-bit-and-2-bit-characters | def isOneBitCharacter(bits: List[int]) -> bool:
"""
We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Example 1:
>>> isOneBitCharacter(bits = [1,0,0])
>>> true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
Example 2:
>>> isOneBitCharacter(bits = [1,1,1,0])
>>> false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
"""
|
maximum-length-of-repeated-subarray | def findLength(nums1: List[int], nums2: List[int]) -> int:
"""
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Example 1:
>>> findLength(nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7])
>>> 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
>>> findLength(nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0])
>>> 5
Explanation: The repeated subarray with maximum length is [0,0,0,0,0].
"""
|
find-k-th-smallest-pair-distance | def smallestDistancePair(nums: List[int], k: int) -> int:
"""
The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
>>> smallestDistancePair(nums = [1,3,1], k = 1)
>>> 0
Explanation: Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
>>> smallestDistancePair(nums = [1,1,1], k = 2)
>>> 0
Example 3:
>>> smallestDistancePair(nums = [1,6,1], k = 3)
>>> 5
"""
|
longest-word-in-dictionary | def longestWord(words: List[str]) -> str:
"""
Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
>>> longestWord(words = ["w","wo","wor","worl","world"])
>>> "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
>>> longestWord(words = ["a","banana","app","appl","ap","apply","apple"])
>>> "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
"""
|
accounts-merge | def accountsMerge(accounts: List[List[str]]) -> List[List[str]]:
"""
Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
>>> accountsMerge(accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]])
>>> [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Example 2:
>>> accountsMerge(accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]])
>>> [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
"""
|
remove-comments | def removeComments(source: List[str]) -> List[str]:
"""
Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\
'.
In C++, there are two types of comments, line comments, and block comments.
The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
For example, if the string "//" occurs in a block comment, it is ignored.
Similarly, if the string "/*" occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
For example, source = "string s = "/* Not a comment. */";" will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return the source code in the same format.
Example 1:
>>> removeComments(source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"])
>>> ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
Explanation: The line by line code is visualized as below:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
Example 2:
>>> removeComments(source = ["a/*comment", "line", "more_comment*/b"])
>>> ["ab"]
Explanation: The original source string is "a/*comment\
line\
more_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].
"""
|
candy-crush | def candyCrush(board: List[List[int]]) -> List[List[int]]:
"""
This question is about implementing a basic elimination algorithm for Candy Crush.
Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty.
The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty.
After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary.
After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return the stable board.
Example 1:
>>> candyCrush(board = [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]])
>>> [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
Example 2:
>>> candyCrush(board = [[1,3,5,5,2],[3,4,3,3,1],[3,2,4,5,2],[2,4,4,5,5],[1,4,4,1,1]])
>>> [[1,3,0,0,0],[3,4,0,5,2],[3,2,0,3,1],[2,4,0,5,2],[1,4,3,1,1]]
"""
|
find-pivot-index | def pivotIndex(nums: List[int]) -> int:
"""
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example 1:
>>> pivotIndex(nums = [1,7,3,6,5,6])
>>> 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
>>> pivotIndex(nums = [1,2,3])
>>> -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
>>> pivotIndex(nums = [2,1,-1])
>>> 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
"""
|
number-of-atoms | def countOfAtoms(formula: str) -> str:
"""
Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.
Two formulas are concatenated together to produce another formula.
For example, "H2O2He3Mg4" is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
For example, "(H2O2)" and "(H2O2)3" are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
Example 1:
>>> countOfAtoms(formula = "H2O")
>>> "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
>>> countOfAtoms(formula = "Mg(OH)2")
>>> "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
>>> countOfAtoms(formula = "K4(ON(SO3)2)2")
>>> "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
"""
|
minimum-window-subsequence | def minWindow(s1: str, s2: str) -> str:
"""
Given strings s1 and s2, return the minimum contiguous substring part of s1, so that s2 is a subsequence of the part.
If there is no such window in s1 that covers all characters in s2, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
>>> minWindow(s1 = "abcdebdde", s2 = "bde")
>>> "bcde"
Explanation:
"bcde" is the answer because it occurs before "bdde" which has the same length.
"deb" is not a smaller window because the elements of s2 in the window must occur in order.
Example 2:
>>> minWindow(s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u")
>>> ""
"""
|
self-dividing-numbers | def selfDividingNumbers(left: int, right: int) -> List[int]:
"""
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right] (both inclusive).
Example 1:
>>> selfDividingNumbers(left = 1, right = 22)
>>> [1,2,3,4,5,6,7,8,9,11,12,15,22]
Example 2:
>>> selfDividingNumbers(left = 47, right = 85)
>>> [48,55,66,77]
"""
|
count-different-palindromic-subsequences | def countPalindromicSubsequences(s: str) -> int:
"""
Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.
Example 1:
>>> countPalindromicSubsequences(s = "bccb")
>>> 6
Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
Example 2:
>>> countPalindromicSubsequences(s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba")
>>> 104860361
Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
"""
|
flood-fill | def floodFill(image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
"""
You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill:
Begin with the starting pixel and change its color to color.
Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
The process stops when there are no more adjacent pixels of the original color to update.
Return the modified image after performing the flood fill.
Example 1:
>>> floodFill(image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2)
>>> [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.
Example 2:
>>> floodFill(image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0)
>>> [[0,0,0],[0,0,0]]
Explanation:
The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.
"""
|
sentence-similarity | def areSentencesSimilar(sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
"""
We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].
Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.
Return true if sentence1 and sentence2 are similar, or false if they are not similar.
Two sentences are similar if:
They have the same length (i.e., the same number of words)
sentence1[i] and sentence2[i] are similar.
Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words a and b are similar, and the words b and c are similar, a and c are not necessarily similar.
Example 1:
>>> areSentencesSimilar(sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]])
>>> true
Explanation: The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
Example 2:
>>> areSentencesSimilar(sentence1 = ["great"], sentence2 = ["great"], similarPairs = [])
>>> true
Explanation: A word is similar to itself.
Example 3:
>>> areSentencesSimilar(sentence1 = ["great"], sentence2 = ["doubleplus","good"], similarPairs = [["great","doubleplus"]])
>>> false
Explanation: As they don't have the same length, we return false.
"""
|
asteroid-collision | def asteroidCollision(asteroids: List[int]) -> List[int]:
"""
We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
>>> asteroidCollision(asteroids = [5,10,-5])
>>> [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
>>> asteroidCollision(asteroids = [8,-8])
>>> []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
>>> asteroidCollision(asteroids = [10,2,-5])
>>> [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
"""
|
parse-lisp-expression | def evaluate(expression: str) -> int:
"""
You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
(An integer could be positive or negative.)
A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.
An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.
A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names.
Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
Example 1:
>>> evaluate(expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))")
>>> 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
Example 2:
>>> evaluate(expression = "(let x 3 x 2 x)")
>>> 2
Explanation: Assignment in let statements is processed sequentially.
Example 3:
>>> evaluate(expression = "(let x 1 y 2 x (add x y) (add x y))")
>>> 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
"""
|
sentence-similarity-ii | def areSentencesSimilarTwo(sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
"""
We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].
Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.
Return true if sentence1 and sentence2 are similar, or false if they are not similar.
Two sentences are similar if:
They have the same length (i.e., the same number of words)
sentence1[i] and sentence2[i] are similar.
Notice that a word is always similar to itself, also notice that the similarity relation is transitive. For example, if the words a and b are similar, and the words b and c are similar, then a and c are similar.
Example 1:
>>> areSentencesSimilarTwo(sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","good"],["fine","good"],["drama","acting"],["skills","talent"]])
>>> true
Explanation: The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
Example 2:
>>> areSentencesSimilarTwo(sentence1 = ["I","love","leetcode"], sentence2 = ["I","love","onepiece"], similarPairs = [["manga","onepiece"],["platform","anime"],["leetcode","platform"],["anime","manga"]])
>>> true
Explanation: "leetcode" --> "platform" --> "anime" --> "manga" --> "onepiece".
Since "leetcode is similar to "onepiece" and the first two words are the same, the two sentences are similar.
Example 3:
>>> areSentencesSimilarTwo(sentence1 = ["I","love","leetcode"], sentence2 = ["I","love","onepiece"], similarPairs = [["manga","hunterXhunter"],["platform","anime"],["leetcode","platform"],["anime","manga"]])
>>> false
Explanation: "leetcode" is not similar to "onepiece".
"""
|
monotone-increasing-digits | def monotoneIncreasingDigits(n: int) -> int:
"""
An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.
Example 1:
>>> monotoneIncreasingDigits(n = 10)
>>> 9
Example 2:
>>> monotoneIncreasingDigits(n = 1234)
>>> 1234
Example 3:
>>> monotoneIncreasingDigits(n = 332)
>>> 299
"""
|
daily-temperatures | def dailyTemperatures(temperatures: List[int]) -> List[int]:
"""
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
>>> dailyTemperatures(temperatures = [73,74,75,71,69,72,76,73])
>>> [1,1,4,2,1,1,0,0]
Example 2:
>>> dailyTemperatures(temperatures = [30,40,50,60])
>>> [1,1,1,0]
Example 3:
>>> dailyTemperatures(temperatures = [30,60,90])
>>> [1,1,0]
"""
|
delete-and-earn | def deleteAndEarn(nums: List[int]) -> int:
"""
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Example 1:
>>> deleteAndEarn(nums = [3,4,2])
>>> 6
Explanation: You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
- Delete 2 to earn 2 points. nums = [].
You earn a total of 6 points.
Example 2:
>>> deleteAndEarn(nums = [2,2,3,3,3,4])
>>> 9
Explanation: You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
- Delete a 3 again to earn 3 points. nums = [3].
- Delete a 3 once more to earn 3 points. nums = [].
You earn a total of 9 points.
"""
|
cherry-pickup | def cherryPickup(grid: List[List[int]]) -> int:
"""
You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,
1 means the cell contains a cherry that you can pick up and pass through, or
-1 means the cell contains a thorn that blocks your way.
Return the maximum number of cherries you can collect by following the rules below:
Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).
After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.
When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.
If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.
Example 1:
>>> cherryPickup(grid = [[0,1,-1],[1,0,-1],[1,1,1]])
>>> 5
Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Example 2:
>>> cherryPickup(grid = [[1,1,-1],[1,-1,1],[-1,1,1]])
>>> 0
"""
|
closest-leaf-in-a-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findClosestLeaf(root: Optional[TreeNode], k: int) -> int:
"""
Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree.
Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.
Example 1:
>>> __init__(root = [1,3,2], k = 1)
>>> 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
Example 2:
>>> __init__(root = [1], k = 1)
>>> 1
Explanation: The nearest leaf node is the root node itself.
Example 3:
>>> __init__(root = [1,2,3,4,null,null,null,5,null,6], k = 2)
>>> 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
"""
|
network-delay-time | def networkDelayTime(times: List[List[int]], n: int, k: int) -> int:
"""
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Example 1:
>>> networkDelayTime(times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2)
>>> 2
Example 2:
>>> networkDelayTime(times = [[1,2,1]], n = 2, k = 1)
>>> 1
Example 3:
>>> networkDelayTime(times = [[1,2,1]], n = 2, k = 2)
>>> -1
"""
|
find-smallest-letter-greater-than-target | def nextGreatestLetter(letters: List[str], target: str) -> str:
"""
You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.
Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.
Example 1:
>>> nextGreatestLetter(letters = ["c","f","j"], target = "a")
>>> "c"
Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
Example 2:
>>> nextGreatestLetter(letters = ["c","f","j"], target = "c")
>>> "f"
Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.
Example 3:
>>> nextGreatestLetter(letters = ["x","x","y","y"], target = "z")
>>> "x"
Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].
"""
|
min-cost-climbing-stairs | def minCostClimbingStairs(cost: List[int]) -> int:
"""
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
>>> minCostClimbingStairs(cost = [10,15,20])
>>> 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
>>> minCostClimbingStairs(cost = [1,100,1,1,1,100,1,1,100,1])
>>> 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
"""
|
largest-number-at-least-twice-of-others | def dominantIndex(nums: List[int]) -> int:
"""
You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
Example 1:
>>> dominantIndex(nums = [3,6,1,0])
>>> 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
>>> dominantIndex(nums = [1,2,3,4])
>>> -1
Explanation: 4 is less than twice the value of 3, so we return -1.
"""
|
shortest-completing-word | def shortestCompletingWord(licensePlate: str, words: List[str]) -> str:
"""
Given a string licensePlate and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.
For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
Example 1:
>>> shortestCompletingWord(licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"])
>>> "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.
Example 2:
>>> shortestCompletingWord(licensePlate = "1s3 456", words = ["looks","pest","stew","show"])
>>> "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.
"""
|
contain-virus | def containVirus(isInfected: List[List[int]]) -> int:
"""
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Example 1:
>>> containVirus(isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]])
>>> 10
Explanation: There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
Example 2:
>>> containVirus(isInfected = [[1,1,1],[1,0,1],[1,1,1]])
>>> 4
Explanation: Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
Example 3:
>>> containVirus(isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]])
>>> 13
Explanation: The region on the left only builds two new walls.
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.