task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
intersection-of-three-sorted-arrays
def arraysIntersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: """ Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. Example 1: >>> arraysIntersection(arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]) >>> [1,5] Explanation: Only 1 and 5 appeared in the three arrays. Example 2: >>> arraysIntersection(arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]) >>> [] """
two-sum-bsts
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def twoSumBSTs(root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool: """ Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target. Example 1: >>> __init__(root1 = [2,1,4], root2 = [1,0,3], target = 5) >>> true Explanation: 2 and 3 sum up to 5. Example 2: >>> __init__(root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18) >>> false """
stepping-numbers
def countSteppingNumbers(low: int, high: int) -> List[int]: """ A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1. For example, 321 is a stepping number while 421 is not. Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high]. Example 1: >>> countSteppingNumbers(low = 0, high = 21) >>> [0,1,2,3,4,5,6,7,8,9,10,12,21] Example 2: >>> countSteppingNumbers(low = 10, high = 15) >>> [10,12] """
valid-palindrome-iii
def isValidPalindrome(s: str, k: int) -> bool: """ Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it. Example 1: >>> isValidPalindrome(s = "abcdeca", k = 2) >>> true Explanation: Remove 'b' and 'e' characters. Example 2: >>> isValidPalindrome(s = "abbababa", k = 1) >>> true """
minimum-cost-to-move-chips-to-the-same-position
def minCostToMoveChips(position: List[int]) -> int: """ We have n chips, where the position of the ith chip is position[i]. We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to: position[i] + 2 or position[i] - 2 with cost = 0. position[i] + 1 or position[i] - 1 with cost = 1. Return the minimum cost needed to move all the chips to the same position. Example 1: >>> minCostToMoveChips(position = [1,2,3]) >>> 1 Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. Example 2: >>> minCostToMoveChips(position = [2,2,2,3,3]) >>> 2 Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2. Example 3: >>> minCostToMoveChips(position = [1,1000000000]) >>> 1 """
longest-arithmetic-subsequence-of-given-difference
def longestSubsequence(arr: List[int], difference: int) -> int: """ Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements. Example 1: >>> longestSubsequence(arr = [1,2,3,4], difference = 1) >>> 4 Explanation: The longest arithmetic subsequence is [1,2,3,4]. Example 2: >>> longestSubsequence(arr = [1,3,5,7], difference = 1) >>> 1 Explanation: The longest arithmetic subsequence is any single element. Example 3: >>> longestSubsequence(arr = [1,5,7,8,5,3,4,2,1], difference = -2) >>> 4 Explanation: The longest arithmetic subsequence is [7,5,3,1]. """
path-with-maximum-gold
def getMaximumGold(grid: List[List[int]]) -> int: """ In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position, you can walk one step to the left, right, up, or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: >>> getMaximumGold(grid = [[0,6,0],[5,8,7],[0,9,0]]) >>> 24 Explanation: [[0,6,0], [5,8,7], [0,9,0]] Path to get the maximum gold, 9 -> 8 -> 7. Example 2: >>> getMaximumGold(grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]) >>> 28 Explanation: [[1,0,7], [2,0,6], [3,4,5], [0,3,0], [9,0,20]] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. """
count-vowels-permutation
def countVowelPermutation(n: int) -> int: """ Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or an 'i'. Each vowel 'i' may not be followed by another 'i'. Each vowel 'o' may only be followed by an 'i' or a 'u'. Each vowel 'u' may only be followed by an 'a'. Since the answer may be too large, return it modulo 10^9 + 7. Example 1: >>> countVowelPermutation(n = 1) >>> 5 Explanation: All possible strings are: "a", "e", "i" , "o" and "u". Example 2: >>> countVowelPermutation(n = 2) >>> 10 Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". Example 3: >>> countVowelPermutation(n = 5) >>> 68 """
split-a-string-in-balanced-strings
def balancedStringSplit(s: str) -> int: """ Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: Each substring is balanced. Return the maximum number of balanced strings you can obtain. Example 1: >>> balancedStringSplit(s = "RLRRLLRLRL") >>> 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. Example 2: >>> balancedStringSplit(s = "RLRRRLLRLL") >>> 2 Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced. Example 3: >>> balancedStringSplit(s = "LLLLRRRR") >>> 1 Explanation: s can be split into "LLLLRRRR". """
queens-that-can-attack-the-king
def queensAttacktheKing(queens: List[List[int]], king: List[int]) -> List[List[int]]: """ On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king. You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king. Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order. Example 1: >>> queensAttacktheKing(queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]) >>> [[0,1],[1,0],[3,3]] Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes). Example 2: >>> queensAttacktheKing(queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]) >>> [[2,2],[3,4],[4,4]] Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes). """
dice-roll-simulation
def dieSimulator(n: int, rollMax: List[int]) -> int: """ A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7. Two sequences are considered different if at least one element differs from each other. Example 1: >>> dieSimulator(n = 2, rollMax = [1,1,2,2,2,3]) >>> 34 Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. Example 2: >>> dieSimulator(n = 2, rollMax = [1,1,1,1,1,1]) >>> 30 Example 3: >>> dieSimulator(n = 3, rollMax = [1,1,1,2,2,3]) >>> 181 """
maximum-equal-frequency
def maxEqualFreq(nums: List[int]) -> int: """ Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Example 1: >>> maxEqualFreq(nums = [2,2,1,1,5,3,3,5]) >>> 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: >>> maxEqualFreq(nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]) >>> 13 """
airplane-seat-assignment-probability
def nthPersonGetsNthSeat(n: int) -> float: """ n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Take their own seat if it is still available, and Pick other seats randomly when they find their seat occupied Return the probability that the nth person gets his own seat. Example 1: >>> nthPersonGetsNthSeat(n = 1) >>> 1.00000 Explanation: The first person can only get the first seat. Example 2: >>> nthPersonGetsNthSeat(n = 2) >>> 0.50000 Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat). """
missing-number-in-arithmetic-progression
def missingNumber(arr: List[int]) -> int: """ In some array arr, the values were in arithmetic progression: the values arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1. A value from arr was removed that was not the first or last value in the array. Given arr, return the removed value. Example 1: >>> missingNumber(arr = [5,7,11,13]) >>> 9 Explanation: The previous array was [5,7,9,11,13]. Example 2: >>> missingNumber(arr = [15,13,12]) >>> 14 Explanation: The previous array was [15,14,13,12]. """
meeting-scheduler
def minAvailableDuration(slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]: """ Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration. If there is no common time slot that satisfies the requirements, return an empty array. The format of a time slot is an array of two elements [start, end] representing an inclusive time range from start to end. It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots [start1, end1] and [start2, end2] of the same person, either start1 > end2 or start2 > end1. Example 1: >>> minAvailableDuration(slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8) >>> [60,68] Example 2: >>> minAvailableDuration(slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12) >>> [] """
toss-strange-coins
def probabilityOfHeads(prob: List[float], target: int) -> float: """ You have some coins.  The i-th coin has a probability prob[i] of facing heads when tossed. Return the probability that the number of coins facing heads equals target if you toss every coin exactly once. Example 1: >>> probabilityOfHeads(prob = [0.4], target = 1) >>> 0.40000 Example 2: >>> probabilityOfHeads(prob = [0.5,0.5,0.5,0.5,0.5], target = 0) >>> 0.03125 """
divide-chocolate
def maximizeSweetness(sweetness: List[int], k: int) -> int: """ You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness. You want to share the chocolate with your k friends so you start cutting the chocolate bar into k + 1 pieces using k cuts, each piece consists of some consecutive chunks. Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends. Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally. Example 1: >>> maximizeSweetness(sweetness = [1,2,3,4,5,6,7,8,9], k = 5) >>> 6 Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9] Example 2: >>> maximizeSweetness(sweetness = [5,6,7,8,9,1,2,3,4], k = 8) >>> 1 Explanation: There is only one way to cut the bar into 9 pieces. Example 3: >>> maximizeSweetness(sweetness = [1,2,2,1,2,2,1,2,2], k = 2) >>> 5 Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2] """
check-if-it-is-a-straight-line
def checkStraightLine(coordinates: List[List[int]]) -> bool: """ You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: >>> checkStraightLine(coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]) >>> true Example 2: >>> checkStraightLine(coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]) >>> false """
remove-sub-folders-from-the-filesystem
def removeSubfolders(folder: List[str]) -> List[str]: """ Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order. If a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j] must start with folder[j], followed by a "/". For example, "/a/b" is a sub-folder of "/a", but "/b" is not a sub-folder of "/a/b/c". The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not. Example 1: >>> removeSubfolders(folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]) >>> ["/a","/c/d","/c/f"] Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem. Example 2: >>> removeSubfolders(folder = ["/a","/a/b/c","/a/b/d"]) >>> ["/a"] Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a". Example 3: >>> removeSubfolders(folder = ["/a/b/c","/a/b/ca","/a/b/d"]) >>> ["/a/b/c","/a/b/ca","/a/b/d"] """
replace-the-substring-for-balanced-string
def balancedString(s: str) -> int: """ You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0. Example 1: >>> balancedString(s = "QWER") >>> 0 Explanation: s is already balanced. Example 2: >>> balancedString(s = "QQWE") >>> 1 Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced. Example 3: >>> balancedString(s = "QQQW") >>> 2 Explanation: We can replace the first "QQ" to "ER". """
maximum-profit-in-job-scheduling
def jobScheduling(startTime: List[int], endTime: List[int], profit: List[int]) -> int: """ We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X. Example 1: >>> jobScheduling(startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]) >>> 120 Explanation: The subset chosen is the first and fourth job. Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70. Example 2: >>> jobScheduling(startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]) >>> 150 Explanation: The subset chosen is the first, fourth and fifth job. Profit obtained 150 = 20 + 70 + 60. Example 3: >>> jobScheduling(startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]) >>> 6 """
circular-permutation-in-binary-representation
def circularPermutation(n: int, start: int) -> List[int]: """ Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :\r \r \r p[0] = start\r p[i] and p[i+1] differ by only one bit in their binary representation.\r p[0] and p[2^n -1] must also differ by only one bit in their binary representation.\r \r \r  \r Example 1:\r \r \r >>> circularPermutation(n = 2, start = 3\r) >>> [3,2,0,1]\r Explanation: The binary representation of the permutation is (11,10,00,01). \r All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]\r \r \r Example 2:\r \r \r >>> circularPermutation(n = 3, start = 2\r) >>> [2,6,7,5,4,0,1,3]\r Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).\r \r \r  \r """
maximum-length-of-a-concatenated-string-with-unique-characters
def maxLength(arr: List[str]) -> int: """ You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: >>> maxLength(arr = ["un","iq","ue"]) >>> 4 Explanation: All the valid concatenations are: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") Maximum length is 4. Example 2: >>> maxLength(arr = ["cha","r","act","ers"]) >>> 6 Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). Example 3: >>> maxLength(arr = ["abcdefghijklmnopqrstuvwxyz"]) >>> 26 Explanation: The only string in arr has all 26 characters. """
tiling-a-rectangle-with-the-fewest-squares
def tilingRectangle(n: int, m: int) -> int: """ Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle. Example 1: >>> tilingRectangle(n = 2, m = 3) >>> 3 Explanation: 3 squares are necessary to cover the rectangle. 2 (squares of 1x1) 1 (square of 2x2) Example 2: >>> tilingRectangle(n = 5, m = 8) >>> 5 Example 3: >>> tilingRectangle(n = 11, m = 13) >>> 6 """
web-crawler-multithreaded
# This is HtmlParser's API interface. # You should not implement it, or speculate about its implementation # """ #class HtmlParser(object): # def getUrls(url): # """ # :type url: str # :rtype List[str] # """ class Solution: def crawl(startUrl: str, htmlParser: 'HtmlParser') -> List[str]: """ Given a URL startUrl and an interface HtmlParser, implement a Multi-threaded web crawler to crawl all links that are under the same hostname as startUrl. Return all URLs obtained by your web crawler in any order. Your crawler should: Start from the page: startUrl Call HtmlParser.getUrls(url) to get all URLs from a webpage of a given URL. Do not crawl the same link twice. Explore only the links that are under the same hostname as startUrl. As shown in the example URL above, the hostname is example.org. For simplicity's sake, you may assume all URLs use HTTP protocol without any port specified. For example, the URLs http://leetcode.com/problems and http://leetcode.com/contest are under the same hostname, while URLs http://example.org/test and http://example.com/abc are not under the same hostname. The HtmlParser interface is defined as such: interface HtmlParser { // Return a list of all urls from a webpage of given url. // This is a blocking call, that means it will do HTTP request and return when this request is finished. public List getUrls(String url); } Note that getUrls(String url) simulates performing an HTTP request. You can treat it as a blocking function call that waits for an HTTP request to finish. It is guaranteed that getUrls(String url) will return the URLs within 15ms. Single-threaded solutions will exceed the time limit so, can your multi-threaded web crawler do better? Below are two examples explaining the functionality of the problem. For custom testing purposes, you'll have three variables urls, edges and startUrl. Notice that you will only have access to startUrl in your code, while urls and edges are not directly accessible to you in code. Example 1: urls = [   "http://news.yahoo.com",   "http://news.yahoo.com/news",   "http://news.yahoo.com/news/topics/",   "http://news.google.com",   "http://news.yahoo.com/us" ] edges = [[2,0],[2,1],[3,2],[3,1],[0,4]] startUrl = "http://news.yahoo.com/news/topics/" >>> getUrls() >>> [   "http://news.yahoo.com",   "http://news.yahoo.com/news",   "http://news.yahoo.com/news/topics/",   "http://news.yahoo.com/us" ] Example 2: urls = [   "http://news.yahoo.com",   "http://news.yahoo.com/news",   "http://news.yahoo.com/news/topics/",   "http://news.google.com" ] edges = [[0,2],[2,1],[3,2],[3,1],[3,0]] startUrl = "http://news.google.com" >>> getUrls() >>> ["http://news.google.com"] Explanation: The startUrl links to all other pages that do not share the same hostname. """
array-transformation
def transformArray(arr: List[int]) -> List[int]: """ Given an initial array arr, every day you produce a new array using the array of the previous day. On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i: If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented. The first and last elements never change. After some days, the array does not change. Return that final array. Example 1: >>> transformArray(arr = [6,2,3,4]) >>> [6,3,3,4] Explanation: On the first day, the array is changed from [6,2,3,4] to [6,3,3,4]. No more operations can be done to this array. Example 2: >>> transformArray(arr = [1,6,3,4,3,5]) >>> [1,4,4,4,4,5] Explanation: On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5]. On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5]. No more operations can be done to this array. """
tree-diameter
def treeDiameter(edges: List[List[int]]) -> int: """ The diameter of a tree is the number of edges in the longest path in that tree. There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree. Return the diameter of the tree. Example 1: >>> treeDiameter(edges = [[0,1],[0,2]]) >>> 2 Explanation: The longest path of the tree is the path 1 - 0 - 2. Example 2: >>> treeDiameter(edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]) >>> 4 Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5. """
palindrome-removal
def minimumMoves(arr: List[int]) -> int: """ You are given an integer array arr. In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal. Return the minimum number of moves needed to remove all numbers from the array. Example 1: >>> minimumMoves(arr = [1,2]) >>> 2 Example 2: >>> minimumMoves(arr = [1,3,4,1,5]) >>> 3 Explanation: Remove [4] then remove [1,3,1] then remove [5]. """
minimum-swaps-to-make-strings-equal
def minimumSwap(s1: str, s2: str) -> int: """ You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. Example 1: >>> minimumSwap(s1 = "xx", s2 = "yy") >>> 1 Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx". Example 2: >>> minimumSwap(s1 = "xy", s2 = "yx") >>> 2 Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx". Swap s1[0] and s2[1], s1 = "xy", s2 = "xy". Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings. Example 3: >>> minimumSwap(s1 = "xx", s2 = "xy") >>> -1 """
count-number-of-nice-subarrays
def numberOfSubarrays(nums: List[int], k: int) -> int: """ Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. Example 1: >>> numberOfSubarrays(nums = [1,1,2,1,1], k = 3) >>> 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. Example 2: >>> numberOfSubarrays(nums = [2,4,6], k = 1) >>> 0 Explanation: There are no odd numbers in the array. Example 3: >>> numberOfSubarrays(nums = [2,2,2,1,2,2,1,2,2,2], k = 2) >>> 16 """
minimum-remove-to-make-valid-parentheses
def minRemoveToMakeValid(s: str) -> str: """ Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Example 1: >>> minRemoveToMakeValid(s = "lee(t(c)o)de)") >>> "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: >>> minRemoveToMakeValid(s = "a)b(c)d") >>> "ab(c)d" Example 3: >>> minRemoveToMakeValid(s = "))((") >>> "" Explanation: An empty string is also valid. """
check-if-it-is-a-good-array
def isGoodArray(nums: List[int]) -> bool: """ Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False. Example 1: >>> isGoodArray(nums = [12,5,7,23]) >>> true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1 Example 2: >>> isGoodArray(nums = [29,6,10]) >>> true Explanation: Pick numbers 29, 6 and 10. 29*1 + 6*(-3) + 10*(-1) = 1 Example 3: >>> isGoodArray(nums = [3,6]) >>> false """
cells-with-odd-values-in-a-matrix
def oddCells(m: int, n: int, indices: List[List[int]]) -> int: """ There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i], do both of the following: Increment all the cells on row ri. Increment all the cells on column ci. Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. Example 1: >>> oddCells(m = 2, n = 3, indices = [[0,1],[1,1]]) >>> 6 Explanation: Initial matrix = [[0,0,0],[0,0,0]]. After applying first increment it becomes [[1,2,1],[0,1,0]]. The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers. Example 2: >>> oddCells(m = 2, n = 2, indices = [[1,1],[0,0]]) >>> 0 Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix. """
reconstruct-a-2-row-binary-matrix
def reconstructMatrix(upper: int, lower: int, colsum: List[int]) -> List[List[int]]: """ Given the following details of a matrix with n columns and 2 rows : The matrix is a binary matrix, which means each element in the matrix can be 0 or 1. The sum of elements of the 0-th(upper) row is given as upper. The sum of elements of the 1-st(lower) row is given as lower. The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n. Your task is to reconstruct the matrix with upper, lower and colsum. Return it as a 2-D integer array. If there are more than one valid solution, any of them will be accepted. If no valid solution exists, return an empty 2-D array. Example 1: >>> reconstructMatrix(upper = 2, lower = 1, colsum = [1,1,1]) >>> [[1,1,0],[0,0,1]] Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers. Example 2: >>> reconstructMatrix(upper = 2, lower = 3, colsum = [2,2,1,1]) >>> [] Example 3: >>> reconstructMatrix(upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]) >>> [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]] """
number-of-closed-islands
def closedIsland(grid: List[List[int]]) -> int: """ Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. Example 1: >>> closedIsland(grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]) >>> 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: >>> closedIsland(grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]) >>> 1 Example 3:   [1,0,0,0,0,0,1],   [1,0,1,1,1,0,1],   [1,0,1,0,1,0,1],   [1,0,1,1,1,0,1],   [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] >>> closedIsland(grid = [[1,1,1,1,1,1,1],) >>> 2 """
maximum-score-words-formed-by-letters
def maxScoreWords(words: List[str], letters: List[str], score: List[int]) -> int: """ Given a list of words, list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively. Example 1: >>> maxScoreWords(words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]) >>> 23 Explanation: Score a=1, c=9, d=5, g=3, o=2 Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23. Words "dad" and "dog" only get a score of 21. Example 2: >>> maxScoreWords(words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]) >>> 27 Explanation: Score a=4, b=4, c=4, x=5, z=10 Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27. Word "xxxz" only get a score of 25. Example 3: >>> maxScoreWords(words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]) >>> 0 Explanation: Letter "e" can only be used once. """
encode-number
def encode(num: int) -> str: """ Given a non-negative integer num, Return its encoding string.\r \r The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:\r \r \r \r  \r Example 1:\r \r \r >>> encode(num = 23\r) >>> "1000"\r \r \r Example 2:\r \r \r >>> encode(num = 107\r) >>> "101100"\r \r \r  \r """
smallest-common-region
def findSmallestRegion(regions: List[List[str]], region1: str, region2: str) -> str: """ You are given some lists of regions where the first region of each list includes all other regions in that list. Naturally, if a region x contains another region y then x is bigger than y. Also, by definition, a region x contains itself. Given two regions: region1 and region2, return the smallest region that contains both of them. If you are given regions r1, r2, and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3. It is guaranteed the smallest region exists. Example 1: regions = [["Earth","North America","South America"], ["North America","United States","Canada"], ["United States","New York","Boston"], ["Canada","Ontario","Quebec"], ["South America","Brazil"]], region1 = "Quebec", region2 = "New York" >>> findSmallestRegion() >>> "North America" Example 2: >>> findSmallestRegion(regions = [["Earth", "North America", "South America"],["North America", "United States", "Canada"],["United States", "New York", "Boston"],["Canada", "Ontario", "Quebec"],["South America", "Brazil"]], region1 = "Canada", region2 = "South America") >>> "Earth" """
synonymous-sentences
def generateSentences(synonyms: List[List[str]], text: str) -> List[str]: """ You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text. Return all possible synonymous sentences sorted lexicographically. Example 1: >>> generateSentences(synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday") >>> ["I am cheerful today but was sad yesterday","I am cheerful today but was sorrow yesterday","I am happy today but was sad yesterday","I am happy today but was sorrow yesterday","I am joy today but was sad yesterday","I am joy today but was sorrow yesterday"] Example 2: >>> generateSentences(synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday") >>> ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"] """
handshakes-that-dont-cross
def numberOfWays(numPeople: int) -> int: """ You are given an even number of people numPeople that stand around a circle and each person shakes hands with someone else so that there are numPeople / 2 handshakes total. Return the number of ways these handshakes could occur such that none of the handshakes cross. Since the answer could be very large, return it modulo 109 + 7. Example 1: >>> numberOfWays(numPeople = 4) >>> 2 Explanation: There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)]. Example 2: >>> numberOfWays(numPeople = 6) >>> 5 """
shift-2d-grid
def shiftGrid(grid: List[List[int]], k: int) -> List[List[int]]: """ Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. In one shift operation: Element at grid[i][j] moves to grid[i][j + 1]. Element at grid[i][n - 1] moves to grid[i + 1][0]. Element at grid[m - 1][n - 1] moves to grid[0][0]. Return the 2D grid after applying shift operation k times. Example 1: >>> shiftGrid(grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1) >>> [[9,1,2],[3,4,5],[6,7,8]] Example 2: >>> shiftGrid(grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4) >>> [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] Example 3: >>> shiftGrid(grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9) >>> [[1,2,3],[4,5,6],[7,8,9]] """
greatest-sum-divisible-by-three
def maxSumDivThree(nums: List[int]) -> int: """ Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three. Example 1: >>> maxSumDivThree(nums = [3,6,5,1,8]) >>> 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: >>> maxSumDivThree(nums = [4]) >>> 0 Explanation: Since 4 is not divisible by 3, do not pick any number. Example 3: >>> maxSumDivThree(nums = [1,2,3,4,4]) >>> 12 Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3). """
minimum-moves-to-move-a-box-to-their-target-location
def minPushBox(grid: List[List[str]]) -> int: """ A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell). The character '.' represents the floor which means a free cell to walk. The character '#' represents the wall which means an obstacle (impossible to walk there). There is only one box 'B' and one target cell 'T' in the grid. The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push. The player cannot walk through the box. Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. Example 1: ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#",".","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] >>> minPushBox(grid = [["#","#","#","#","#","#"],) >>> 3 Explanation: We return only the number of times the box is pushed. Example 2: ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#","#","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] >>> minPushBox(grid = [["#","#","#","#","#","#"],) >>> -1 Example 3: ["#","T",".",".","#","#"], ["#",".","#","B",".","#"], ["#",".",".",".",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] >>> minPushBox(grid = [["#","#","#","#","#","#"],) >>> 5 Explanation: push the box down, left, left, up and up. """
minimum-time-visiting-all-points
def minTimeToVisitAllPoints(points: List[List[int]]) -> int: """ On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. You can move according to these rules: In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points that appear later in the order, but these do not count as visits. Example 1: >>> minTimeToVisitAllPoints(points = [[1,1],[3,4],[-1,0]]) >>> 7 Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] Time from [1,1] to [3,4] = 3 seconds Time from [3,4] to [-1,0] = 4 seconds Total time = 7 seconds Example 2: >>> minTimeToVisitAllPoints(points = [[3,2],[-2,2]]) >>> 5 """
count-servers-that-communicate
def countServers(grid: List[List[int]]) -> int: """ You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server. Example 1: >>> countServers(grid = [[1,0],[0,1]]) >>> 0 Explanation: No servers can communicate with others. Example 2: >>> countServers(grid = [[1,0],[1,1]]) >>> 3 Explanation: All three servers can communicate with at least one other server. Example 3: >>> countServers(grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]) >>> 4 Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server. """
search-suggestions-system
def suggestedProducts(products: List[str], searchWord: str) -> List[List[str]]: """ You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed. Example 1: >>> suggestedProducts(products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse") >>> [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]] Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]. After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]. After typing mou, mous and mouse the system suggests ["mouse","mousepad"]. Example 2: >>> suggestedProducts(products = ["havana"], searchWord = "havana") >>> [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] Explanation: The only word "havana" will be always suggested while typing the search word. """
number-of-ways-to-stay-in-the-same-place-after-some-steps
def numWays(steps: int, arrLen: int) -> int: """ You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numWays(steps = 3, arrLen = 2) >>> 4 Explanation: There are 4 differents ways to stay at index 0 after 3 steps. Right, Left, Stay Stay, Right, Left Right, Stay, Left Stay, Stay, Stay Example 2: >>> numWays(steps = 2, arrLen = 4) >>> 2 Explanation: There are 2 differents ways to stay at index 0 after 2 steps Right, Left Stay, Stay Example 3: >>> numWays(steps = 4, arrLen = 2) >>> 8 """
hexspeak
def toHexspeak(num: str) -> str: """ A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and only if it consists only of the letters in the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}. Given a string num representing a decimal integer n, return the Hexspeak representation of n if it is valid, otherwise return "ERROR". Example 1: >>> toHexspeak(num = "257") >>> "IOI" Explanation: 257 is 101 in hexadecimal. Example 2: >>> toHexspeak(num = "3") >>> "ERROR" """
remove-interval
def removeInterval(intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: """ A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b). You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi). You are also given another interval toBeRemoved. Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint intervals as described above. Example 1: >>> removeInterval(intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]) >>> [[0,1],[6,7]] Example 2: >>> removeInterval(intervals = [[0,5]], toBeRemoved = [2,3]) >>> [[0,2],[3,5]] Example 3: >>> removeInterval(intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]) >>> [[-5,-4],[-3,-2],[4,5],[8,9]] """
delete-tree-nodes
def deleteTreeNodes(nodes: int, parent: List[int], value: List[int]) -> int: """ A tree rooted at node 0 is given as follows: The number of nodes is nodes; The value of the ith node is value[i]; The parent of the ith node is parent[i]. Remove every subtree whose sum of values of nodes is zero. Return the number of the remaining nodes in the tree. Example 1: >>> deleteTreeNodes(nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]) >>> 2 Example 2: >>> deleteTreeNodes(nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2]) >>> 6 """
find-winner-on-a-tic-tac-toe-game
def tictactoe(moves: List[List[int]]) -> str: """ Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Players take turns placing characters into empty squares ' '. The first player A always places 'X' characters, while the second player B always places 'O' characters. 'X' and 'O' characters are always placed into empty squares, never on filled ones. The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending". You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first. Example 1: >>> tictactoe(moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]) >>> "A" Explanation: A wins, they always play first. Example 2: >>> tictactoe(moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]) >>> "B" Explanation: B wins. Example 3: >>> tictactoe(moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]) >>> "Draw" Explanation: The game ends in a draw since there are no moves to make. """
number-of-burgers-with-no-waste-of-ingredients
def numOfBurgers(tomatoSlices: int, cheeseSlices: int) -> List[int]: """ Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: Jumbo Burger: 4 tomato slices and 1 cheese slice. Small Burger: 2 Tomato slices and 1 cheese slice. Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return []. Example 1: >>> numOfBurgers(tomatoSlices = 16, cheeseSlices = 7) >>> [1,6] Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. There will be no remaining ingredients. Example 2: >>> numOfBurgers(tomatoSlices = 17, cheeseSlices = 4) >>> [] Explantion: There will be no way to use all ingredients to make small and jumbo burgers. Example 3: >>> numOfBurgers(tomatoSlices = 4, cheeseSlices = 17) >>> [] Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining. """
count-square-submatrices-with-all-ones
def countSquares(matrix: List[List[int]]) -> int: """ Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: [   [0,1,1,1],   [1,1,1,1],   [0,1,1,1] ] >>> countSquares(matrix =) >>> 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: [ [1,0,1], [1,1,0], [1,1,0] ] >>> countSquares(matrix =) >>> 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7. """
palindrome-partitioning-iii
def palindromePartition(s: str, k: int) -> int: """ You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. Return the minimal number of characters that you need to change to divide the string. Example 1: >>> palindromePartition(s = "abc", k = 2) >>> 1 Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome. Example 2: >>> palindromePartition(s = "aabbc", k = 3) >>> 0 Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome. Example 3: >>> palindromePartition(s = "leetcode", k = 8) >>> 0 """
subtract-the-product-and-sum-of-digits-of-an-integer
def subtractProductAndSum(n: int) -> int: """ Given an integer number n, return the difference between the product of its digits and the sum of its digits. Example 1: >>> subtractProductAndSum(n = 234) >>> 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: >>> subtractProductAndSum(n = 4421) >>> 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 """
group-the-people-given-the-group-size-they-belong-to
def groupThePeople(groupSizes: List[int]) -> List[List[int]]: """ There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1. You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3. Return a list of groups such that each person i is in a group of size groupSizes[i]. Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input. Example 1: >>> groupThePeople(groupSizes = [3,3,3,3,3,1,3]) >>> [[5],[0,1,2],[3,4,6]] Explanation: The first group is [5]. The size is 1, and groupSizes[5] = 1. The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3. The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3. Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. Example 2: >>> groupThePeople(groupSizes = [2,1,3,3,3,2]) >>> [[1],[0,5],[2,3,4]] """
find-the-smallest-divisor-given-a-threshold
def smallestDivisor(nums: List[int], threshold: int) -> int: """ Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). The test cases are generated so that there will be an answer. Example 1: >>> smallestDivisor(nums = [1,2,5,9], threshold = 6) >>> 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: >>> smallestDivisor(nums = [44,22,33,11,1], threshold = 5) >>> 44 """
minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix
def minFlips(mat: List[List[int]]) -> int: """ Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0. Example 1: >>> minFlips(mat = [[0,0],[0,1]]) >>> 3 Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown. Example 2: >>> minFlips(mat = [[0]]) >>> 0 Explanation: Given matrix is a zero matrix. We do not need to change it. Example 3: >>> minFlips(mat = [[1,0,0],[1,0,0]]) >>> -1 Explanation: Given matrix cannot be a zero matrix. """
element-appearing-more-than-25-in-sorted-array
def findSpecialInteger(arr: List[int]) -> int: """ Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. Example 1: >>> findSpecialInteger(arr = [1,2,2,6,6,6,6,7,10]) >>> 6 Example 2: >>> findSpecialInteger(arr = [1,1]) >>> 1 """
remove-covered-intervals
def removeCoveredIntervals(intervals: List[List[int]]) -> int: """ Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. Return the number of remaining intervals. Example 1: >>> removeCoveredIntervals(intervals = [[1,4],[3,6],[2,8]]) >>> 2 Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. Example 2: >>> removeCoveredIntervals(intervals = [[1,4],[2,3]]) >>> 1 """
minimum-falling-path-sum-ii
def minFallingPathSum(grid: List[List[int]]) -> int: """ Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. Example 1: >>> minFallingPathSum(grid = [[1,2,3],[4,5,6],[7,8,9]]) >>> 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is [1,5,7], so the answer is 13. Example 2: >>> minFallingPathSum(grid = [[7]]) >>> 7 """
convert-binary-number-in-a-linked-list-to-integer
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(head: Optional[ListNode]) -> int: """ Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. Example 1: >>> __init__(head = [1,0,1]) >>> 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: >>> __init__(head = [0]) >>> 0 """
sequential-digits
def sequentialDigits(low: int, high: int) -> List[int]: """ An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. Example 1: >>> sequentialDigits(low = 100, high = 300) >>> [123,234] Example 2: >>> sequentialDigits(low = 1000, high = 13000) >>> [1234,2345,3456,4567,5678,6789,12345] """
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
def maxSideLength(mat: List[List[int]], threshold: int) -> int: """ Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. Example 1: >>> maxSideLength(mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4) >>> 2 Explanation: The maximum side length of square with sum less than 4 is 2 as shown. Example 2: >>> maxSideLength(mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1) >>> 0 """
shortest-path-in-a-grid-with-obstacles-elimination
def shortestPath(grid: List[List[int]], k: int) -> int: """ You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. Example 1: >>> shortestPath(grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1) >>> 6 Explanation: The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2). Example 2: >>> shortestPath(grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1) >>> -1 Explanation: We need to eliminate at least two obstacles to find such a walk. """
find-numbers-with-even-number-of-digits
def findNumbers(nums: List[int]) -> int: """ Given an array nums of integers, return how many of them contain an even number of digits. Example 1: >>> findNumbers(nums = [12,345,2,6,7896]) >>> 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. Example 2: >>> findNumbers(nums = [555,901,482,1771]) >>> 1 Explanation: Only 1771 contains an even number of digits. """
divide-array-in-sets-of-k-consecutive-numbers
def isPossibleDivide(nums: List[int], k: int) -> bool: """ Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible. Otherwise, return false. Example 1: >>> isPossibleDivide(nums = [1,2,3,3,4,4,5,6], k = 4) >>> true Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. Example 2: >>> isPossibleDivide(nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3) >>> true Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. Example 3: >>> isPossibleDivide(nums = [1,2,3,4], k = 3) >>> false Explanation: Each array should be divided in subarrays of size 3. """
maximum-number-of-occurrences-of-a-substring
def maxFreq(s: str, maxLetters: int, minSize: int, maxSize: int) -> int: """ Given a string s, return the maximum number of occurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. Example 1: >>> maxFreq(s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4) >>> 2 Explanation: Substring "aab" has 2 occurrences in the original string. It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). Example 2: >>> maxFreq(s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3) >>> 2 Explanation: Substring "aaa" occur 2 times in the string. It can overlap. """
maximum-candies-you-can-get-from-boxes
def maxCandies(status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int: """ You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where: status[i] is 1 if the ith box is open and 0 if the ith box is closed, candies[i] is the number of candies in the ith box, keys[i] is a list of the labels of the boxes you can open after opening the ith box. containedBoxes[i] is a list of the boxes you found inside the ith box. You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above. Example 1: >>> maxCandies(status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]) >>> 16 Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2. In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed. Total number of candies collected = 7 + 4 + 5 = 16 candy. Example 2: >>> maxCandies(status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]) >>> 6 Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6. """
replace-elements-with-greatest-element-on-right-side
def replaceElements(arr: List[int]) -> List[int]: """ Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example 1: >>> replaceElements(arr = [17,18,5,4,6,1]) >>> [18,6,6,6,1,-1] Explanation: - index 0 --> the greatest element to the right of index 0 is index 1 (18). - index 1 --> the greatest element to the right of index 1 is index 4 (6). - index 2 --> the greatest element to the right of index 2 is index 4 (6). - index 3 --> the greatest element to the right of index 3 is index 4 (6). - index 4 --> the greatest element to the right of index 4 is index 5 (1). - index 5 --> there are no elements to the right of index 5, so we put -1. Example 2: >>> replaceElements(arr = [400]) >>> [-1] Explanation: There are no elements to the right of index 0. """
sum-of-mutated-array-closest-to-target
def findBestValue(arr: List[int], target: int) -> int: """ Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr. Example 1: >>> findBestValue(arr = [4,9,3], target = 10) >>> 3 Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer. Example 2: >>> findBestValue(arr = [2,3,5], target = 10) >>> 5 Example 3: >>> findBestValue(arr = [60864,25176,27249,21296,20204], target = 56803) >>> 11361 """
number-of-paths-with-max-score
def pathsWithMaxScore(board: List[str]) -> List[int]: """ You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.\r \r You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\r \r Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.\r \r In case there is no path, return [0, 0].\r \r  \r Example 1:\r >>> pathsWithMaxScore(board = ["E23","2X2","12S"]\r) >>> [7,1]\r Example 2:\r >>> pathsWithMaxScore(board = ["E12","1X1","21S"]\r) >>> [4,2]\r Example 3:\r >>> pathsWithMaxScore(board = ["E11","XXX","11S"]\r) >>> [0,0]\r \r  \r """
deepest-leaves-sum
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deepestLeavesSum(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return the sum of values of its deepest leaves. Example 1: >>> __init__(root = [1,2,3,4,5,null,6,7,null,null,null,null,8]) >>> 15 Example 2: >>> __init__(root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]) >>> 19 """
find-n-unique-integers-sum-up-to-zero
def sumZero(n: int) -> List[int]: """ Given an integer n, return any array containing n unique integers such that they add up to 0. Example 1: >>> sumZero(n = 5) >>> [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. Example 2: >>> sumZero(n = 3) >>> [-1,0,1] Example 3: >>> sumZero(n = 1) >>> [0] """
all-elements-in-two-binary-search-trees
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getAllElements(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]: """ Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. Example 1: >>> __init__(root1 = [2,1,4], root2 = [1,0,3]) >>> [0,1,1,2,3,4] Example 2: >>> __init__(root1 = [1,null,8], root2 = [8,1]) >>> [1,1,8,8] """
jump-game-iii
def canReach(arr: List[int], start: int) -> bool: """ Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0. Notice that you can not jump outside of the array at any time. Example 1: >>> canReach(arr = [4,2,3,0,3,1,2], start = 5) >>> true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3 Example 2: >>> canReach(arr = [4,2,3,0,3,1,2], start = 0) >>> true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3 Example 3: >>> canReach(arr = [3,0,2,1,2], start = 2) >>> false Explanation: There is no way to reach at index 1 with value 0. """
verbal-arithmetic-puzzle
def isSolvable(words: List[str], result: str) -> bool: """ Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number without leading zeros. Sum of numbers on the left side (words) will equal to the number on the right side (result). Return true if the equation is solvable, otherwise return false. Example 1: >>> isSolvable(words = ["SEND","MORE"], result = "MONEY") >>> true Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652 Example 2: >>> isSolvable(words = ["SIX","SEVEN","SEVEN"], result = "TWENTY") >>> true Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214 Example 3: >>> isSolvable(words = ["LEET","CODE"], result = "POINT") >>> false Explanation: There is no possible mapping to satisfy the equation, so we return false. Note that two different characters cannot map to the same digit. """
decrypt-string-from-alphabet-to-integer-mapping
def freqAlphabets(s: str) -> str: """ You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively. Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. Return the string formed after mapping. The test cases are generated so that a unique mapping will always exist. Example 1: >>> freqAlphabets(s = "10#11#12") >>> "jkab" Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". Example 2: >>> freqAlphabets(s = "1326#") >>> "acz" """
xor-queries-of-a-subarray
def xorQueries(arr: List[int], queries: List[List[int]]) -> List[int]: """ You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti]. For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ). Return an array answer where answer[i] is the answer to the ith query. Example 1: >>> xorQueries(arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]) >>> [2,7,14,8] Explanation: The binary representation of the elements in the array are: 1 = 0001 3 = 0011 4 = 0100 8 = 1000 The XOR values for queries are: [0,1] = 1 xor 3 = 2 [1,2] = 3 xor 4 = 7 [0,3] = 1 xor 3 xor 4 xor 8 = 14 [3,3] = 8 Example 2: >>> xorQueries(arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]) >>> [8,0,4,4] """
get-watched-videos-by-your-friends
def watchedVideosByFriends(watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]: """ There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. Example 1: >>> watchedVideosByFriends(watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1) >>> ["B","C"] Explanation: You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = ["C"] Person with id = 2 -> watchedVideos = ["B","C"] The frequencies of watchedVideos by your friends are: B -> 1 C -> 2 Example 2: >>> watchedVideosByFriends(watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2) >>> ["D"] Explanation: You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure). """
minimum-insertion-steps-to-make-a-string-palindrome
def minInsertions(s: str) -> int: """ Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. Example 1: >>> minInsertions(s = "zzazz") >>> 0 Explanation: The string "zzazz" is already palindrome we do not need any insertions. Example 2: >>> minInsertions(s = "mbadm") >>> 2 Explanation: String can be "mbdadbm" or "mdbabdm". Example 3: >>> minInsertions(s = "leetcode") >>> 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel". """
decompress-run-length-encoded-list
def decompressRLElist(nums: List[int]) -> List[int]: """ We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Example 1: >>> decompressRLElist(nums = [1,2,3,4]) >>> [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. Example 2: >>> decompressRLElist(nums = [1,1,2,3]) >>> [1,3,3] """
matrix-block-sum
def matrixBlockSum(mat: List[List[int]], k: int) -> List[List[int]]: """ Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: i - k <= r <= i + k, j - k <= c <= j + k, and (r, c) is a valid position in the matrix. Example 1: >>> matrixBlockSum(mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1) >>> [[12,21,16],[27,45,33],[24,39,28]] Example 2: >>> matrixBlockSum(mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2) >>> [[45,45,45],[45,45,45],[45,45,45]] """
sum-of-nodes-with-even-valued-grandparent
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumEvenGrandparent(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists. Example 1: >>> __init__(root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]) >>> 18 Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents. Example 2: >>> __init__(root = [1]) >>> 0 """
distinct-echo-substrings
def distinctEchoSubstrings(text: str) -> int: """ Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string). Example 1: >>> distinctEchoSubstrings(text = "abcabcabc") >>> 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". Example 2: >>> distinctEchoSubstrings(text = "leetcodeleetcode") >>> 2 Explanation: The 2 substrings are "ee" and "leetcodeleetcode". """
convert-integer-to-the-sum-of-two-no-zero-integers
def getNoZeroIntegers(n: int) -> List[int]: """ No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n, return a list of two integers [a, b] where: a and b are No-Zero integers. a + b = n The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them. Example 1: >>> getNoZeroIntegers(n = 2) >>> [1,1] Explanation: Let a = 1 and b = 1. Both a and b are no-zero integers, and a + b = 2 = n. Example 2: >>> getNoZeroIntegers(n = 11) >>> [2,9] Explanation: Let a = 2 and b = 9. Both a and b are no-zero integers, and a + b = 11 = n. Note that there are other valid answers as [8, 3] that can be accepted. """
minimum-flips-to-make-a-or-b-equal-to-c
def minFlips(a: int, b: int, c: int) -> int: """ Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).\r Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.\r \r  \r Example 1:\r \r \r \r \r >>> minFlips(a = 2, b = 6, c = 5\r) >>> 3\r Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)\r \r Example 2:\r \r \r >>> minFlips(a = 4, b = 2, c = 7\r) >>> 1\r \r \r Example 3:\r \r \r >>> minFlips(a = 1, b = 2, c = 3\r) >>> 0\r \r \r  \r """
number-of-operations-to-make-network-connected
def makeConnected(n: int, connections: List[List[int]]) -> int: """ There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1. Example 1: >>> makeConnected(n = 4, connections = [[0,1],[0,2],[1,2]]) >>> 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: >>> makeConnected(n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]) >>> 2 Example 3: >>> makeConnected(n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]) >>> -1 Explanation: There are not enough cables. """
minimum-distance-to-type-a-word-using-two-fingers
def minimumDistance(word: str) -> int: """ You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1). Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. Example 1: >>> minimumDistance(word = "CAKE") >>> 3 Explanation: Using two fingers, one optimal way to type "CAKE" is: Finger 1 on letter 'C' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 Finger 2 on letter 'K' -> cost = 0 Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 Total distance = 3 Example 2: >>> minimumDistance(word = "HAPPY") >>> 6 Explanation: Using two fingers, one optimal way to type "HAPPY" is: Finger 1 on letter 'H' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 Finger 2 on letter 'P' -> cost = 0 Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 Total distance = 6 """
print-words-vertically
def printVertically(s: str) -> List[str]: """ Given a string s. Return all the words vertically in the same order in which they appear in s.\r Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).\r Each word would be put on only one column and that in one column there will be only one word.\r \r  \r Example 1:\r \r \r >>> printVertically(s = "HOW ARE YOU"\r) >>> ["HAY","ORO","WEU"]\r Explanation: Each word is printed vertically. \r "HAY"\r  "ORO"\r  "WEU"\r \r \r Example 2:\r \r \r >>> printVertically(s = "TO BE OR NOT TO BE"\r) >>> ["TBONTB","OEROOE"," T"]\r Explanation: Trailing spaces is not allowed. \r "TBONTB"\r "OEROOE"\r " T"\r \r \r Example 3:\r \r \r >>> printVertically(s = "CONTEST IS COMING"\r) >>> ["CIC","OSO","N M","T I","E N","S G","T"]\r \r \r  \r """
delete-leaves-with-a-given-value
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def removeLeafNodes(root: Optional[TreeNode], target: int) -> Optional[TreeNode]: """ Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). Example 1: >>> __init__(root = [1,2,3,2,null,2,4], target = 2) >>> [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: >>> __init__(root = [1,3,3,3,2], target = 3) >>> [1,3,null,null,2] Example 3: >>> __init__(root = [1,2,null,2,null,2], target = 2) >>> [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step. """
minimum-number-of-taps-to-open-to-water-a-garden
def minTaps(n: int, ranges: List[int]) -> int: """ There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e., the length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. Example 1: >>> minTaps(n = 5, ranges = [3,4,1,1,0,0]) >>> 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5] Example 2: >>> minTaps(n = 3, ranges = [0,0,0,0]) >>> -1 Explanation: Even if you activate all the four taps you cannot water the whole garden. """
break-a-palindrome
def breakPalindrome(palindrome: str) -> str: """ Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'. Example 1: >>> breakPalindrome(palindrome = "abccba") >>> "aaccba" Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba". Of all the ways, "aaccba" is the lexicographically smallest. Example 2: >>> breakPalindrome(palindrome = "a") >>> "" Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string. """
sort-the-matrix-diagonally
def diagonalSort(mat: List[List[int]]) -> List[List[int]]: """ A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. Example 1: >>> diagonalSort(mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]) >>> [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Example 2: >>> diagonalSort(mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]) >>> [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]] """
reverse-subarray-to-maximize-array-value
def maxValueAfterReverse(nums: List[int]) -> int: """ You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array. Example 1: >>> maxValueAfterReverse(nums = [2,3,1,5,4]) >>> 10 Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10. Example 2: >>> maxValueAfterReverse(nums = [2,4,9,24,2,1,10]) >>> 68 """
rank-transform-of-an-array
def arrayRankTransform(arr: List[int]) -> List[int]: """ Given an array of integers arr, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: Rank is an integer starting from 1. The larger the element, the larger the rank. If two elements are equal, their rank must be the same. Rank should be as small as possible. Example 1: >>> arrayRankTransform(arr = [40,10,20,30]) >>> [4,1,2,3] Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest. Example 2: >>> arrayRankTransform(arr = [100,100,100]) >>> [1,1,1] Explanation: Same elements share the same rank. Example 3: >>> arrayRankTransform(arr = [37,12,28,9,100,56,80,5,12]) >>> [5,3,4,2,8,6,7,1,3] """
remove-palindromic-subsequences
def removePalindromeSub(s: str) -> int: """ You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward. Example 1: >>> removePalindromeSub(s = "ababa") >>> 1 Explanation: s is already a palindrome, so its entirety can be removed in a single step. Example 2: >>> removePalindromeSub(s = "abb") >>> 2 Explanation: "abb" -> "bb" -> "". Remove palindromic subsequence "a" then "bb". Example 3: >>> removePalindromeSub(s = "baabb") >>> 2 Explanation: "baabb" -> "b" -> "". Remove palindromic subsequence "baab" then "b". """
filter-restaurants-by-vegan-friendly-price-and-distance
def filterRestaurants(restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]: """ Given the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false. Example 1: >>> filterRestaurants(restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10) >>> [3,1,5] Explanation: The restaurants are: Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). Example 2: >>> filterRestaurants(restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10) >>> [4,3,2,1,5] Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered. Example 3: >>> filterRestaurants(restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3) >>> [4,5] """
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
def findTheCity(n: int, edges: List[List[int]], distanceThreshold: int) -> int: """ There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. Example 1: >>> findTheCity(n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4) >>> 3 Explanation: The figure above describes the graph. The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2] City 1 -> [City 0, City 2, City 3] City 2 -> [City 0, City 1, City 3] City 3 -> [City 1, City 2] Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. Example 2: >>> findTheCity(n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2) >>> 0 Explanation: The figure above describes the graph. The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> [City 1] City 1 -> [City 0, City 4] City 2 -> [City 3, City 4] City 3 -> [City 2, City 4] City 4 -> [City 1, City 2, City 3] The city 0 has 1 neighboring city at a distanceThreshold = 2. """
minimum-difficulty-of-a-job-schedule
def minDifficulty(jobDifficulty: List[int], d: int) -> int: """ You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1. Example 1: >>> minDifficulty(jobDifficulty = [6,5,4,3,2,1], d = 2) >>> 7 Explanation: First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 Example 2: >>> minDifficulty(jobDifficulty = [9,9,9], d = 4) >>> -1 Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. Example 3: >>> minDifficulty(jobDifficulty = [1,1,1], d = 3) >>> 3 Explanation: The schedule is one job per day. total difficulty will be 3. """