task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
strange-printer-ii
def isPrintable(targetGrid: List[List[int]]) -> bool: """ There is a strange printer with the following two special requirements: On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. Once the printer has used a color for the above operation, the same color cannot be used again. You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid, otherwise, return false. Example 1: >>> isPrintable(targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]) >>> true Example 2: >>> isPrintable(targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]) >>> true Example 3: >>> isPrintable(targetGrid = [[1,2,1],[2,1,2],[1,2,1]]) >>> false Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns. """
rearrange-spaces-between-words
def reorderSpaces(text: str) -> str: """ You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces. Example 1: >>> reorderSpaces(text = " this is a sentence ") >>> "this is a sentence" Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces. Example 2: >>> reorderSpaces(text = " practice makes perfect") >>> "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string. """
split-a-string-into-the-max-number-of-unique-substrings
def maxUniqueSplit(s: str) -> int: """ Given a string s, return the maximum number of unique substrings that the given string can be split into. You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique. A substring is a contiguous sequence of characters within a string. Example 1: >>> maxUniqueSplit(s = "ababccc") >>> 5 Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times. Example 2: >>> maxUniqueSplit(s = "aba") >>> 2 Explanation: One way to split maximally is ['a', 'ba']. Example 3: >>> maxUniqueSplit(s = "aa") >>> 1 Explanation: It is impossible to split the string any further. """
maximum-non-negative-product-in-a-matrix
def maxProductPath(grid: List[List[int]]) -> int: """ You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product. Example 1: >>> maxProductPath(grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]) >>> -1 Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. Example 2: >>> maxProductPath(grid = [[1,-2,1],[1,-2,1],[3,-4,1]]) >>> 8 Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8). Example 3: >>> maxProductPath(grid = [[1,3],[0,-4]]) >>> 0 Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0). """
minimum-cost-to-connect-two-groups-of-points
def connectTwoGroups(cost: List[List[int]]) -> int: """ You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups. Example 1: >>> connectTwoGroups(cost = [[15, 96], [36, 2]]) >>> 17 Explanation: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. Example 2: >>> connectTwoGroups(cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]) >>> 4 Explanation: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. Example 3: >>> connectTwoGroups(cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]) >>> 10 """
crawler-log-folder
def minOperations(logs: List[str]) -> int: """ The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). "./" : Remain in the same folder. "x/" : Move to the child folder named x (This folder is guaranteed to always exist). You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step. The file system starts in the main folder, then the operations in logs are performed. Return the minimum number of operations needed to go back to the main folder after the change folder operations. Example 1: >>> minOperations(logs = ["d1/","d2/","../","d21/","./"]) >>> 2 Explanation: Use this change folder operation "../" 2 times and go back to the main folder. Example 2: >>> minOperations(logs = ["d1/","d2/","./","d3/","../","d31/"]) >>> 3 Example 3: >>> minOperations(logs = ["d1/","../","../","../"]) >>> 0 """
maximum-profit-of-operating-a-centennial-wheel
def minOperationsMaxProfit(customers: List[int], boardingCost: int, runningCost: int) -> int: """ You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation. Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1. Example 1: >>> minOperationsMaxProfit(customers = [8,3], boardingCost = 5, runningCost = 6) >>> 3 Explanation: The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37. The highest profit was $37 after rotating the wheel 3 times. Example 2: >>> minOperationsMaxProfit(customers = [10,9,6], boardingCost = 6, runningCost = 4) >>> 7 Explanation: 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122. The highest profit was $122 after rotating the wheel 7 times. Example 3: >>> minOperationsMaxProfit(customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92) >>> -1 Explanation: 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447. The profit was never positive, so return -1. """
maximum-number-of-achievable-transfer-requests
def maximumRequests(n: int, requests: List[List[int]]) -> int: """ We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi. All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2. Return the maximum number of achievable requests. Example 1: >>> maximumRequests(n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]) >>> 5 Explantion: Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. Example 2: >>> maximumRequests(n = 3, requests = [[0,0],[1,2],[2,1]]) >>> 3 Explantion: Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. Example 3: >>> maximumRequests(n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]) >>> 4 """
find-nearest-right-node-in-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findNearestRightNode(root: TreeNode, u: TreeNode) -> Optional[TreeNode]: """ Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level. Example 1: >>> __init__(root = [1,2,3,null,4,5,6], u = 4) >>> 5 Explanation: The nearest node on the same level to the right of node 4 is node 5. Example 2: >>> __init__(root = [3,null,4,2], u = 2) >>> null Explanation: There are no nodes to the right of 2. """
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
def alertNames(keyName: List[str], keyTime: List[str]) -> List[str]: """ LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day. Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49". Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically. Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period. Example 1: >>> alertNames(keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]) >>> ["daniel"] Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00"). Example 2: >>> alertNames(keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]) >>> ["bob"] Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30"). """
find-valid-matrix-given-row-and-column-sums
def restoreMatrix(rowSum: List[int], colSum: List[int]) -> List[List[int]]: """ You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists. Example 1: >>> restoreMatrix(rowSum = [3,8], colSum = [4,7]) >>> [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]] Example 2: >>> restoreMatrix(rowSum = [5,7,10], colSum = [8,6,8]) >>> [[0,5,0], [6,1,0], [2,0,8]] """
find-servers-that-handled-most-number-of-requests
def busiestServers(k: int, arrival: List[int], load: List[int]) -> List[int]: """ You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm: The ith (0-indexed) request arrives. If all servers are busy, the request is dropped (not handled at all). If the (i % k)th server is available, assign the request to that server. Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on. You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order. Example 1: >>> busiestServers(k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]) >>> [1] Explanation: All of the servers start out available. The first 3 requests are handled by the first 3 servers in order. Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1. Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped. Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server. Example 2: >>> busiestServers(k = 3, arrival = [1,2,3,4], load = [1,2,1,2]) >>> [0] Explanation: The first 3 requests are handled by first 3 servers. Request 3 comes in. It is handled by server 0 since the server is available. Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. Example 3: >>> busiestServers(k = 3, arrival = [1,2,3], load = [10,12,11]) >>> [0,1,2] Explanation: Each server handles a single request, so they are all considered the busiest. """
special-array-with-x-elements-greater-than-or-equal-x
def specialArray(nums: List[int]) -> int: """ You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique. Example 1: >>> specialArray(nums = [3,5]) >>> 2 Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. Example 2: >>> specialArray(nums = [0,0]) >>> -1 Explanation: No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. Example 3: >>> specialArray(nums = [0,4,3,0,4]) >>> 3 Explanation: There are 3 values that are greater than or equal to 3. """
even-odd-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isEvenOddTree(root: Optional[TreeNode]) -> bool: """ A binary tree is named Even-Odd if it meets the following conditions: The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc. For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right). For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right). Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false. Example 1: >>> __init__(root = [1,10,4,3,null,7,9,12,8,6,null,null,2]) >>> true Explanation: The node values on each level are: Level 0: [1] Level 1: [10,4] Level 2: [3,7,9] Level 3: [12,8,6,2] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. Example 2: >>> __init__(root = [5,4,2,3,3,7]) >>> false Explanation: The node values on each level are: Level 0: [5] Level 1: [4,2] Level 2: [3,3,7] Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. Example 3: >>> __init__(root = [5,9,1,3,5,7]) >>> false Explanation: Node values in the level 1 should be even integers. """
maximum-number-of-visible-points
def visiblePoints(points: List[List[int]], angle: int, location: List[int]) -> int: """ You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see. Example 1: >>> visiblePoints(points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]) >>> 3 Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight. Example 2: >>> visiblePoints(points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]) >>> 4 Explanation: All points can be made visible in your field of view, including the one at your location. Example 3: >>> visiblePoints(points = [[1,0],[2,1]], angle = 13, location = [1,1]) >>> 1 Explanation: You can only see one of the two points, as shown above. """
minimum-one-bit-operations-to-make-integers-zero
def minimumOneBitOperations(n: int) -> int: """ Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. Example 1: >>> minimumOneBitOperations(n = 3) >>> 2 Explanation: The binary representation of 3 is "11". "11" -> "01" with the 2nd operation since the 0th bit is 1. "01" -> "00" with the 1st operation. Example 2: >>> minimumOneBitOperations(n = 6) >>> 4 Explanation: The binary representation of 6 is "110". "110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010" -> "011" with the 1st operation. "011" -> "001" with the 2nd operation since the 0th bit is 1. "001" -> "000" with the 1st operation. """
maximum-nesting-depth-of-the-parentheses
def maxDepth(s: str) -> int: """ Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses. Example 1: >>> maxDepth(s = "(1+(2*3)+((8)/4))+1") >>> 3 Explanation: Digit 8 is inside of 3 nested parentheses in the string. Example 2: >>> maxDepth(s = "(1)+((2))+(((3)))") >>> 3 Explanation: Digit 3 is inside of 3 nested parentheses in the string. Example 3: >>> maxDepth(s = "()(())((()()))") >>> 3 """
maximal-network-rank
def maximalNetworkRank(n: int, roads: List[List[int]]) -> int: """ There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads, return the maximal network rank of the entire infrastructure. Example 1: >>> maximalNetworkRank(n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]) >>> 4 Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. Example 2: >>> maximalNetworkRank(n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]) >>> 5 Explanation: There are 5 roads that are connected to cities 1 or 2. Example 3: >>> maximalNetworkRank(n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]) >>> 5 Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. """
split-two-strings-to-make-palindrome
def checkPalindromeFormation(a: str, b: str) -> bool: """ You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome. When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false. Notice that x + y denotes the concatenation of strings x and y. Example 1: >>> checkPalindromeFormation(a = "x", b = "y") >>> true Explaination: If either a or b are palindromes the answer is true since you can split in the following way: aprefix = "", asuffix = "x" bprefix = "", bsuffix = "y" Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome. Example 2: >>> checkPalindromeFormation(a = "xbdef", b = "xecab") >>> false Example 3: >>> checkPalindromeFormation(a = "ulacfd", b = "jizalu") >>> true Explaination: Split them at index 3: aprefix = "ula", asuffix = "cfd" bprefix = "jiz", bsuffix = "alu" Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome. """
count-subtrees-with-max-distance-between-cities
def countSubgraphsForEachDiameter(n: int, edges: List[List[int]]) -> List[int]: """ There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.\r \r A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\r \r For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.\r \r Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.\r \r Notice that the distance between the two cities is the number of edges in the path between them.\r \r  \r Example 1:\r \r \r \r \r >>> countSubgraphsForEachDiameter(n = 4, edges = [[1,2],[2,3],[2,4]]\r) >>> [3,4,0]\r Explanation:\r The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r No subtree has two nodes where the max distance between them is 3.\r \r \r Example 2:\r \r \r >>> countSubgraphsForEachDiameter(n = 2, edges = [[1,2]]\r) >>> [1]\r \r \r Example 3:\r \r \r >>> countSubgraphsForEachDiameter(n = 3, edges = [[1,2],[2,3]]\r) >>> [2,1]\r \r \r  \r """
mean-of-array-after-removing-some-elements
def trimMean(arr: List[int]) -> float: """ Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. Example 1: >>> trimMean(arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]) >>> 2.00000 Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. Example 2: >>> trimMean(arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]) >>> 4.00000 Example 3: >>> trimMean(arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]) >>> 4.77778 """
coordinate-with-maximum-network-quality
def bestCoordinate(towers: List[List[int]], radius: int) -> List[int]: """ You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance. You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable. The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate. Note: A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: x1 < x2, or x1 == x2 and y1 < y2. ⌊val⌋ is the greatest integer less than or equal to val (the floor function). Example 1: >>> bestCoordinate(towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2) >>> [2,1] Explanation: At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. Example 2: >>> bestCoordinate(towers = [[23,11,21]], radius = 9) >>> [23,11] Explanation: Since there is only one tower, the network quality is highest right at the tower's location. Example 3: >>> bestCoordinate(towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2) >>> [1,2] Explanation: Coordinate (1, 2) has the highest network quality. """
number-of-sets-of-k-non-overlapping-line-segments
def numberOfSets(n: int, k: int) -> int: """ Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7. Example 1: >>> numberOfSets(n = 4, k = 2) >>> 5 Explanation: The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. Example 2: >>> numberOfSets(n = 3, k = 1) >>> 3 Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. Example 3: >>> numberOfSets(n = 30, k = 7) >>> 796297179 Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. """
largest-substring-between-two-equal-characters
def maxLengthBetweenEqualCharacters(s: str) -> int: """ Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. Example 1: >>> maxLengthBetweenEqualCharacters(s = "aa") >>> 0 Explanation: The optimal substring here is an empty substring between the two 'a's. Example 2: >>> maxLengthBetweenEqualCharacters(s = "abca") >>> 2 Explanation: The optimal substring here is "bc". Example 3: >>> maxLengthBetweenEqualCharacters(s = "cbzxy") >>> -1 Explanation: There are no characters that appear twice in s. """
lexicographically-smallest-string-after-applying-operations
def findLexSmallestString(s: str, a: int, b: int) -> str: """ You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951". Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345". Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'. Example 1: >>> findLexSmallestString(s = "5525", a = 9, b = 2) >>> "2050" Explanation: We can apply the following operations: Start: "5525" Rotate: "2555" Add: "2454" Add: "2353" Rotate: "5323" Add: "5222" Add: "5121" Rotate: "2151" Add: "2050"​​​​​ There is no way to obtain a string that is lexicographically smaller than "2050". Example 2: >>> findLexSmallestString(s = "74", a = 5, b = 1) >>> "24" Explanation: We can apply the following operations: Start: "74" Rotate: "47" ​​​​​​​Add: "42" ​​​​​​​Rotate: "24"​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller than "24". Example 3: >>> findLexSmallestString(s = "0011", a = 4, b = 2) >>> "0011" Explanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011". """
best-team-with-no-conflicts
def bestTeamScore(scores: List[int], ages: List[int]) -> int: """ You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams. Example 1: >>> bestTeamScore(scores = [1,3,5,10,15], ages = [1,2,3,4,5]) >>> 34 Explanation: You can choose all the players. Example 2: >>> bestTeamScore(scores = [4,5,6,5], ages = [2,1,2,1]) >>> 16 Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. Example 3: >>> bestTeamScore(scores = [1,2,3,5], ages = [8,9,10,1]) >>> 6 Explanation: It is best to choose the first 3 players. """
graph-connectivity-with-threshold
def areConnected(n: int, threshold: int, queries: List[List[int]]) -> List[bool]: """ We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z > threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path. Example 1: >>> areConnected(n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]) >>> [false,false,true] Explanation: The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: [1,4] 1 is not connected to 4 [2,5] 2 is not connected to 5 [3,6] 3 is connected to 6 through path 3--6 Example 2: >>> areConnected(n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]) >>> [true,true,true,true,true] Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. Example 3: >>> areConnected(n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]) >>> [false,false,false,false,false] Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x]. """
slowest-key
def slowestKey(releaseTimes: List[int], keysPressed: str) -> str: """ A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. Example 1: >>> slowestKey(releaseTimes = [9,29,49,50], keysPressed = "cbcd") >>> "c" Explanation: The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. Example 2: >>> slowestKey(releaseTimes = [12,23,36,46,62], keysPressed = "spuda") >>> "a" Explanation: The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. """
arithmetic-subarrays
def checkArithmeticSubarrays(nums: List[int], l: List[int], r: List[int]) -> List[bool]: """ A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic: 1, 1, 2, 5, 7 You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. Example 1: >>> checkArithmeticSubarrays(nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]) >>> [true,false,true] Explanation: In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence. In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence. Example 2: >>> checkArithmeticSubarrays(nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]) >>> [false,true,false,false,true,true] """
path-with-minimum-effort
def minimumEffortPath(heights: List[List[int]]) -> int: """ You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. Example 1: >>> minimumEffortPath(heights = [[1,2,2],[3,8,2],[5,3,5]]) >>> 2 Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. Example 2: >>> minimumEffortPath(heights = [[1,2,3],[3,8,4],[5,3,5]]) >>> 1 Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. Example 3: >>> minimumEffortPath(heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]) >>> 0 Explanation: This route does not require any effort. """
rank-transform-of-a-matrix
def matrixRankTransform(matrix: List[List[int]]) -> List[List[int]]: """ Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The rank is an integer starting from 1. If two elements p and q are in the same row or column, then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q) The rank should be as small as possible. The test cases are generated so that answer is unique under the given rules. Example 1: >>> matrixRankTransform(matrix = [[1,2],[3,4]]) >>> [[1,2],[2,3]] Explanation: The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. Example 2: >>> matrixRankTransform(matrix = [[7,7],[7,7]]) >>> [[1,1],[1,1]] Example 3: >>> matrixRankTransform(matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]) >>> [[4,2,3],[1,3,4],[5,1,6],[1,3,4]] """
sort-array-by-increasing-frequency
def frequencySort(nums: List[int]) -> List[int]: """ Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. Example 1: >>> frequencySort(nums = [1,1,2,2,2,3]) >>> [3,1,1,2,2,2] Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. Example 2: >>> frequencySort(nums = [2,3,1,3,2]) >>> [1,3,3,2,2] Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. Example 3: >>> frequencySort(nums = [-1,1,-6,4,5,-6,1,4,1]) >>> [5,-1,4,4,-6,-6,1,1,1] """
widest-vertical-area-between-two-points-containing-no-points
def maxWidthOfVerticalArea(points: List[List[int]]) -> int: """ Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. Example 1: ​ >>> maxWidthOfVerticalArea(points = [[8,7],[9,9],[7,4],[9,7]]) >>> 1 Explanation: Both the red and the blue area are optimal. Example 2: >>> maxWidthOfVerticalArea(points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]) >>> 3 """
count-substrings-that-differ-by-one-character
def countSubstrings(s: str, t: str) -> int: """ Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. Example 1: >>> countSubstrings(s = "aba", t = "baba") >>> 6 Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character: ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") ("aba", "baba") The underlined portions are the substrings that are chosen from s and t. ​​Example 2: >>> countSubstrings(s = "ab", t = "bb") >>> 3 Explanation: The following are the pairs of substrings from s and t that differ by 1 character: ("ab", "bb") ("ab", "bb") ("ab", "bb") ​​​​The underlined portions are the substrings that are chosen from s and t. """
number-of-ways-to-form-a-target-string-given-a-dictionary
def numWays(words: List[str], target: str) -> int: """ You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: target should be formed from left to right. To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k]. Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string. Repeat the process until you form the string target. Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numWays(words = ["acca","bbbb","caca"], target = "aba") >>> 6 Explanation: There are 6 ways to form target. "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca") "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca") "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca") "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca") "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca") "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca") Example 2: >>> numWays(words = ["abba","baab"], target = "bab") >>> 4 Explanation: There are 4 ways to form target. "bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba") "bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab") "bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab") "bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab") """
check-array-formation-through-concatenation
def canFormArray(arr: List[int], pieces: List[List[int]]) -> bool: """ You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. Example 1: >>> canFormArray(arr = [15,88], pieces = [[88],[15]]) >>> true Explanation: Concatenate [15] then [88] Example 2: >>> canFormArray(arr = [49,18,16], pieces = [[16,18,49]]) >>> false Explanation: Even though the numbers match, we cannot reorder pieces[0]. Example 3: >>> canFormArray(arr = [91,4,64,78], pieces = [[78],[4,64],[91]]) >>> true Explanation: Concatenate [91] then [4,64] then [78] """
count-sorted-vowel-strings
def countVowelStrings(n: int) -> int: """ Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. Example 1: >>> countVowelStrings(n = 1) >>> 5 Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. Example 2: >>> countVowelStrings(n = 2) >>> 15 Explanation: The 15 sorted strings that consist of vowels only are ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. Example 3: >>> countVowelStrings(n = 33) >>> 66045 """
furthest-building-you-can-reach
def furthestBuilding(heights: List[int], bricks: int, ladders: int) -> int: """ You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks. If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks. Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. Example 1: >>> furthestBuilding(heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1) >>> 4 Explanation: Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders. Example 2: >>> furthestBuilding(heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2) >>> 7 Example 3: >>> furthestBuilding(heights = [14,3,19,3], bricks = 17, ladders = 0) >>> 3 """
kth-smallest-instructions
def kthSmallestPath(destination: List[int], k: int) -> str: """ Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are represented as a string, where each character is either: 'H', meaning move horizontally (go right), or 'V', meaning move vertically (go down). Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions. However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed. Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination. Example 1: >>> kthSmallestPath(destination = [2,3], k = 1) >>> "HHHVV" Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"]. Example 2: >>> kthSmallestPath(destination = [2,3], k = 2) >>> "HHVHV" Example 3: >>> kthSmallestPath(destination = [2,3], k = 3) >>> "HHVVH" """
lowest-common-ancestor-of-a-binary-tree-ii
# class TreeNode: # def __init__(x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """ Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique. According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)". A descendant of a node x is a node y that is on the path from node x to some leaf node. Example 1: >>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1) >>> 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: >>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4) >>> 5 Explanation: The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA. Example 3: >>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10) >>> null Explanation: Node 10 does not exist in the tree, so return null. """
get-maximum-in-generated-array
def getMaximumGenerated(n: int) -> int: """ You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: nums[0] = 0 nums[1] = 1 nums[2 * i] = nums[i] when 2 <= 2 * i <= n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n Return the maximum integer in the array nums​​​. Example 1: >>> getMaximumGenerated(n = 7) >>> 3 Explanation: According to the given rules: nums[0] = 0 nums[1] = 1 nums[(1 * 2) = 2] = nums[1] = 1 nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 nums[(2 * 2) = 4] = nums[2] = 1 nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 nums[(3 * 2) = 6] = nums[3] = 2 nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. Example 2: >>> getMaximumGenerated(n = 2) >>> 1 Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1. Example 3: >>> getMaximumGenerated(n = 3) >>> 2 Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2. """
minimum-deletions-to-make-character-frequencies-unique
def minDeletions(s: str) -> int: """ A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. Example 1: >>> minDeletions(s = "aab") >>> 0 Explanation: s is already good. Example 2: >>> minDeletions(s = "aaabbbcc") >>> 2 Explanation: You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". Example 3: >>> minDeletions(s = "ceabaacb") >>> 2 Explanation: You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). """
sell-diminishing-valued-colored-balls
def maxProfit(inventory: List[int], orders: int) -> int: """ You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. Example 1: >>> maxProfit(inventory = [2,5], orders = 4) >>> 14 Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3). The maximum total value is 2 + 5 + 4 + 3 = 14. Example 2: >>> maxProfit(inventory = [3,5], orders = 6) >>> 19 Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2). The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. """
create-sorted-array-through-instructions
def createSortedArray(instructions: List[int]) -> int: """ Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:\r \r \r The number of elements currently in nums that are strictly less than instructions[i].\r The number of elements currently in nums that are strictly greater than instructions[i].\r \r \r For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].\r \r Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7\r \r  \r Example 1:\r \r \r >>> createSortedArray(instructions = [1,5,6,2]\r) >>> 1\r Explanation: Begin with nums = [].\r Insert 1 with cost min(0, 0) = 0, now nums = [1].\r Insert 5 with cost min(1, 0) = 0, now nums = [1,5].\r Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\r Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\r The total cost is 0 + 0 + 0 + 1 = 1.\r \r Example 2:\r \r \r >>> createSortedArray(instructions = [1,2,3,6,5,4]\r) >>> 3\r Explanation: Begin with nums = [].\r Insert 1 with cost min(0, 0) = 0, now nums = [1].\r Insert 2 with cost min(1, 0) = 0, now nums = [1,2].\r Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\r Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\r Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\r Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\r The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\r \r \r Example 3:\r \r \r >>> createSortedArray(instructions = [1,3,3,3,2,4,2,1,2]\r) >>> 4\r Explanation: Begin with nums = [].\r Insert 1 with cost min(0, 0) = 0, now nums = [1].\r Insert 3 with cost min(1, 0) = 0, now nums = [1,3].\r Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\r Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\r Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\r Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\r ​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\r ​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\r ​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\r The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\r \r \r  \r """
defuse-the-bomb
def decrypt(code: List[int], k: int) -> List[int]: """ You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. If k > 0, replace the ith number with the sum of the next k numbers. If k < 0, replace the ith number with the sum of the previous k numbers. If k == 0, replace the ith number with 0. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! Example 1: >>> decrypt(code = [5,7,1,4], k = 3) >>> [12,10,16,13] Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around. Example 2: >>> decrypt(code = [1,2,3,4], k = 0) >>> [0,0,0,0] Explanation: When k is zero, the numbers are replaced by 0. Example 3: >>> decrypt(code = [2,4,9,3], k = -2) >>> [12,5,6,13] Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers. """
minimum-deletions-to-make-string-balanced
def minimumDeletions(s: str) -> int: """ You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. Example 1: >>> minimumDeletions(s = "aababbab") >>> 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). Example 2: >>> minimumDeletions(s = "bbaaaaabb") >>> 2 Explanation: The only solution is to delete the first two characters. """
minimum-jumps-to-reach-home
def minimumJumps(forbidden: List[int], a: int, b: int, x: int) -> int: """ A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. Example 1: >>> minimumJumps(forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9) >>> 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: >>> minimumJumps(forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11) >>> -1 Example 3: >>> minimumJumps(forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7) >>> 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. """
distribute-repeating-integers
def canDistribute(nums: List[int], quantity: List[int]) -> bool: """ You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer gets exactly quantity[i] integers, The integers the ith customer gets are all equal, and Every customer is satisfied. Return true if it is possible to distribute nums according to the above conditions. Example 1: >>> canDistribute(nums = [1,2,3,4], quantity = [2]) >>> false Explanation: The 0th customer cannot be given two different integers. Example 2: >>> canDistribute(nums = [1,2,3,3], quantity = [2]) >>> true Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. Example 3: >>> canDistribute(nums = [1,1,2,2], quantity = [2,2]) >>> true Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2]. """
determine-if-two-strings-are-close
def closeStrings(word1: str, word2: str) -> bool: """ Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary. Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. Example 1: >>> closeStrings(word1 = "abc", word2 = "bca") >>> true Explanation: You can attain word2 from word1 in 2 operations. Apply Operation 1: "abc" -> "acb" Apply Operation 1: "acb" -> "bca" Example 2: >>> closeStrings(word1 = "a", word2 = "aa") >>> false Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. Example 3: >>> closeStrings(word1 = "cabbba", word2 = "abbccc") >>> true Explanation: You can attain word2 from word1 in 3 operations. Apply Operation 1: "cabbba" -> "caabbb" Apply Operation 2: "caabbb" -> "baaccc" Apply Operation 2: "baaccc" -> "abbccc" """
minimum-operations-to-reduce-x-to-zero
def minOperations(nums: List[int], x: int) -> int: """ You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. Example 1: >>> minOperations(nums = [1,1,4,2,3], x = 5) >>> 2 Explanation: The optimal solution is to remove the last two elements to reduce x to zero. Example 2: >>> minOperations(nums = [5,6,7,8,9], x = 4) >>> -1 Example 3: >>> minOperations(nums = [3,2,20,1,1,3], x = 10) >>> 5 Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. """
maximize-grid-happiness
def getMaxGridHappiness(m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int: """ You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert). Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert). Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness. Example 1: >>> getMaxGridHappiness(m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2) >>> 240 Explanation: Assume the grid is 1-indexed with coordinates (row, column). We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3). - Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120 - Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 - Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 The grid happiness is 120 + 60 + 60 = 240. The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells. Example 2: >>> getMaxGridHappiness(m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1) >>> 260 Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1). - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80 - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 The grid happiness is 90 + 80 + 90 = 260. Example 3: >>> getMaxGridHappiness(m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0) >>> 240 """
check-if-two-string-arrays-are-equivalent
def arrayStringsAreEqual(word1: List[str], word2: List[str]) -> bool: """ Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. Example 1: >>> arrayStringsAreEqual(word1 = ["ab", "c"], word2 = ["a", "bc"]) >>> true Explanation: word1 represents string "ab" + "c" -> "abc" word2 represents string "a" + "bc" -> "abc" The strings are the same, so return true. Example 2: >>> arrayStringsAreEqual(word1 = ["a", "cb"], word2 = ["ab", "c"]) >>> false Example 3: >>> arrayStringsAreEqual(word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]) >>> true """
smallest-string-with-a-given-numeric-value
def getSmallestString(n: int, k: int) -> str: """ The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. Example 1: >>> getSmallestString(n = 3, k = 27) >>> "aay" Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. Example 2: >>> getSmallestString(n = 5, k = 73) >>> "aaszz" """
ways-to-make-a-fair-array
def waysToMakeFair(nums: List[int]) -> int: """ You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums = [6,1,4,1]. Choosing to remove index 4 results in nums = [6,1,7,4]. An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair. Example 1: >>> waysToMakeFair(nums = [2,1,6,4]) >>> 1 Explanation: Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. Example 2: >>> waysToMakeFair(nums = [1,1,1]) >>> 3 Explanation: You can remove any index and the remaining array is fair. Example 3: >>> waysToMakeFair(nums = [1,2,3]) >>> 0 Explanation: You cannot make a fair array after removing any index. """
minimum-initial-energy-to-finish-tasks
def minimumEffort(tasks: List[List[int]]) -> int: """ You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks. Example 1: >>> minimumEffort(tasks = [[1,2],[2,4],[4,8]]) >>> 8 Explanation: Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. Example 2: >>> minimumEffort(tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]) >>> 32 Explanation: Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. Example 3: >>> minimumEffort(tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]) >>> 27 Explanation: Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6. """
maximum-repeating-substring
def maxRepeating(sequence: str, word: str) -> int: """ For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. Example 1: >>> maxRepeating(sequence = "ababc", word = "ab") >>> 2 Explanation: "abab" is a substring in "ababc". Example 2: >>> maxRepeating(sequence = "ababc", word = "ba") >>> 1 Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc". Example 3: >>> maxRepeating(sequence = "ababc", word = "ac") >>> 0 Explanation: "ac" is not a substring in "ababc". """
merge-in-between-linked-lists
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def mergeInBetween(list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: """ You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. Example 1: >>> __init__(list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]) >>> [10,1,13,1000000,1000001,1000002,5] Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. Example 2: >>> __init__(list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]) >>> [0,1,1000000,1000001,1000002,1000003,1000004,6] Explanation: The blue edges and nodes in the above figure indicate the result. """
minimum-number-of-removals-to-make-mountain-array
def minimumMountainRemovals(nums: List[int]) -> int: """ You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array. Example 1: >>> minimumMountainRemovals(nums = [1,3,1]) >>> 0 Explanation: The array itself is a mountain array so we do not need to remove any elements. Example 2: >>> minimumMountainRemovals(nums = [2,1,1,5,6,2,3,1]) >>> 3 Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. """
richest-customer-wealth
def maximumWealth(accounts: List[List[int]]) -> int: """ You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. Example 1: >>> maximumWealth(accounts = [[1,2,3],[3,2,1]]) >>> 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. Example 2: >>> maximumWealth(accounts = [[1,5],[7,3],[3,5]]) >>> 10 Explanation: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. Example 3: >>> maximumWealth(accounts = [[2,8,7],[7,1,3],[1,9,5]]) >>> 17 """
find-the-most-competitive-subsequence
def mostCompetitive(nums: List[int], k: int) -> List[int]: """ Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. Example 1: >>> mostCompetitive(nums = [3,5,2,6], k = 2) >>> [2,6] Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. Example 2: >>> mostCompetitive(nums = [2,4,3,3,5,4,9,6], k = 4) >>> [2,3,3,4] """
minimum-moves-to-make-array-complementary
def minMoves(nums: List[int], limit: int) -> int: """ You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary. Example 1: >>> minMoves(nums = [1,2,4,3], limit = 4) >>> 1 Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed). nums[0] + nums[3] = 1 + 3 = 4. nums[1] + nums[2] = 2 + 2 = 4. nums[2] + nums[1] = 2 + 2 = 4. nums[3] + nums[0] = 3 + 1 = 4. Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. Example 2: >>> minMoves(nums = [1,2,2,1], limit = 2) >>> 2 Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit. Example 3: >>> minMoves(nums = [1,2,1,2], limit = 2) >>> 0 Explanation: nums is already complementary. """
minimize-deviation-in-array
def minimumDeviation(nums: List[int]) -> int: """ You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the element is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4]. The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations. Example 1: >>> minimumDeviation(nums = [1,2,3,4]) >>> 1 Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. Example 2: >>> minimumDeviation(nums = [4,1,5,20,3]) >>> 3 Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. Example 3: >>> minimumDeviation(nums = [2,10,8]) >>> 3 """
goal-parser-interpretation
def interpret(command: str) -> str: """ You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. Given the string command, return the Goal Parser's interpretation of command. Example 1: >>> interpret(command = "G()(al)") >>> "Goal" Explanation: The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal". Example 2: >>> interpret(command = "G()()()()(al)") >>> "Gooooal" Example 3: >>> interpret(command = "(al)G(al)()()G") >>> "alGalooG" """
max-number-of-k-sum-pairs
def maxOperations(nums: List[int], k: int) -> int: """ You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. Example 1: >>> maxOperations(nums = [1,2,3,4], k = 5) >>> 2 Explanation: Starting with nums = [1,2,3,4]: - Remove numbers 1 and 4, then nums = [2,3] - Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations. Example 2: >>> maxOperations(nums = [3,1,3,4,3], k = 6) >>> 1 Explanation: Starting with nums = [3,1,3,4,3]: - Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation. """
concatenation-of-consecutive-binary-numbers
def concatenatedBinary(n: int) -> int: """ Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. Example 1: >>> concatenatedBinary(n = 1) >>> 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: >>> concatenatedBinary(n = 3) >>> 27 Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11". After concatenating them, we have "11011", which corresponds to the decimal value 27. Example 3: >>> concatenatedBinary(n = 12) >>> 505379714 Explanation: The concatenation results in "1101110010111011110001001101010111100". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. """
minimum-incompatibility
def minimumIncompatibility(nums: List[int], k: int) -> int: """ You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. Example 1: >>> minimumIncompatibility(nums = [1,2,1,4], k = 2) >>> 4 Explanation: The optimal distribution of subsets is [1,2] and [1,4]. The incompatibility is (2-1) + (4-1) = 4. Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements. Example 2: >>> minimumIncompatibility(nums = [6,3,8,1,3,1,2,2], k = 4) >>> 6 Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. Example 3: >>> minimumIncompatibility(nums = [5,3,3,6,3,3], k = 3) >>> -1 Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset. """
longest-palindromic-subsequence-ii
def longestPalindromeSubseq(s: str) -> int: """ A subsequence of a string s is considered a good palindromic subsequence if: It is a subsequence of s. It is a palindrome (has the same value if reversed). It has an even length. No two consecutive characters are equal, except the two middle ones. For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence, while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not. Given a string s, return the length of the longest good palindromic subsequence in s. Example 1: >>> longestPalindromeSubseq(s = "bbabab") >>> 4 Explanation: The longest good palindromic subsequence of s is "baab". Example 2: >>> longestPalindromeSubseq(s = "dcbccacdb") >>> 4 Explanation: The longest good palindromic subsequence of s is "dccd". """
count-the-number-of-consistent-strings
def countConsistentStrings(allowed: str, words: List[str]) -> int: """ You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: >>> countConsistentStrings(allowed = "ab", words = ["ad","bd","aaab","baa","badab"]) >>> 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. Example 2: >>> countConsistentStrings(allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]) >>> 7 Explanation: All strings are consistent. Example 3: >>> countConsistentStrings(allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]) >>> 4 Explanation: Strings "cc", "acd", "ac", and "d" are consistent. """
sum-of-absolute-differences-in-a-sorted-array
def getSumAbsoluteDifferences(nums: List[int]) -> List[int]: """ You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed). Example 1: >>> getSumAbsoluteDifferences(nums = [2,3,5]) >>> [4,3,5] Explanation: Assuming the arrays are 0-indexed, then result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. Example 2: >>> getSumAbsoluteDifferences(nums = [1,4,6,8,10]) >>> [24,15,13,15,21] """
stone-game-vi
def stoneGameVI(aliceValues: List[int], bobValues: List[int]) -> int: """ Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently. You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone. The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values. Determine the result of the game, and: If Alice wins, return 1. If Bob wins, return -1. If the game results in a draw, return 0. Example 1: >>> stoneGameVI(aliceValues = [1,3], bobValues = [2,1]) >>> 1 Explanation: If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points. Bob can only choose stone 0, and will only receive 2 points. Alice wins. Example 2: >>> stoneGameVI(aliceValues = [1,2], bobValues = [3,1]) >>> 0 Explanation: If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. Draw. Example 3: >>> stoneGameVI(aliceValues = [2,4,3], bobValues = [1,6,7]) >>> -1 Explanation: Regardless of how Alice plays, Bob will be able to have more points than Alice. For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7. Bob wins. """
delivering-boxes-from-storage-to-ports
def boxDelivering(boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: """ You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight. ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. Example 1: >>> boxDelivering(boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3) >>> 4 Explanation: The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). Example 2: >>> boxDelivering(boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6) >>> 6 Explanation: The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. Example 3: >>> boxDelivering(boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7) >>> 6 Explanation: The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. """
count-of-matches-in-tournament
def numberOfMatches(n: int) -> int: """ You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. Example 1: >>> numberOfMatches(n = 7) >>> 6 Explanation: Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. Example 2: >>> numberOfMatches(n = 14) >>> 13 Explanation: Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. """
partitioning-into-minimum-number-of-deci-binary-numbers
def minPartitions(n: str) -> int: """ A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. Example 1: >>> minPartitions(n = "32") >>> 3 Explanation: 10 + 11 + 11 = 32 Example 2: >>> minPartitions(n = "82734") >>> 8 Example 3: >>> minPartitions(n = "27346209830709182346") >>> 9 """
stone-game-vii
def stoneGameVII(stones: List[int]) -> int: """ Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally. Example 1: >>> stoneGameVII(stones = [5,3,1,4,2]) >>> 6 Explanation: - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = []. The score difference is 18 - 12 = 6. Example 2: >>> stoneGameVII(stones = [7,90,5,1,100,10,10,2]) >>> 122 """
maximum-height-by-stacking-cuboids
def maxHeight(cuboids: List[List[int]]) -> int: """ Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. Example 1: >>> maxHeight(cuboids = [[50,45,20],[95,37,53],[45,23,12]]) >>> 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: >>> maxHeight(cuboids = [[38,25,45],[76,35,3]]) >>> 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: >>> maxHeight(cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]) >>> 102 Explanation: After rearranging the cuboids, you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102. """
count-ways-to-distribute-candies
def waysToDistribute(n: int, k: int) -> int: """ There are n unique candies (labeled 1 through n) and k bags. You are asked to distribute all the candies into the bags such that every bag has at least one candy. There can be multiple ways to distribute the candies. Two ways are considered different if the candies in one bag in the first way are not all in the same bag in the second way. The order of the bags and the order of the candies within each bag do not matter. For example, (1), (2,3) and (2), (1,3) are considered different because candies 2 and 3 in the bag (2,3) in the first way are not in the same bag in the second way (they are split between the bags (2) and (1,3)). However, (1), (2,3) and (3,2), (1) are considered the same because the candies in each bag are all in the same bags in both ways. Given two integers, n and k, return the number of different ways to distribute the candies. As the answer may be too large, return it modulo 109 + 7. Example 1: >>> waysToDistribute(n = 3, k = 2) >>> 3 Explanation: You can distribute 3 candies into 2 bags in 3 ways: (1), (2,3) (1,2), (3) (1,3), (2) Example 2: >>> waysToDistribute(n = 4, k = 2) >>> 7 Explanation: You can distribute 4 candies into 2 bags in 7 ways: (1), (2,3,4) (1,2), (3,4) (1,3), (2,4) (1,4), (2,3) (1,2,3), (4) (1,2,4), (3) (1,3,4), (2) Example 3: >>> waysToDistribute(n = 20, k = 5) >>> 206085257 Explanation: You can distribute 20 candies into 5 bags in 1881780996 ways. 1881780996 modulo 109 + 7 = 206085257. """
reformat-phone-number
def reformatNumber(number: str) -> str: """ You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'. You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: 2 digits: A single block of length 2. 3 digits: A single block of length 3. 4 digits: Two blocks of length 2 each. The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting. Example 1: >>> reformatNumber(number = "1-23-45 6") >>> "123-456" Explanation: The digits are "123456". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456". Joining the blocks gives "123-456". Example 2: >>> reformatNumber(number = "123 4-567") >>> "123-45-67" Explanation: The digits are "1234567". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67". Joining the blocks gives "123-45-67". Example 3: >>> reformatNumber(number = "123 4-5678") >>> "123-456-78" Explanation: The digits are "12345678". Step 1: The 1st block is "123". Step 2: The 2nd block is "456". Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78". Joining the blocks gives "123-456-78". """
maximum-erasure-value
def maximumUniqueSubarray(nums: List[int]) -> int: """ You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). Example 1: >>> maximumUniqueSubarray(nums = [4,2,4,5,6]) >>> 17 Explanation: The optimal subarray here is [2,4,5,6]. Example 2: >>> maximumUniqueSubarray(nums = [5,2,1,2,5,2,1,2,5]) >>> 8 Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. """
jump-game-vi
def maxResult(nums: List[int], k: int) -> int: """ You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get. Example 1: >>> maxResult(nums = [1,-1,-2,4,-7,3], k = 2) >>> 7 Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. Example 2: >>> maxResult(nums = [10,-5,-2,4,0,3], k = 3) >>> 17 Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. Example 3: >>> maxResult(nums = [1,-5,-20,4,-1,3,-6,-3], k = 2) >>> 0 """
checking-existence-of-edge-length-limited-paths
def distanceLimitedPathsExist(n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]: """ An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise. Example 1: >>> distanceLimitedPathsExist(n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]) >>> [false,true] Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. Example 2: >>> distanceLimitedPathsExist(n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]) >>> [true,false] Explanation: The above figure shows the given graph. """
number-of-distinct-substrings-in-a-string
def countDistinct(s: str) -> int: """ Given a string s, return the number of distinct substrings of s. A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string. Example 1: >>> countDistinct(s = "aabbaba") >>> 21 Explanation: The set of distinct strings is ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"] Example 2: >>> countDistinct(s = "abcdefg") >>> 28 """
number-of-students-unable-to-eat-lunch
def countStudents(students: List[int], sandwiches: List[int]) -> int: """ The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat. Example 1: >>> countStudents(students = [1,1,0,0], sandwiches = [0,1,0,1]) >>> 0 Explanation: - Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. Hence all students are able to eat. Example 2: >>> countStudents(students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]) >>> 3 """
average-waiting-time
def averageWaitingTime(customers: List[List[int]]) -> float: """ There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]: arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order. timei is the time needed to prepare the order of the ith customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input. Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted. Example 1: >>> averageWaitingTime(customers = [[1,2],[2,5],[4,3]]) >>> 5.00000 Explanation: 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. Example 2: >>> averageWaitingTime(customers = [[5,2],[5,4],[10,3],[20,1]]) >>> 3.25000 Explanation: 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. """
maximum-binary-string-after-change
def maximumBinaryString(binary: str) -> str: """ You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation. Example 1: >>> maximumBinaryString(binary = "000110") >>> "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: >>> maximumBinaryString(binary = "01") >>> "01" Explanation: "01" cannot be transformed any further. """
minimum-adjacent-swaps-for-k-consecutive-ones
def minMoves(nums: List[int], k: int) -> int: """ You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's. Example 1: >>> minMoves(nums = [1,0,0,1,0,1], k = 2) >>> 1 Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. Example 2: >>> minMoves(nums = [1,0,0,0,0,0,1,1], k = 3) >>> 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. Example 3: >>> minMoves(nums = [1,1,0,1], k = 2) >>> 0 Explanation: nums already has 2 consecutive 1's. """
determine-if-string-halves-are-alike
def halvesAreAlike(s: str) -> bool: """ You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false. Example 1: >>> halvesAreAlike(s = "book") >>> true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: >>> halvesAreAlike(s = "textbook") >>> false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. """
maximum-number-of-eaten-apples
def eatenApples(apples: List[int], days: List[int]) -> int: """ There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. Example 1: >>> eatenApples(apples = [1,2,3,5,2], days = [3,2,1,4,2]) >>> 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. Example 2: >>> eatenApples(apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]) >>> 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. """
where-will-the-ball-fall
def findBall(grid: List[List[int]]) -> List[int]: """ You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box. Example 1: >>> findBall(grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]) >>> [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: >>> findBall(grid = [[-1]]) >>> [-1] Explanation: The ball gets stuck against the left wall. Example 3: >>> findBall(grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]) >>> [0,1,2,3,4,-1] """
maximum-xor-with-an-element-from-array
def maximizeXor(nums: List[int], queries: List[List[int]]) -> List[int]: """ You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query. Example 1: >>> maximizeXor(nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]) >>> [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. Example 2: >>> maximizeXor(nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]) >>> [15,-1,5] """
largest-subarray-length-k
def largestSubarray(nums: List[int], k: int) -> List[int]: """ An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i]. For example, consider 0-indexing: [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2. [1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2. A subarray is a contiguous subsequence of the array. Given an integer array nums of distinct integers, return the largest subarray of nums of length k. Example 1: >>> largestSubarray(nums = [1,4,5,2,3], k = 3) >>> [5,2,3] Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3]. Of these, [5,2,3] is the largest. Example 2: >>> largestSubarray(nums = [1,4,5,2,3], k = 4) >>> [4,5,2,3] Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3]. Of these, [4,5,2,3] is the largest. Example 3: >>> largestSubarray(nums = [1,4,5,2,3], k = 1) >>> [5] """
maximum-units-on-a-truck
def maximumUnits(boxTypes: List[List[int]], truckSize: int) -> int: """ You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the type i. You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck. Example 1: >>> maximumUnits(boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4) >>> 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. Example 2: >>> maximumUnits(boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10) >>> 91 """
count-good-meals
def countPairs(deliciousness: List[int]) -> int: """ A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value. Example 1: >>> countPairs(deliciousness = [1,3,5,7,9]) >>> 4 Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. Example 2: >>> countPairs(deliciousness = [1,1,1,3,3,3,7]) >>> 15 Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. """
ways-to-split-array-into-three-subarrays
def waysToSplit(nums: List[int]) -> int: """ A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7. Example 1: >>> waysToSplit(nums = [1,1,1]) >>> 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: >>> waysToSplit(nums = [1,2,2,2,5,0]) >>> 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: >>> waysToSplit(nums = [3,2,1]) >>> 0 Explanation: There is no good way to split nums. """
minimum-operations-to-make-a-subsequence
def minOperations(target: List[int], arr: List[int]) -> int: """ You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. Example 1: >>> minOperations(target = [5,1,3], arr = [9,4,2,3,4]) >>> 2 Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. Example 2: >>> minOperations(target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]) >>> 3 """
sum-of-special-evenly-spaced-elements-in-array
def solve(nums: List[int], queries: List[List[int]]) -> List[int]: """ You are given a 0-indexed integer array nums consisting of n non-negative integers. You are also given an array queries, where queries[i] = [xi, yi]. The answer to the ith query is the sum of all nums[j] where xi <= j < n and (j - xi) is divisible by yi. Return an array answer where answer.length == queries.length and answer[i] is the answer to the ith query modulo 109 + 7. Example 1: >>> solve(nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1],[4,2]]) >>> [9,18,10] Explanation: The answers of the queries are as follows: 1) The j indices that satisfy this query are 0, 3, and 6. nums[0] + nums[3] + nums[6] = 9 2) The j indices that satisfy this query are 5, 6, and 7. nums[5] + nums[6] + nums[7] = 18 3) The j indices that satisfy this query are 4 and 6. nums[4] + nums[6] = 10 Example 2: >>> solve(nums = [100,200,101,201,102,202,103,203], queries = [[0,7]]) >>> [303] """
calculate-money-in-leetcode-bank
def totalMoney(n: int) -> int: """ Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day. Example 1: >>> totalMoney(n = 4) >>> 10 Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. Example 2: >>> totalMoney(n = 10) >>> 37 Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. Example 3: >>> totalMoney(n = 20) >>> 96 Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. """
maximum-score-from-removing-substrings
def maximumGain(s: str, x: int, y: int) -> int: """ You are given a string s and two integers x and y. You can perform two types of operations any number of times. Remove substring "ab" and gain x points. For example, when removing "ab" from "cabxbae" it becomes "cxbae". Remove substring "ba" and gain y points. For example, when removing "ba" from "cabxbae" it becomes "cabxe". Return the maximum points you can gain after applying the above operations on s. Example 1: >>> maximumGain(s = "cdbcbbaaabab", x = 4, y = 5) >>> 19 Explanation: - Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. - Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. - Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. Example 2: >>> maximumGain(s = "aabbaaxybbaabb", x = 5, y = 4) >>> 20 """
construct-the-lexicographically-largest-valid-sequence
def constructDistancedSequence(n: int) -> List[int]: """ Given an integer n, find a sequence with elements in the range [1, n] that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For every integer i between 2 and n, the distance between the two occurrences of i is exactly i. The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|. Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5. Example 1: >>> constructDistancedSequence(n = 3) >>> [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. Example 2: >>> constructDistancedSequence(n = 5) >>> [5,3,1,4,3,5,2,4,2] """
number-of-ways-to-reconstruct-a-tree
def checkWays(pairs: List[List[int]]) -> int: """ You are given an array pairs, where pairs[i] = [xi, yi], and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose values appeared in pairs. A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi. Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: 0 if ways == 0 1 if ways == 1 2 if ways > 1 A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. Example 1: >>> checkWays(pairs = [[1,2],[2,3]]) >>> 1 Explanation: There is exactly one valid rooted tree, which is shown in the above figure. Example 2: >>> checkWays(pairs = [[1,2],[2,3],[1,3]]) >>> 2 Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. Example 3: >>> checkWays(pairs = [[1,2],[2,3],[2,4],[1,5]]) >>> 0 Explanation: There are no valid rooted trees. """
decode-xored-array
def decode(encoded: List[int], first: int) -> List[int]: """ There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique. Example 1: >>> decode(encoded = [1,2,3], first = 1) >>> [1,0,2,1] Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] Example 2: >>> decode(encoded = [6,2,7,3], first = 4) >>> [4,2,0,7,4] """