task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
cherry-pickup-ii
def cherryPickup(grid: List[List[int]]) -> int: """ You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Robot #1 is located at the top-left corner (0, 0), and Robot #2 is located at the top-right corner (0, cols - 1). Return the maximum number of cherries collection using both robots by following the rules below: From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1). When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell. When both robots stay in the same cell, only one takes the cherries. Both robots cannot move outside of the grid at any moment. Both robots should reach the bottom row in grid. Example 1: >>> cherryPickup(grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]) >>> 24 Explanation: Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12. Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12. Total of cherries: 12 + 12 = 24. Example 2: >>> cherryPickup(grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]) >>> 28 Explanation: Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17. Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11. Total of cherries: 17 + 11 = 28. """
maximum-product-of-two-elements-in-an-array
def maxProduct(nums: List[int]) -> int: """ Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: >>> maxProduct(nums = [3,4,5,2]) >>> 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. Example 2: >>> maxProduct(nums = [1,5,4,5]) >>> 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. Example 3: >>> maxProduct(nums = [3,7]) >>> 12 """
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
def maxArea(h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: """ You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7. Example 1: >>> maxArea(h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]) >>> 4 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. Example 2: >>> maxArea(h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]) >>> 6 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. Example 3: >>> maxArea(h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]) >>> 9 """
reorder-routes-to-make-all-paths-lead-to-the-city-zero
def minReorder(n: int, connections: List[List[int]]) -> int: """ There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 1: >>> minReorder(n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]) >>> 3 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 2: >>> minReorder(n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]) >>> 2 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 3: >>> minReorder(n = 3, connections = [[1,0],[2,0]]) >>> 0 """
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
def getProbability(balls: List[int]) -> float: """ Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct. Example 1: >>> getProbability(balls = [1,1]) >>> 1.00000 Explanation: Only 2 ways to divide the balls equally: - A ball of color 1 to box 1 and a ball of color 2 to box 2 - A ball of color 2 to box 1 and a ball of color 1 to box 2 In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1 Example 2: >>> getProbability(balls = [2,1,1]) >>> 0.66667 Explanation: We have the set of balls [1, 1, 2, 3] This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12): [1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1] After that, we add the first two balls to the first box and the second two balls to the second box. We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box. Probability is 8/12 = 0.66667 Example 3: >>> getProbability(balls = [1,2,1,2]) >>> 0.60000 Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box. Probability = 108 / 180 = 0.6 """
find-all-the-lonely-nodes
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getLonelyNodes(root: Optional[TreeNode]) -> List[int]: """ In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node. Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order. Example 1: >>> __init__(root = [1,2,3,null,4]) >>> [4] Explanation: Light blue node is the only lonely node. Node 1 is the root and is not lonely. Nodes 2 and 3 have the same parent and are not lonely. Example 2: >>> __init__(root = [7,1,4,6,null,5,3,null,null,null,null,null,2]) >>> [6,2] Explanation: Light blue nodes are lonely nodes. Please remember that order doesn't matter, [2,6] is also an acceptable answer. Example 3: >>> __init__(root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22]) >>> [77,55,33,66,44,22] Explanation: Nodes 99 and 88 share the same parent. Node 11 is the root. All other nodes are lonely. """
shuffle-the-array
def shuffle(nums: List[int], n: int) -> List[int]: """ Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\r \r Return the array in the form [x1,y1,x2,y2,...,xn,yn].\r \r  \r Example 1:\r \r \r >>> shuffle(nums = [2,5,1,3,4,7], n = 3\r) >>> [2,3,5,4,1,7] \r Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\r \r \r Example 2:\r \r \r >>> shuffle(nums = [1,2,3,4,4,3,2,1], n = 4\r) >>> [1,4,2,3,3,2,4,1]\r \r \r Example 3:\r \r \r >>> shuffle(nums = [1,1,2,2], n = 2\r) >>> [1,2,1,2]\r \r \r  \r """
the-k-strongest-values-in-an-array
def getStrongest(arr: List[int], k: int) -> List[int]: """ Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the centre of the array. If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. Return a list of the strongest k values in the array. return the answer in any arbitrary order. The centre is the middle value in an ordered integer list. More formally, if the length of the list is n, the centre is the element in position ((n - 1) / 2) in the sorted list (0-indexed). For arr = [6, -3, 7, 2, 11], n = 5 and the centre is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the centre is arr[m] where m = ((5 - 1) / 2) = 2. The centre is 6. For arr = [-7, 22, 17, 3], n = 4 and the centre is obtained by sorting the array arr = [-7, 3, 17, 22] and the centre is arr[m] where m = ((4 - 1) / 2) = 1. The centre is 3. Example 1: >>> getStrongest(arr = [1,2,3,4,5], k = 2) >>> [5,1] Explanation: Centre is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer. Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1. Example 2: >>> getStrongest(arr = [1,1,3,5,5], k = 2) >>> [5,5] Explanation: Centre is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5]. Example 3: >>> getStrongest(arr = [6,7,11,7,6,8], k = 5) >>> [11,8,6,6,7] Explanation: Centre is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7]. Any permutation of [11,8,6,6,7] is accepted. """
paint-house-iii
def minCost(houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: """ There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. Given an array houses, an m x n matrix cost and an integer target where: houses[i]: is the color of the house i, and 0 if the house is not painted yet. cost[i][j]: is the cost of paint the house i with the color j + 1. Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1. Example 1: >>> minCost(houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3) >>> 9 Explanation: Paint houses of this way [1,2,2,1,1] This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. Example 2: >>> minCost(houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3) >>> 11 Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2] This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. Cost of paint the first and last house (10 + 1) = 11. Example 3: >>> minCost(houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3) >>> -1 Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3. """
delete-n-nodes-after-m-nodes-of-a-linked-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def deleteNodes(head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]: """ You are given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way: Start with the head as the current node. Keep the first m nodes starting with the current node. Remove the next n nodes Keep repeating steps 2 and 3 until you reach the end of the list. Return the head of the modified list after removing the mentioned nodes. Example 1: >>> __init__(head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3) >>> [1,2,6,7,11,12] Explanation: Keep the first (m = 2) nodes starting from the head of the linked List (1 ->2) show in black nodes. Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes. Continue with the same procedure until reaching the tail of the Linked List. Head of the linked list after removing nodes is returned. Example 2: >>> __init__(head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3) >>> [1,5,9] Explanation: Head of linked list after removing nodes is returned. """
final-prices-with-a-special-discount-in-a-shop
def finalPrices(prices: List[int]) -> List[int]: """ You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all. Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount. Example 1: >>> finalPrices(prices = [8,4,6,2,3]) >>> [4,2,4,2,3] Explanation: For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. For items 3 and 4 you will not receive any discount at all. Example 2: >>> finalPrices(prices = [1,2,3,4,5]) >>> [1,2,3,4,5] Explanation: In this case, for all items, you will not receive any discount at all. Example 3: >>> finalPrices(prices = [10,1,1,6]) >>> [9,0,1,6] """
find-two-non-overlapping-sub-arrays-each-with-target-sum
def minSumOfLengths(arr: List[int], target: int) -> int: """ You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. Example 1: >>> minSumOfLengths(arr = [3,2,2,4,3], target = 3) >>> 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: >>> minSumOfLengths(arr = [7,3,4,7], target = 7) >>> 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: >>> minSumOfLengths(arr = [4,3,2,6,2,3,4], target = 6) >>> -1 Explanation: We have only one sub-array of sum = 6. """
allocate-mailboxes
def minDistance(houses: List[int], k: int) -> int: """ Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: >>> minDistance(houses = [1,4,8,10,20], k = 3) >>> 5 Explanation: Allocate mailboxes in position 3, 9 and 20. Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 Example 2: >>> minDistance(houses = [2,3,5,12,18], k = 2) >>> 9 Explanation: Allocate mailboxes in position 3 and 14. Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9. """
running-sum-of-1d-array
def runningSum(nums: List[int]) -> List[int]: """ Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: >>> runningSum(nums = [1,2,3,4]) >>> [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. Example 2: >>> runningSum(nums = [1,1,1,1,1]) >>> [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. Example 3: >>> runningSum(nums = [3,1,2,10,1]) >>> [3,4,6,16,17] """
least-number-of-unique-integers-after-k-removals
def findLeastNumOfUniqueInts(arr: List[int], k: int) -> int: """ Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\r \r \r \r \r  \r Example 1:\r \r \r >>> findLeastNumOfUniqueInts(arr = [5,5,4], k = 1\r) >>> 1\r Explanation: Remove the single 4, only 5 is left.\r \r Example 2:\r \r \r >>> findLeastNumOfUniqueInts(arr = [4,3,1,1,3,3,2], k = 3\r) >>> 2\r Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\r \r  \r """
minimum-number-of-days-to-make-m-bouquets
def minDays(bloomDay: List[int], m: int, k: int) -> int: """ You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1. Example 1: >>> minDays(bloomDay = [1,10,3,10,2], m = 3, k = 1) >>> 3 Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: [x, _, _, _, _] // we can only make one bouquet. After day 2: [x, _, _, _, x] // we can only make two bouquets. After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. Example 2: >>> minDays(bloomDay = [1,10,3,10,2], m = 3, k = 2) >>> -1 Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. Example 3: >>> minDays(bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3) >>> 12 Explanation: We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: [x, x, x, x, _, x, x] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: [x, x, x, x, x, x, x] It is obvious that we can make two bouquets in different ways. """
clone-binary-tree-with-random-pointer
# class Node: # def __init__(val=0, left=None, right=None, random=None): # self.val = val # self.left = left # self.right = right # self.random = random class Solution: def copyRandomBinaryTree(root: 'Optional[Node]') -> 'Optional[NodeCopy]': """ A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null. Return a deep copy of the tree. The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (in the input) where the random pointer points to, or null if it does not point to any node. You will be given the tree in class Node and you should return the cloned tree in class NodeCopy. NodeCopy class is just a clone of Node class with the same attributes and constructors. Example 1: >>> __init__(root = [[1,null],null,[4,3],[7,0]]) >>> [[1,null],null,[4,3],[7,0]] Explanation: The original binary tree is [1,null,4,7]. The random pointer of node one is null, so it is represented as [1, null]. The random pointer of node 4 is node 7, so it is represented as [4, 3] where 3 is the index of node 7 in the array representing the tree. The random pointer of node 7 is node 1, so it is represented as [7, 0] where 0 is the index of node 1 in the array representing the tree. Example 2: >>> __init__(root = [[1,4],null,[1,0],null,[1,5],[1,5]]) >>> [[1,4],null,[1,0],null,[1,5],[1,5]] Explanation: The random pointer of a node can be the node itself. Example 3: >>> __init__(root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]) >>> [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]] """
xor-operation-in-an-array
def xorOperation(n: int, start: int) -> int: """ You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. Example 1: >>> xorOperation(n = 5, start = 0) >>> 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^" corresponds to bitwise XOR operator. Example 2: >>> xorOperation(n = 4, start = 3) >>> 8 Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. """
making-file-names-unique
def getFolderNames(names: List[str]) -> List[str]: """ Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. Example 1: >>> getFolderNames(names = ["pes","fifa","gta","pes(2019)"]) >>> ["pes","fifa","gta","pes(2019)"] Explanation: Let's see how the file system creates folder names: "pes" --> not assigned before, remains "pes" "fifa" --> not assigned before, remains "fifa" "gta" --> not assigned before, remains "gta" "pes(2019)" --> not assigned before, remains "pes(2019)" Example 2: >>> getFolderNames(names = ["gta","gta(1)","gta","avalon"]) >>> ["gta","gta(1)","gta(2)","avalon"] Explanation: Let's see how the file system creates folder names: "gta" --> not assigned before, remains "gta" "gta(1)" --> not assigned before, remains "gta(1)" "gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)" "avalon" --> not assigned before, remains "avalon" Example 3: >>> getFolderNames(names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]) >>> ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"] Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)". """
avoid-flood-in-the-city
def avoidFlood(rains: List[int]) -> List[int]: """ Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake. Given an integer array rains where: rains[i] > 0 means there will be rains over the rains[i] lake. rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it. Return an array ans where: ans.length == rains.length ans[i] == -1 if rains[i] > 0. ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array. Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. Example 1: >>> avoidFlood(rains = [1,2,3,4]) >>> [-1,-1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day full lakes are [1,2,3] After the fourth day full lakes are [1,2,3,4] There's no day to dry any lake and there is no flood in any lake. Example 2: >>> avoidFlood(rains = [1,2,0,0,2,1]) >>> [-1,-1,2,1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day, we dry lake 2. Full lakes are [1] After the fourth day, we dry lake 1. There is no full lakes. After the fifth day, full lakes are [2]. After the sixth day, full lakes are [1,2]. It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario. Example 3: >>> avoidFlood(rains = [1,2,0,1,2]) >>> [] Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day. After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood. """
find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree
def findCriticalAndPseudoCriticalEdges(n: int, edges: List[List[int]]) -> List[List[int]]: """ Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. Example 1: >>> findCriticalAndPseudoCriticalEdges(n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]) >>> [[0,1],[2,3,4,5]] Explanation: The figure above describes the graph. The following figure shows all the possible MSTs: Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. Example 2: >>> findCriticalAndPseudoCriticalEdges(n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]) >>> [[],[0,1,2,3]] Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical. """
average-salary-excluding-the-minimum-and-maximum-salary
def average(salary: List[int]) -> float: """ You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. Example 1: >>> average(salary = [4000,3000,1000,2000]) >>> 2500.00000 Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500 Example 2: >>> average(salary = [1000,2000,3000]) >>> 2000.00000 Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively. Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 """
the-kth-factor-of-n
def kthFactor(n: int, k: int) -> int: """ You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. Example 1: >>> kthFactor(n = 12, k = 3) >>> 3 Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3. Example 2: >>> kthFactor(n = 7, k = 2) >>> 7 Explanation: Factors list is [1, 7], the 2nd factor is 7. Example 3: >>> kthFactor(n = 4, k = 4) >>> -1 Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1. """
longest-subarray-of-1s-after-deleting-one-element
def longestSubarray(nums: List[int]) -> int: """ Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. Example 1: >>> longestSubarray(nums = [1,1,0,1]) >>> 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: >>> longestSubarray(nums = [0,1,1,1,0,1,1,0,1]) >>> 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: >>> longestSubarray(nums = [1,1,1]) >>> 2 Explanation: You must delete one element. """
parallel-courses-ii
def minNumberOfSemesters(n: int, relations: List[List[int]], k: int) -> int: """ You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k. In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking. Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course. Example 1: >>> minNumberOfSemesters(n = 4, relations = [[2,1],[3,1],[1,4]], k = 2) >>> 3 Explanation: The figure above represents the given graph. In the first semester, you can take courses 2 and 3. In the second semester, you can take course 1. In the third semester, you can take course 4. Example 2: >>> minNumberOfSemesters(n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2) >>> 4 Explanation: The figure above represents the given graph. In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester. In the second semester, you can take course 4. In the third semester, you can take course 1. In the fourth semester, you can take course 5. """
path-crossing
def isPathCrossing(path: str) -> bool: """ Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise. Example 1: >>> isPathCrossing(path = "NES") >>> false Explanation: Notice that the path doesn't cross any point more than once. Example 2: >>> isPathCrossing(path = "NESWW") >>> true Explanation: Notice that the path visits the origin twice. """
check-if-array-pairs-are-divisible-by-k
def canArrange(arr: List[int], k: int) -> bool: """ Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true If you can find a way to do that or false otherwise. Example 1: >>> canArrange(arr = [1,2,3,4,5,10,6,7,8,9], k = 5) >>> true Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10). Example 2: >>> canArrange(arr = [1,2,3,4,5,6], k = 7) >>> true Explanation: Pairs are (1,6),(2,5) and(3,4). Example 3: >>> canArrange(arr = [1,2,3,4,5,6], k = 10) >>> false Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10. """
number-of-subsequences-that-satisfy-the-given-sum-condition
def numSubseq(nums: List[int], target: int) -> int: """ You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numSubseq(nums = [3,5,6,7], target = 9) >>> 4 Explanation: There are 4 subsequences that satisfy the condition. [3] -> Min value + max value <= target (3 + 3 <= 9) [3,5] -> (3 + 5 <= 9) [3,5,6] -> (3 + 6 <= 9) [3,6] -> (3 + 6 <= 9) Example 2: >>> numSubseq(nums = [3,3,6,8], target = 10) >>> 6 Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). [3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6] Example 3: >>> numSubseq(nums = [2,3,3,4,6,7], target = 12) >>> 61 Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]). Number of valid subsequences (63 - 2 = 61). """
max-value-of-equation
def findMaxValueOfEquation(points: List[List[int]], k: int) -> int: """ You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k. Example 1: >>> findMaxValueOfEquation(points = [[1,3],[2,0],[5,10],[6,-10]], k = 1) >>> 4 Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. No other pairs satisfy the condition, so we return the max of 4 and 1. Example 2: >>> findMaxValueOfEquation(points = [[0,0],[3,0],[9,2]], k = 3) >>> 3 Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3. """
can-make-arithmetic-progression-from-sequence
def canMakeArithmeticProgression(arr: List[int]) -> bool: """ A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. Example 1: >>> canMakeArithmeticProgression(arr = [3,5,1]) >>> true Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. Example 2: >>> canMakeArithmeticProgression(arr = [1,2,4]) >>> false Explanation: There is no way to reorder the elements to obtain an arithmetic progression. """
last-moment-before-all-ants-fall-out-of-a-plank
def getLastMoment(n: int, left: List[int], right: List[int]) -> int: """ We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank. Example 1: >>> getLastMoment(n = 4, left = [4,3], right = [0,1]) >>> 4 Explanation: In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). Example 2: >>> getLastMoment(n = 7, left = [], right = [0,1,2,3,4,5,6,7]) >>> 7 Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. Example 3: >>> getLastMoment(n = 7, left = [0,1,2,3,4,5,6,7], right = []) >>> 7 Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall. """
count-submatrices-with-all-ones
def numSubmat(mat: List[List[int]]) -> int: """ Given an m x n binary matrix mat, return the number of submatrices that have all ones. Example 1: >>> numSubmat(mat = [[1,0,1],[1,1,0],[1,1,0]]) >>> 13 Explanation: There are 6 rectangles of side 1x1. There are 2 rectangles of side 1x2. There are 3 rectangles of side 2x1. There is 1 rectangle of side 2x2. There is 1 rectangle of side 3x1. Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13. Example 2: >>> numSubmat(mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]) >>> 24 Explanation: There are 8 rectangles of side 1x1. There are 5 rectangles of side 1x2. There are 2 rectangles of side 1x3. There are 4 rectangles of side 2x1. There are 2 rectangles of side 2x2. There are 2 rectangles of side 3x1. There is 1 rectangle of side 3x2. Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24. """
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
def minInteger(num: str, k: int) -> str: """ You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string. Example 1: >>> minInteger(num = "4321", k = 4) >>> "1342" Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown. Example 2: >>> minInteger(num = "100", k = 1) >>> "010" Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros. Example 3: >>> minInteger(num = "36789", k = 1000) >>> "36789" Explanation: We can keep the number without any swaps. """
reformat-date
def reformatDate(date: str) -> str: """ Given a date string in the form Day Month Year, where: Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. Year is in the range [1900, 2100]. Convert the date string to the format YYYY-MM-DD, where: YYYY denotes the 4 digit year. MM denotes the 2 digit month. DD denotes the 2 digit day. Example 1: >>> reformatDate(date = "20th Oct 2052") >>> "2052-10-20" Example 2: >>> reformatDate(date = "6th Jun 1933") >>> "1933-06-06" Example 3: >>> reformatDate(date = "26th May 1960") >>> "1960-05-26" """
range-sum-of-sorted-subarray-sums
def rangeSum(nums: List[int], n: int, left: int, right: int) -> int: """ You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7. Example 1: >>> rangeSum(nums = [1,2,3,4], n = 4, left = 1, right = 5) >>> 13 Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. Example 2: >>> rangeSum(nums = [1,2,3,4], n = 4, left = 3, right = 4) >>> 6 Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6. Example 3: >>> rangeSum(nums = [1,2,3,4], n = 4, left = 1, right = 10) >>> 50 """
minimum-difference-between-largest-and-smallest-value-in-three-moves
def minDifference(nums: List[int]) -> int: """ You are given an integer array nums. In one move, you can choose one element of nums and change it to any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves. Example 1: >>> minDifference(nums = [5,3,2,4]) >>> 0 Explanation: We can make at most 3 moves. In the first move, change 2 to 3. nums becomes [5,3,3,4]. In the second move, change 4 to 3. nums becomes [5,3,3,3]. In the third move, change 5 to 3. nums becomes [3,3,3,3]. After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0. Example 2: >>> minDifference(nums = [1,5,0,10,14]) >>> 1 Explanation: We can make at most 3 moves. In the first move, change 5 to 0. nums becomes [1,0,0,10,14]. In the second move, change 10 to 0. nums becomes [1,0,0,0,14]. In the third move, change 14 to 1. nums becomes [1,0,0,0,1]. After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1. It can be shown that there is no way to make the difference 0 in 3 moves. Example 3: >>> minDifference(nums = [3,100,20]) >>> 0 Explanation: We can make at most 3 moves. In the first move, change 100 to 7. nums becomes [3,7,20]. In the second move, change 20 to 7. nums becomes [3,7,7]. In the third move, change 3 to 7. nums becomes [7,7,7]. After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0. """
stone-game-iv
def winnerSquareGame(n: int) -> bool: """ Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally. Example 1: >>> winnerSquareGame(n = 1) >>> true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves. Example 2: >>> winnerSquareGame(n = 2) >>> false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). Example 3: >>> winnerSquareGame(n = 4) >>> true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). """
number-of-good-pairs
def numIdenticalPairs(nums: List[int]) -> int: """ Given an array of integers nums, return the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j. Example 1: >>> numIdenticalPairs(nums = [1,2,3,1,1,3]) >>> 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: >>> numIdenticalPairs(nums = [1,1,1,1]) >>> 6 Explanation: Each pair in the array are good. Example 3: >>> numIdenticalPairs(nums = [1,2,3]) >>> 0 """
number-of-substrings-with-only-1s
def numSub(s: str) -> int: """ Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numSub(s = "0110111") >>> 9 Explanation: There are 9 substring in total with only 1's characters. "1" -> 5 times. "11" -> 3 times. "111" -> 1 time. Example 2: >>> numSub(s = "101") >>> 2 Explanation: Substring "1" is shown 2 times in s. Example 3: >>> numSub(s = "111111") >>> 21 Explanation: Each substring contains only 1's characters. """
path-with-maximum-probability
def maxProbability(n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float: """ You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5. Example 1: >>> maxProbability(n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2) >>> 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: >>> maxProbability(n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2) >>> 0.30000 Example 3: >>> maxProbability(n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2) >>> 0.00000 Explanation: There is no path between 0 and 2. """
best-position-for-a-service-centre
def getMinDistSum(positions: List[List[int]]) -> float: """ A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum. Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized: Answers within 10-5 of the actual value will be accepted. Example 1: >>> getMinDistSum(positions = [[0,1],[1,0],[1,2],[2,1]]) >>> 4.00000 Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve. Example 2: >>> getMinDistSum(positions = [[1,1],[3,3]]) >>> 2.82843 Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843 """
water-bottles
def numWaterBottles(numBottles: int, numExchange: int) -> int: """ There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. Example 1: >>> numWaterBottles(numBottles = 9, numExchange = 3) >>> 13 Explanation: You can exchange 3 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 9 + 3 + 1 = 13. Example 2: >>> numWaterBottles(numBottles = 15, numExchange = 4) >>> 19 Explanation: You can exchange 4 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 15 + 3 + 1 = 19. """
number-of-nodes-in-the-sub-tree-with-the-same-label
def countSubTrees(n: int, edges: List[List[int]], labels: str) -> List[int]: """ You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]). The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i. A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. Example 1: >>> countSubTrees(n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd") >>> [2,1,1,1,1,1,1] Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree. Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself). Example 2: >>> countSubTrees(n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb") >>> [4,2,1,1] Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1. The sub-tree of node 3 contains only node 3, so the answer is 1. The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2. The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4. Example 3: >>> countSubTrees(n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab") >>> [3,2,1,1,1] """
maximum-number-of-non-overlapping-substrings
def maxNumOfSubstrings(s: str) -> List[str]: """ Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c. Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order. Example 1: >>> maxNumOfSubstrings(s = "adefaddaccc") >>> ["e","f","ccc"] Explanation: The following are all the possible substrings that meet the conditions: [   "adefaddaccc"   "adefadda",   "ef",   "e", "f",   "ccc", ] If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist. Example 2: >>> maxNumOfSubstrings(s = "abbaccd") >>> ["d","bb","cc"] Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length. """
find-a-value-of-a-mysterious-function-closest-to-target
def closestToTarget(arr: List[int], target: int) -> int: """ Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target|. Notice that func should be called with the values l and r where 0 <= l, r < arr.length. Example 1: >>> closestToTarget(arr = [9,12,3,7,15], target = 5) >>> 2 Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2. Example 2: >>> closestToTarget(arr = [1000000,1000000,1000000], target = 1) >>> 999999 Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999. Example 3: >>> closestToTarget(arr = [1,2,4,8,16], target = 0) >>> 0 """
count-odd-numbers-in-an-interval-range
def countOdds(low: int, high: int) -> int: """ Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\r \r  \r Example 1:\r \r \r >>> countOdds(low = 3, high = 7\r) >>> 3\r Explanation: The odd numbers between 3 and 7 are [3,5,7].\r \r Example 2:\r \r \r >>> countOdds(low = 8, high = 10\r) >>> 1\r Explanation: The odd numbers between 8 and 10 are [9].\r \r  \r """
number-of-sub-arrays-with-odd-sum
def numOfSubarrays(arr: List[int]) -> int: """ Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. Example 1: >>> numOfSubarrays(arr = [1,3,5]) >>> 4 Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,8,5]. Odd sums are [1,9,3,5] so the answer is 4. Example 2: >>> numOfSubarrays(arr = [2,4,6]) >>> 0 Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]] All sub-arrays sum are [2,6,12,4,10,6]. All sub-arrays have even sum and the answer is 0. Example 3: >>> numOfSubarrays(arr = [1,2,3,4,5,6,7]) >>> 16 """
number-of-good-ways-to-split-a-string
def numSplits(s: str) -> int: """ You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. Example 1: >>> numSplits(s = "aacaba") >>> 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively. Example 2: >>> numSplits(s = "abcd") >>> 1 Explanation: Split the string as follows ("ab", "cd"). """
minimum-number-of-increments-on-subarrays-to-form-a-target-array
def minNumberOperations(target: List[int]) -> int: """ You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: >>> minNumberOperations(target = [1,2,3,2,1]) >>> 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: >>> minNumberOperations(target = [3,1,1,2]) >>> 4 Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] Example 3: >>> minNumberOperations(target = [3,1,5,4,2]) >>> 7 Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2]. """
shuffle-string
def restoreString(s: str, indices: List[int]) -> str: """ You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Example 1: >>> restoreString(s = "codeleet", indices = [4,5,6,7,0,2,1,3]) >>> "leetcode" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. Example 2: >>> restoreString(s = "abc", indices = [0,1,2]) >>> "abc" Explanation: After shuffling, each character remains in its position. """
minimum-suffix-flips
def minFlips(target: str) -> int: """ You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. Example 1: >>> minFlips(target = "10111") >>> 3 Explanation: Initially, s = "00000". Choose index i = 2: "00000" -> "00111" Choose index i = 0: "00111" -> "11000" Choose index i = 1: "11000" -> "10111" We need at least 3 flip operations to form target. Example 2: >>> minFlips(target = "101") >>> 3 Explanation: Initially, s = "000". Choose index i = 0: "000" -> "111" Choose index i = 1: "111" -> "100" Choose index i = 2: "100" -> "101" We need at least 3 flip operations to form target. Example 3: >>> minFlips(target = "00000") >>> 0 Explanation: We do not need any operations since the initial s already equals target. """
number-of-good-leaf-nodes-pairs
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countPairs(root: Optional[TreeNode], distance: int) -> int: """ You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree. Example 1: >>> __init__(root = [1,2,3,null,4], distance = 3) >>> 1 Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. Example 2: >>> __init__(root = [1,2,3,4,5,6,7], distance = 3) >>> 2 Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4. Example 3: >>> __init__(root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3) >>> 1 Explanation: The only good pair is [2,5]. """
string-compression-ii
def getLengthOfOptimalCompression(s: str, k: int) -> int: """ Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters. Example 1: >>> getLengthOfOptimalCompression(s = "aaabcccd", k = 2) >>> 4 Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. Example 2: >>> getLengthOfOptimalCompression(s = "aabbaa", k = 2) >>> 2 Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. Example 3: >>> getLengthOfOptimalCompression(s = "aaaaaaaaaaa", k = 0) >>> 3 Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3. """
count-good-triplets
def countGoodTriplets(arr: List[int], a: int, b: int, c: int) -> int: """ Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.\r \r A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:\r \r \r 0 <= i < j < k < arr.length\r |arr[i] - arr[j]| <= a\r |arr[j] - arr[k]| <= b\r |arr[i] - arr[k]| <= c\r \r \r Where |x| denotes the absolute value of x.\r \r Return the number of good triplets.\r \r  \r Example 1:\r \r \r >>> countGoodTriplets(arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\r) >>> 4\r Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\r \r \r Example 2:\r \r \r >>> countGoodTriplets(arr = [1,1,2,2,3], a = 0, b = 0, c = 1\r) >>> 0\r Explanation: No triplet satisfies all conditions.\r \r \r  \r """
find-the-winner-of-an-array-game
def getWinner(arr: List[int], k: int) -> int: """ Given an integer array arr of distinct integers and an integer k. A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game. It is guaranteed that there will be a winner of the game. Example 1: >>> getWinner(arr = [2,1,3,5,4,6,7], k = 2) >>> 5 Explanation: Let's see the rounds of the game: Round | arr | winner | win_count 1 | [2,1,3,5,4,6,7] | 2 | 1 2 | [2,3,5,4,6,7,1] | 3 | 1 3 | [3,5,4,6,7,1,2] | 5 | 1 4 | [5,4,6,7,1,2,3] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. Example 2: >>> getWinner(arr = [3,2,1], k = 10) >>> 3 Explanation: 3 will win the first 10 rounds consecutively. """
minimum-swaps-to-arrange-a-binary-grid
def minSwaps(grid: List[List[int]]) -> int: """ Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n). Example 1: >>> minSwaps(grid = [[0,0,1],[1,1,0],[1,0,0]]) >>> 3 Example 2: >>> minSwaps(grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]) >>> -1 Explanation: All rows are similar, swaps have no effect on the grid. Example 3: >>> minSwaps(grid = [[1,0,0],[1,1,0],[1,1,1]]) >>> 0 """
get-the-maximum-score
def maxSum(nums1: List[int], nums2: List[int]) -> int: """ You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path). The score is defined as the sum of unique values in a valid path. Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> maxSum(nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]) >>> 30 Explanation: Valid paths: [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1) [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2) The maximum is obtained with the path in green [2,4,6,8,10]. Example 2: >>> maxSum(nums1 = [1,3,5,7,9], nums2 = [3,5,100]) >>> 109 Explanation: Maximum sum is obtained with the path [1,3,5,100]. Example 3: >>> maxSum(nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]) >>> 40 Explanation: There are no common elements between nums1 and nums2. Maximum sum is obtained with the path [6,7,8,9,10]. """
kth-missing-positive-number
def findKthPositive(arr: List[int], k: int) -> int: """ Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array. Example 1: >>> findKthPositive(arr = [2,3,4,7,11], k = 5) >>> 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. Example 2: >>> findKthPositive(arr = [1,2,3,4], k = 2) >>> 6 Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. """
can-convert-string-in-k-moves
def canConvertString(s: str, t: str, k: int) -> bool: """ Given two strings s and t, your goal is to convert s into t in k moves or less. During the ith (1 <= i <= k) move you can: Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times. Do nothing. Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times. Remember that any index j can be picked at most once. Return true if it's possible to convert s into t in no more than k moves, otherwise return false. Example 1: >>> canConvertString(s = "input", t = "ouput", k = 9) >>> true Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'. Example 2: >>> canConvertString(s = "abc", t = "bcd", k = 10) >>> false Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s. Example 3: >>> canConvertString(s = "aab", t = "bbb", k = 27) >>> true Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'. """
minimum-insertions-to-balance-a-parentheses-string
def minInsertions(s: str) -> int: """ Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced. Example 1: >>> minInsertions(s = "(()))") >>> 1 Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced. Example 2: >>> minInsertions(s = "())") >>> 0 Explanation: The string is already balanced. Example 3: >>> minInsertions(s = "))())(") >>> 3 Explanation: Add '(' to match the first '))', Add '))' to match the last '('. """
find-longest-awesome-substring
def longestAwesome(s: str) -> int: """ You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s. Example 1: >>> longestAwesome(s = "3242415") >>> 5 Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps. Example 2: >>> longestAwesome(s = "12345678") >>> 1 Example 3: >>> longestAwesome(s = "213123") >>> 6 Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps. """
make-the-string-great
def makeGood(s: str) -> str: """ Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. Return the string after making it good. The answer is guaranteed to be unique under the given constraints. Notice that an empty string is also good. Example 1: >>> makeGood(s = "leEeetcode") >>> "leetcode" Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". Example 2: >>> makeGood(s = "abBAcC") >>> "" Explanation: We have many possible scenarios, and all lead to the same answer. For example: "abBAcC" --> "aAcC" --> "cC" --> "" "abBAcC" --> "abBA" --> "aA" --> "" Example 3: >>> makeGood(s = "s") >>> "s" """
find-kth-bit-in-nth-binary-string
def findKthBit(n: int, k: int) -> str: """ Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, the first four strings in the above sequence are: S1 = "0" S2 = "011" S3 = "0111001" S4 = "011100110110001" Return the kth bit in Sn. It is guaranteed that k is valid for the given n. Example 1: >>> findKthBit(n = 3, k = 1) >>> "0" Explanation: S3 is "0111001". The 1st bit is "0". Example 2: >>> findKthBit(n = 4, k = 11) >>> "1" Explanation: S4 is "011100110110001". The 11th bit is "1". """
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
def maxNonOverlapping(nums: List[int], target: int) -> int: """ Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target. Example 1: >>> maxNonOverlapping(nums = [1,1,1,1,1], target = 2) >>> 2 Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2). Example 2: >>> maxNonOverlapping(nums = [-1,3,5,1,4,2,-9], target = 6) >>> 2 Explanation: There are 3 subarrays with sum equal to 6. ([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping. """
minimum-cost-to-cut-a-stick
def minCost(n: int, cuts: List[int]) -> int: """ Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts. Example 1: >>> minCost(n = 7, cuts = [1,3,4,5]) >>> 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). Example 2: >>> minCost(n = 9, cuts = [5,6,1,4,2]) >>> 22 Explanation: If you try the given cuts ordering the cost will be 25. There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible. """
the-most-similar-path-in-a-graph
def mostSimilar(n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]: """ We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai with city bi. Each city has a name consisting of exactly three upper-case English letters given in the string array names. Starting at any city x, you can reach any city y where y != x (i.e., the cities and the roads are forming an undirected connected graph). You will be given a string array targetPath. You should find a path in the graph of the same length and with the minimum edit distance to targetPath. You need to return the order of the nodes in the path with the minimum edit distance. The path should be of the same length of targetPath and should be valid (i.e., there should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers return any one of them. The edit distance is defined as follows: Example 1: >>> mostSimilar(n = 5, roads = [[0,2],[0,3],[1,2],[1,3],[1,4],[2,4]], names = ["ATL","PEK","LAX","DXB","HND"], targetPath = ["ATL","DXB","HND","LAX"]) >>> [0,2,4,2] Explanation: [0,2,4,2], [0,3,0,2] and [0,3,1,2] are accepted answers. [0,2,4,2] is equivalent to ["ATL","LAX","HND","LAX"] which has edit distance = 1 with targetPath. [0,3,0,2] is equivalent to ["ATL","DXB","ATL","LAX"] which has edit distance = 1 with targetPath. [0,3,1,2] is equivalent to ["ATL","DXB","PEK","LAX"] which has edit distance = 1 with targetPath. Example 2: >>> mostSimilar(n = 4, roads = [[1,0],[2,0],[3,0],[2,1],[3,1],[3,2]], names = ["ATL","PEK","LAX","DXB"], targetPath = ["ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX"]) >>> [0,1,0,1,0,1,0,1] Explanation: Any path in this graph has edit distance = 8 with targetPath. Example 3: >>> mostSimilar(n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[4,5]], names = ["ATL","PEK","LAX","ATL","DXB","HND"], targetPath = ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]) >>> [3,4,5,4,3,2,1] Explanation: [3,4,5,4,3,2,1] is the only path with edit distance = 0 with targetPath. It's equivalent to ["ATL","DXB","HND","DXB","ATL","LAX","PEK"] """
three-consecutive-odds
def threeConsecutiveOdds(arr: List[int]) -> bool: """ Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. Example 1: >>> threeConsecutiveOdds(arr = [2,6,4,1]) >>> false Explanation: There are no three consecutive odds. Example 2: >>> threeConsecutiveOdds(arr = [1,2,34,3,4,5,7,23,12]) >>> true Explanation: [5,7,23] are three consecutive odds. """
minimum-operations-to-make-array-equal
def minOperations(n: int) -> int: """ You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal. Example 1: >>> minOperations(n = 3) >>> 2 Explanation: arr = [1, 3, 5] First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4] In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]. Example 2: >>> minOperations(n = 6) >>> 9 """
magnetic-force-between-two-balls
def maxDistance(position: List[int], m: int) -> int: """ In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force. Example 1: >>> maxDistance(position = [1,2,3,4,7], m = 3) >>> 3 Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. Example 2: >>> maxDistance(position = [5,4,3,2,1,1000000000], m = 2) >>> 999999999 Explanation: We can use baskets 1 and 1000000000. """
minimum-number-of-days-to-eat-n-oranges
def minDays(n: int) -> int: """ There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. You can only choose one of the actions per day. Given the integer n, return the minimum number of days to eat n oranges. Example 1: >>> minDays(n = 10) >>> 4 Explanation: You have 10 oranges. Day 1: Eat 1 orange, 10 - 1 = 9. Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3) Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. Day 4: Eat the last orange 1 - 1 = 0. You need at least 4 days to eat the 10 oranges. Example 2: >>> minDays(n = 6) >>> 3 Explanation: You have 6 oranges. Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2). Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3) Day 3: Eat the last orange 1 - 1 = 0. You need at least 3 days to eat the 6 oranges. """
strings-differ-by-one-character
def differByOne(dict: List[str]) -> bool: """ Given a list of strings dict where all the strings are of the same length. Return true if there are 2 strings that only differ by 1 character in the same index, otherwise return false. Example 1: >>> differByOne(dict = ["abcd","acbd", "aacd"]) >>> true Explanation: Strings "abcd" and "aacd" differ only by one character in the index 1. Example 2: >>> differByOne(dict = ["ab","cd","yz"]) >>> false Example 3: >>> differByOne(dict = ["abcd","cccc","abyd","abab"]) >>> true """
thousand-separator
def thousandSeparator(n: int) -> str: """ Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: >>> thousandSeparator(n = 987) >>> "987" Example 2: >>> thousandSeparator(n = 1234) >>> "1.234" """
minimum-number-of-vertices-to-reach-all-nodes
def findSmallestSetOfVertices(n: int, edges: List[List[int]]) -> List[int]: """ Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. Example 1: >>> findSmallestSetOfVertices(n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]) >>> [0,3] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3]. Example 2: >>> findSmallestSetOfVertices(n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]) >>> [0,2,3] Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4. """
minimum-numbers-of-function-calls-to-make-target-array
def minOperations(nums: List[int]) -> int: """ You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to convert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr. The test cases are generated so that the answer fits in a 32-bit signed integer. Example 1: >>> minOperations(nums = [1,5]) >>> 5 Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation). Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations). Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations). Total of operations: 1 + 2 + 2 = 5. Example 2: >>> minOperations(nums = [2,2]) >>> 3 Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations). Double all the elements: [1, 1] -> [2, 2] (1 operation). Total of operations: 2 + 1 = 3. Example 3: >>> minOperations(nums = [4,2,5]) >>> 6 Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums). """
detect-cycles-in-2d-grid
def containsCycle(grid: List[List[str]]) -> bool: """ Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false. Example 1: >>> containsCycle(grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]) >>> true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: >>> containsCycle(grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]) >>> true Explanation: There is only one valid cycle highlighted in the image below: Example 3: >>> containsCycle(grid = [["a","b","b"],["b","z","b"],["b","b","a"]]) >>> false """
most-visited-sector-in-a-circular-track
def mostVisited(n: int, rounds: List[int]) -> List[int]: """ Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). Example 1: >>> mostVisited(n = 4, rounds = [1,3,1,2]) >>> [1,2] Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. Example 2: >>> mostVisited(n = 2, rounds = [2,1,2,1,2,1,2,1,2]) >>> [2] Example 3: >>> mostVisited(n = 7, rounds = [1,3,5,7]) >>> [1,2,3,4,5,6,7] """
maximum-number-of-coins-you-can-get
def maxCoins(piles: List[int]) -> int: """ There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with the maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins that you can have. Example 1: >>> maxCoins(piles = [2,4,1,2,7,8]) >>> 9 Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. Example 2: >>> maxCoins(piles = [2,4,5]) >>> 4 Example 3: >>> maxCoins(piles = [9,8,7,6,5,1,2,3,4]) >>> 18 """
find-latest-group-of-size-m
def findLatestStep(arr: List[int], m: int) -> int: """ Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1. Example 1: >>> findLatestStep(arr = [3,5,1,2,4], m = 1) >>> 4 Explanation: Step 1: "00100", groups: ["1"] Step 2: "00101", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "11101", groups: ["111", "1"] Step 5: "11111", groups: ["11111"] The latest step at which there exists a group of size 1 is step 4. Example 2: >>> findLatestStep(arr = [3,1,5,4,2], m = 2) >>> -1 Explanation: Step 1: "00100", groups: ["1"] Step 2: "10100", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "10111", groups: ["1", "111"] Step 5: "11111", groups: ["11111"] No group of size 2 exists during any step. """
stone-game-v
def stoneGameV(stoneValue: List[int]) -> int: """ There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain. Example 1: >>> stoneGameV(stoneValue = [6,2,3,4,5,5]) >>> 18 Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11. In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5). The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row. Example 2: >>> stoneGameV(stoneValue = [7,7,7,7,7,7,7]) >>> 28 Example 3: >>> stoneGameV(stoneValue = [4]) >>> 0 """
put-boxes-into-the-warehouse-i
def maxBoxesInWarehouse(boxes: List[int], warehouse: List[int]) -> int: """ You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labelled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room. Boxes are put into the warehouse by the following rules: Boxes cannot be stacked. You can rearrange the insertion order of the boxes. Boxes can only be pushed into the warehouse from left to right only. If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped before that room. Return the maximum number of boxes you can put into the warehouse. Example 1: >>> maxBoxesInWarehouse(boxes = [4,3,4,1], warehouse = [5,3,3,4,1]) >>> 3 Explanation: We can first put the box of height 1 in room 4. Then we can put the box of height 3 in either of the 3 rooms 1, 2, or 3. Lastly, we can put one box of height 4 in room 0. There is no way we can fit all 4 boxes in the warehouse. Example 2: >>> maxBoxesInWarehouse(boxes = [1,2,2,3,4], warehouse = [3,4,1,2]) >>> 3 Explanation: Notice that it's not possible to put the box of height 4 into the warehouse since it cannot pass the first room of height 3. Also, for the last two rooms, 2 and 3, only boxes of height 1 can fit. We can fit 3 boxes maximum as shown above. The yellow box can also be put in room 2 instead. Swapping the orange and green boxes is also valid, or swapping one of them with the red box. Example 3: >>> maxBoxesInWarehouse(boxes = [1,2,3], warehouse = [1,2,3,4]) >>> 1 Explanation: Since the first room in the warehouse is of height 1, we can only put boxes of height 1. """
detect-pattern-of-length-m-repeated-k-or-more-times
def containsPattern(arr: List[int], m: int, k: int) -> bool: """ Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. Example 1: >>> containsPattern(arr = [1,2,4,4,4,4], m = 1, k = 3) >>> true Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less. Example 2: >>> containsPattern(arr = [1,2,1,2,1,1,1,3], m = 2, k = 2) >>> true Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times. Example 3: >>> containsPattern(arr = [1,2,1,2,1,3], m = 2, k = 3) >>> false Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times. """
maximum-length-of-subarray-with-positive-product
def getMaxLen(nums: List[int]) -> int: """ Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product. Example 1: >>> getMaxLen(nums = [1,-2,-3,4]) >>> 4 Explanation: The array nums already has a positive product of 24. Example 2: >>> getMaxLen(nums = [0,1,-2,-3,-4]) >>> 3 Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. Example 3: >>> getMaxLen(nums = [-1,-2,-3,0,1]) >>> 2 Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3]. """
minimum-number-of-days-to-disconnect-island
def minDays(grid: List[List[int]]) -> int: """ You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid. Example 1: >>> minDays(grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]) >>> 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island. Example 2: >>> minDays(grid = [[1,1]]) >>> 2 Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands. """
number-of-ways-to-reorder-array-to-get-same-bst
def numOfWays(nums: List[int]) -> int: """ Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums. For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST. Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums. Since the answer may be very large, return it modulo 109 + 7. Example 1: >>> numOfWays(nums = [2,1,3]) >>> 1 Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST. Example 2: >>> numOfWays(nums = [3,4,5,1,2]) >>> 5 Explanation: The following 5 arrays will yield the same BST: [3,1,2,4,5] [3,1,4,2,5] [3,1,4,5,2] [3,4,1,2,5] [3,4,1,5,2] Example 3: >>> numOfWays(nums = [1,2,3]) >>> 0 Explanation: There are no other orderings of nums that will yield the same BST. """
matrix-diagonal-sum
def diagonalSum(mat: List[List[int]]) -> int: """ Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1:   [4,5,6],   [7,8,9]] >>> diagonalSum(mat = [[1,2,3],) >>> 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2:   [1,1,1,1],   [1,1,1,1],   [1,1,1,1]] >>> diagonalSum(mat = [[1,1,1,1],) >>> 8 Example 3: >>> diagonalSum(mat = [[5]]) >>> 5 """
number-of-ways-to-split-a-string
def numWays(s: str) -> int: """ Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s. Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numWays(s = "10101") >>> 4 Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'. "1|010|1" "1|01|01" "10|10|1" "10|1|01" Example 2: >>> numWays(s = "1001") >>> 0 Example 3: >>> numWays(s = "0000") >>> 3 Explanation: There are three ways to split s in 3 parts. "0|0|00" "0|00|0" "00|0|0" """
shortest-subarray-to-be-removed-to-make-array-sorted
def findLengthOfShortestSubarray(arr: List[int]) -> int: """ Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. Example 1: >>> findLengthOfShortestSubarray(arr = [1,2,3,10,4,2,3,5]) >>> 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4]. Example 2: >>> findLengthOfShortestSubarray(arr = [5,4,3,2,1]) >>> 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]. Example 3: >>> findLengthOfShortestSubarray(arr = [1,2,3]) >>> 0 Explanation: The array is already non-decreasing. We do not need to remove any elements. """
count-all-possible-routes
def countRoutes(locations: List[int], start: int, finish: int, fuel: int) -> int: """ You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> countRoutes(locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5) >>> 4 Explanation: The following are all possible routes, each uses 5 units of fuel: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3 Example 2: >>> countRoutes(locations = [4,3,1], start = 1, finish = 0, fuel = 6) >>> 5 Explanation: The following are all possible routes: 1 -> 0, used fuel = 1 1 -> 2 -> 0, used fuel = 5 1 -> 2 -> 1 -> 0, used fuel = 5 1 -> 0 -> 1 -> 0, used fuel = 3 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5 Example 3: >>> countRoutes(locations = [5,2,1], start = 0, finish = 2, fuel = 3) >>> 0 Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel. """
replace-all-s-to-avoid-consecutive-repeating-characters
def modifyString(s: str) -> str: """ Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guaranteed that there are no consecutive repeating characters in the given string except for '?'. Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints. Example 1: >>> modifyString(s = "?zs") >>> "azs" Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs". Example 2: >>> modifyString(s = "ubv?w") >>> "ubvaw" Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww". """
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
def numTriplets(nums1: List[int], nums2: List[int]) -> int: """ Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules: Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length. Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length. Example 1: >>> numTriplets(nums1 = [7,4], nums2 = [5,2,8,9]) >>> 1 Explanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). Example 2: >>> numTriplets(nums1 = [1,1], nums2 = [1,1,1]) >>> 9 Explanation: All Triplets are valid, because 12 = 1 * 1. Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k]. Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k]. Example 3: >>> numTriplets(nums1 = [7,7,8,3], nums2 = [1,2,9,7]) >>> 2 Explanation: There are 2 valid triplets. Type 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2]. Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1]. """
minimum-time-to-make-rope-colorful
def minCost(colors: str, neededTime: List[int]) -> int: """ Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. Return the minimum time Bob needs to make the rope colorful. Example 1: >>> minCost(colors = "abaac", neededTime = [1,2,3,4,5]) >>> 3 Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. Example 2: >>> minCost(colors = "abc", neededTime = [1,2,3]) >>> 0 Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope. Example 3: >>> minCost(colors = "aabaa", neededTime = [1,2,3,4,1]) >>> 2 Explanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. """
remove-max-number-of-edges-to-keep-graph-fully-traversable
def maxNumEdgesToRemove(n: int, edges: List[List[int]]) -> int: """ Alice and Bob have an undirected graph of n nodes and three types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both Alice and Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. Example 1: >>> maxNumEdgesToRemove(n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]) >>> 2 Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. Example 2: >>> maxNumEdgesToRemove(n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]) >>> 0 Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob. Example 3: >>> maxNumEdgesToRemove(n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]) >>> -1 Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. """
put-boxes-into-the-warehouse-ii
def maxBoxesInWarehouse(boxes: List[int], warehouse: List[int]) -> int: """ You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room. Boxes are put into the warehouse by the following rules: Boxes cannot be stacked. You can rearrange the insertion order of the boxes. Boxes can be pushed into the warehouse from either side (left or right) If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped before that room. Return the maximum number of boxes you can put into the warehouse. Example 1: >>> maxBoxesInWarehouse(boxes = [1,2,2,3,4], warehouse = [3,4,1,2]) >>> 4 Explanation: We can store the boxes in the following order: 1- Put the yellow box in room 2 from either the left or right side. 2- Put the orange box in room 3 from the right side. 3- Put the green box in room 1 from the left side. 4- Put the red box in room 0 from the left side. Notice that there are other valid ways to put 4 boxes such as swapping the red and green boxes or the red and orange boxes. Example 2: >>> maxBoxesInWarehouse(boxes = [3,5,5,2], warehouse = [2,1,3,4,5]) >>> 3 Explanation: It is not possible to put the two boxes of height 5 in the warehouse since there's only 1 room of height >= 5. Other valid solutions are to put the green box in room 2 or to put the orange box first in room 2 before putting the green and red boxes. """
special-positions-in-a-binary-matrix
def numSpecial(mat: List[List[int]]) -> int: """ Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Example 1: >>> numSpecial(mat = [[1,0,0],[0,0,1],[1,0,0]]) >>> 1 Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2: >>> numSpecial(mat = [[1,0,0],[0,1,0],[0,0,1]]) >>> 3 Explanation: (0, 0), (1, 1) and (2, 2) are special positions. """
count-unhappy-friends
def unhappyFriends(n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: """ You are given a list of preferences for n friends, where n is always even. For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1. All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi. However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but: x prefers u over y, and u prefers x over v. Return the number of unhappy friends. Example 1: >>> unhappyFriends(n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]) >>> 2 Explanation: Friend 1 is unhappy because: - 1 is paired with 0 but prefers 3 over 0, and - 3 prefers 1 over 2. Friend 3 is unhappy because: - 3 is paired with 2 but prefers 1 over 2, and - 1 prefers 3 over 0. Friends 0 and 2 are happy. Example 2: >>> unhappyFriends(n = 2, preferences = [[1], [0]], pairs = [[1, 0]]) >>> 0 Explanation: Both friends 0 and 1 are happy. Example 3: >>> unhappyFriends(n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]) >>> 4 """
min-cost-to-connect-all-points
def minCostConnectPoints(points: List[List[int]]) -> int: """ You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. Example 1: >>> minCostConnectPoints(points = [[0,0],[2,2],[3,10],[5,2],[7,0]]) >>> 20 Explanation: We can connect the points as shown above to get the minimum cost of 20. Notice that there is a unique path between every pair of points. Example 2: >>> minCostConnectPoints(points = [[3,12],[-2,5],[-4,1]]) >>> 18 """
check-if-string-is-transformable-with-substring-sort-operations
def isTransformable(s: str, t: str) -> bool: """ Given two strings s and t, transform string s into string t using the following operation any number of times: Choose a non-empty substring in s and sort it in place so the characters are in ascending order. For example, applying the operation on the underlined substring in "14234" results in "12344". Return true if it is possible to transform s into t. Otherwise, return false. A substring is a contiguous sequence of characters within a string. Example 1: >>> isTransformable(s = "84532", t = "34852") >>> true Explanation: You can transform s into t using the following sort operations: "84532" (from index 2 to 3) -> "84352" "84352" (from index 0 to 2) -> "34852" Example 2: >>> isTransformable(s = "34521", t = "23415") >>> true Explanation: You can transform s into t using the following sort operations: "34521" -> "23451" "23451" -> "23415" Example 3: >>> isTransformable(s = "12345", t = "12435") >>> false """
sum-of-all-odd-length-subarrays
def sumOddLengthSubarrays(arr: List[int]) -> int: """ Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr. A subarray is a contiguous subsequence of the array. Example 1: >>> sumOddLengthSubarrays(arr = [1,4,2,5,3]) >>> 58 Explanation: The odd-length subarrays of arr and their sums are: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4,2] = 7 [4,2,5] = 11 [2,5,3] = 10 [1,4,2,5,3] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 Example 2: >>> sumOddLengthSubarrays(arr = [1,2]) >>> 3 Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. Example 3: >>> sumOddLengthSubarrays(arr = [10,11,12]) >>> 66 """
maximum-sum-obtained-of-any-permutation
def maxSumRangeQuery(nums: List[int], requests: List[List[int]]) -> int: """ We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed. Return the maximum total sum of all requests among all permutations of nums. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> maxSumRangeQuery(nums = [1,2,3,4,5], requests = [[1,3],[0,1]]) >>> 19 Explanation: One permutation of nums is [2,1,3,4,5] with the following result: requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8 requests[1] -> nums[0] + nums[1] = 2 + 1 = 3 Total sum: 8 + 3 = 11. A permutation with a higher total sum is [3,5,4,2,1] with the following result: requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11 requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 Total sum: 11 + 8 = 19, which is the best that you can do. Example 2: >>> maxSumRangeQuery(nums = [1,2,3,4,5,6], requests = [[0,1]]) >>> 11 Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11]. Example 3: >>> maxSumRangeQuery(nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]) >>> 47 Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10]. """
make-sum-divisible-by-p
def minSubarray(nums: List[int], p: int) -> int: """ Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array. Example 1: >>> minSubarray(nums = [3,1,4,2], p = 6) >>> 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. Example 2: >>> minSubarray(nums = [6,3,5,2], p = 9) >>> 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. Example 3: >>> minSubarray(nums = [1,2,3], p = 3) >>> 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything. """