sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
1c9c32
884223
You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser. void visit(string url) Visits url from the current page. It clears up all the forward history. string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps. string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.   Example: Input: ["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"] [["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]] Output: [null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"] Explanation: BrowserHistory browserHistory = new BrowserHistory("leetcode.com"); browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com" browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com" browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com" browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com" browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com" browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com" browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com" browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps. browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com" browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"   Constraints: 1 <= homepage.length <= 20 1 <= url.length <= 20 1 <= steps <= 100 homepage and url consist of  '.' or lower case English letters. At most 5000 calls will be made to visit, back, and forward.
class BrowserHistory: def __init__(self, homepage: str): self.d = collections.deque() self.d.append(homepage) self.i = 0 def visit(self, url: str) -> None: while len(self.d) > self.i + 1: self.d.pop() self.d.append(url) self.i += 1 def back(self, n): self.i -= n if self.i < 0: self.i = 0 return self.d[self.i] def forward(self, n): self.i += n if self.i >= len(self.d): self.i = len(self.d) - 1 return self.d[self.i] # Your BrowserHistory object will be instantiated and called as such: # obj = BrowserHistory(homepage) # obj.visit(url) # param_2 = obj.back(steps) # param_3 = obj.forward(steps)
efb80a
884223
You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser. void visit(string url) Visits url from the current page. It clears up all the forward history. string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps. string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.   Example: Input: ["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"] [["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]] Output: [null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"] Explanation: BrowserHistory browserHistory = new BrowserHistory("leetcode.com"); browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com" browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com" browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com" browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com" browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com" browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com" browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com" browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps. browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com" browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"   Constraints: 1 <= homepage.length <= 20 1 <= url.length <= 20 1 <= steps <= 100 homepage and url consist of  '.' or lower case English letters. At most 5000 calls will be made to visit, back, and forward.
class BrowserHistory(object): def __init__(self, homepage): """ :type homepage: str """ self.homepage = homepage self.history = [] self.cursor = 0 def visit(self, url): """ :type url: str :rtype: None """ del self.history[self.cursor:] self.history.append(url) self.cursor = len(self.history) def back(self, steps): """ :type steps: int :rtype: str """ self.cursor = max(0, self.cursor - steps) if self.cursor == 0: return self.homepage return self.history[self.cursor-1] def forward(self, steps): """ :type steps: int :rtype: str """ self.cursor = min(len(self.history), self.cursor + steps) if self.cursor == 0: return self.homepage return self.history[self.cursor-1] # Your BrowserHistory object will be instantiated and called as such: # obj = BrowserHistory(homepage) # obj.visit(url) # param_2 = obj.back(steps) # param_3 = obj.forward(steps)
915cc1
a195f7
You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two adjacent non-coprime numbers. Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 10^8. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.   Example 1: Input: nums = [6,4,3,2,7,6,2] Output: [12,7,6] Explanation: - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2]. - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [12,7,6]. Note that there are other ways to obtain the same resultant array. Example 2: Input: nums = [2,2,1,1,3,3,3] Output: [2,1,1,3] Explanation: - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [2,1,1,3]. Note that there are other ways to obtain the same resultant array.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000 The test cases are generated such that the values in the final array are less than or equal to 10^8.
class Solution: def replaceNonCoprimes(self, A: List[int]) -> List[int]: N = len(A) def lcm(x, y): return x * y // math.gcd(x, y) stack = [] for x in A: stack.append(x) while len(stack) >= 2 and math.gcd(stack[-1], stack[-2]) > 1: stack.append(lcm(stack.pop(), stack.pop())) return stack
f1a6b6
a195f7
You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two adjacent non-coprime numbers. Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 10^8. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.   Example 1: Input: nums = [6,4,3,2,7,6,2] Output: [12,7,6] Explanation: - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2]. - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [12,7,6]. Note that there are other ways to obtain the same resultant array. Example 2: Input: nums = [2,2,1,1,3,3,3] Output: [2,1,1,3] Explanation: - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [2,1,1,3]. Note that there are other ways to obtain the same resultant array.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000 The test cases are generated such that the values in the final array are less than or equal to 10^8.
from fractions import gcd class Solution(object): def replaceNonCoprimes(self, nums): """ :type nums: List[int] :rtype: List[int] """ a = [] for v in nums: a.append(v) while len(a) >= 2 and gcd(a[-1], a[-2]) > 1: x = a[-1] * (a[-2] // gcd(a[-1], a[-2])) a.pop() a[-1] = x return a
ccbccf
9ba872
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: 1 <= pivot < n nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged. Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.   Example 1: Input: nums = [2,-1,2], k = 3 Output: 1 Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2]. There is one way to partition the array: - For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2. Example 2: Input: nums = [0,0,0], k = 1 Output: 2 Explanation: The optimal approach is to leave the array unchanged. There are two ways to partition the array: - For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0. - For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0. Example 3: Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 Output: 4 Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14]. There are four ways to partition the array.   Constraints: n == nums.length 2 <= n <= 100000 -100000 <= k, nums[i] <= 100000
from collections import defaultdict from typing import List class Solution: def waysToPartition(self, nums: List[int], k: int) -> int: n = len(nums) add = [nums[0]] for num in nums[1:-1]: add.append(add[-1] + num) target = sum(nums) left = defaultdict(int) right = defaultdict(int) for a in add: left[a] += 1 ans = 0 if target % 2 == 0: ans = left[target >> 1] if (target - nums[-1] + k) % 2 == 0: ans = max(ans, left[(target - nums[-1] + k) >> 1]) for i in range(n - 2, -1, -1): left[add[i]] -= 1 right[add[i]] += 1 tmp = target - nums[i] + k if tmp % 2 == 0: ans = max(ans, left[tmp >> 1] + right[(tmp >> 1) - k + nums[i]]) return ans
fe531a
9ba872
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: 1 <= pivot < n nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged. Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.   Example 1: Input: nums = [2,-1,2], k = 3 Output: 1 Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2]. There is one way to partition the array: - For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2. Example 2: Input: nums = [0,0,0], k = 1 Output: 2 Explanation: The optimal approach is to leave the array unchanged. There are two ways to partition the array: - For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0. - For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0. Example 3: Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 Output: 4 Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14]. There are four ways to partition the array.   Constraints: n == nums.length 2 <= n <= 100000 -100000 <= k, nums[i] <= 100000
class Solution(object): def waysToPartition(self, A, k): su = sum(A) n = len(A) ress = [0] * n count = collections.Counter() cur = 0 for i in xrange(n): cur += A[i] ress[i] += count[k - A[i]] diff = cur - (su - cur) count[diff] += 1 if i == n - 2: res = count[0] # print ress count = collections.Counter() cur = 0 for i in xrange(n - 1, -1, -1): cur += A[i] ress[i] += count[k - A[i]] diff = cur - (su - cur) count[diff] += 1 # print ress, res return max(res, max(ress))
dcf857
f8d1bf
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 2^31, (that is, each integer fits in a 32-bit signed integer type), f.length >= 3, and f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.   Example 1: Input: num = "1101111" Output: [11,0,11,11] Explanation: The output [110, 1, 111] would also be accepted. Example 2: Input: num = "112358130" Output: [] Explanation: The task is impossible. Example 3: Input: num = "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.   Constraints: 1 <= num.length <= 200 num contains only digits.
def valid(a): if a[0] == '0': return len(a) == 1 return 0 <= int(a) <= 2 ** 31 - 1 def valid2(s, a, b): res = [a, b] while s: n = a + b if not s.startswith(str(n)) or not valid(str(n)): return False s = s[len(str(n)):] a, b = b, n res.append(n) return res class Solution(object): def splitIntoFibonacci(self, S): for i in range(1, len(S) - 2): for j in range(i+1, len(S) - 1): a = S[:i] b = S[i:j] if valid(a) and valid(b) and valid2(S[j:], int(a), int(b)): return valid2(S[j:], int(a), int(b)) return []
1223c1
f8d1bf
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 2^31, (that is, each integer fits in a 32-bit signed integer type), f.length >= 3, and f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.   Example 1: Input: num = "1101111" Output: [11,0,11,11] Explanation: The output [110, 1, 111] would also be accepted. Example 2: Input: num = "112358130" Output: [] Explanation: The task is impossible. Example 3: Input: num = "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.   Constraints: 1 <= num.length <= 200 num contains only digits.
class Solution: def splitIntoFibonacci(self, S): """ :type S: str :rtype: List[int] """ n=len(S) self.arr=[] self.ans=[] def dfs(x): if x==n: if len(self.arr)>2: self.ans=self.arr return for i in range(x+1,n+1 if S[x]!='0' else x+2): this=int(S[x:i]) if this>=2**31: break if len(self.arr)<2 or self.arr[-2]+self.arr[-1]==this: self.arr.append(this) dfs(i) if len(self.ans)>0: return self.arr.pop() dfs(0) return self.ans
1fd0ff
8a0d70
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.   Example 1: Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 2: Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 3: Input: n = 3, connections = [[1,0],[2,0]] Output: 0   Constraints: 2 <= n <= 5 * 10000 connections.length == n - 1 connections[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
class Solution(object): def minReorder(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: int """ graph = collections.defaultdict(set) for x, y in connections: graph[x].add(y) graph[y].add(x) frontier = deque() frontier.append(0) dist = collections.defaultdict(int) dist[0] = 0 while frontier: curr = frontier.popleft() for nbr in graph[curr]: if nbr not in dist: dist[nbr]=dist[curr]+1 frontier.append(nbr) ans = 0 for x, y in connections: if dist[x] < dist[y]: ans += 1 return ans
df233c
8a0d70
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.   Example 1: Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 2: Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 3: Input: n = 3, connections = [[1,0],[2,0]] Output: 0   Constraints: 2 <= n <= 5 * 10000 connections.length == n - 1 connections[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: f = [[] for _ in range(n)] r = [[] for _ in range(n)] for s, t in connections: f[s].append(t) r[t].append(s) seen = set([0]) q = [0] ans = 0 while q: n = q.pop() for m in r[n]: if m not in seen: seen.add(m) q.append(m) for m in f[n]: if m not in seen: seen.add(m) q.append(m) ans += 1 return ans
a3d524
be79d4
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 10^9 + 7.   Example 1: Input: words = ["acca","bbbb","caca"], target = "aba" Output: 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: Input: words = ["abba","baab"], target = "bab" Output: 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")   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 All strings in words have the same length. 1 <= target.length <= 1000 words[i] and target contain only lowercase English letters.
class Solution: def numWays(self, words: List[str], target: str) -> int: MOD = 10 ** 9 + 7 Nt = len(target) Nw = len(words[0]) counts = [[0] * 26 for _ in range(Nw)] for word in words: for index, x in enumerate(word): counts[index][ord(x)-ord('a')] += 1 @lru_cache(None) def go(index, target_index): if target_index == Nt: return 1 if index == Nw: return 0 total = 0 total += go(index + 1, target_index) total %= MOD total += go(index + 1, target_index + 1) * counts[index][ord(target[target_index])-ord('a')] total %= MOD return total % MOD return go(0, 0) % MOD
90d215
be79d4
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 10^9 + 7.   Example 1: Input: words = ["acca","bbbb","caca"], target = "aba" Output: 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: Input: words = ["abba","baab"], target = "bab" Output: 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")   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 All strings in words have the same length. 1 <= target.length <= 1000 words[i] and target contain only lowercase English letters.
class Solution(object): def numWays(self, words, target): """ :type words: List[str] :type target: str :rtype: int """ dp = {} mod = 1000000007 mm = len(target) n, m = len(words), len(words[0]) cs = [{} for _ in range(m)] i = 0 while i<m: j=0 while j<n: c = words[j][i] if c not in cs[i]: cs[i][c]=0 cs[i][c]+=1 j+=1 i+=1 def dfs(s, p): if s==mm: return 1 if p==m: return 0 k = (s, p) rc = 0 if k in dp: return dp[k] rc = dfs(s, p+1) c = target[s] if c in cs[p]: t = cs[p][c]*dfs(s+1, p+1) t %= mod rc += t rc %= mod dp[k]=rc return rc return dfs(0, 0)
7a8f83
825fd9
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.   Example 1: Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete. Example 2: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" Explanation: First delete "eee" and "ccc", get "ddbbbdaa" Then delete "bbb", get "dddaa" Finally delete "ddd", get "aa" Example 3: Input: s = "pbbcggttciiippooaais", k = 2 Output: "ps"   Constraints: 1 <= s.length <= 100000 2 <= k <= 10000 s only contains lowercase English letters.
class Solution(object): def removeDuplicates(self, S, K): stack = [] for c in S: if not stack: stack.append([c, 1]) elif stack[-1][0] != c: stack.append([c, 1]) elif stack[-1][1] + 1 < K: stack[-1][1] += 1 else: stack.pop() ans = [] for c,ct in stack: ans.extend([c] * ct) return "".join(ans)
ff0e92
825fd9
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.   Example 1: Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete. Example 2: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" Explanation: First delete "eee" and "ccc", get "ddbbbdaa" Then delete "bbb", get "dddaa" Finally delete "ddd", get "aa" Example 3: Input: s = "pbbcggttciiippooaais", k = 2 Output: "ps"   Constraints: 1 <= s.length <= 100000 2 <= k <= 10000 s only contains lowercase English letters.
class Solution: def removeDuplicates(self, s: str, k: int) -> str: st = [] last = None for c in s: if last is None: last = [c, 1] st.append(last) else: if last[0] == c: last[1] += 1 if last[1] == k: st.pop() if st: last = st[-1] else: last = None else: last = [c, 1] st.append(last) ans = [] for c, v in st: ans.append(c*v) return "".join(ans)
94d148
ac9dc0
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: n = len(nums) j = ans = 0 mx = mi = nums[0] for i, v in enumerate(nums): mx = max(mx, v) mi = min(mi, v) while mx - mi > limit: if mx == nums[j]: mx = max(nums[j + 1: i + 1]) if mi == nums[j]: mi= min(nums[j + 1: i + 1]) j += 1 ans = max(ans, i - j + 1) return ans
7dd9c7
ac9dc0
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import heapq class Solution(object): def get_top_heap(self, my_heap, range_l, range_r): while True: val, pos = my_heap[0] if pos < range_l or pos > range_r: heapq.heappop(my_heap) else: return val def longestSubarray(self, nums, limit): """ :type nums: List[int] :type limit: int :rtype: int """ # Can do min queue approach beg = 0 end = 0 ans = 0 min_heap = [(nums[0], 0)] max_heap = [(-nums[0], 0)] while True: ans = max(ans, end-beg+1) if end == len(nums) - 1: break end += 1 # Move right pointer, adding to heap heapq.heappush(min_heap, (nums[end], end)) heapq.heappush(max_heap, (-nums[end], end)) minn = self.get_top_heap(min_heap, beg, end) maxx = -self.get_top_heap(max_heap, beg, end) while maxx - minn > limit: beg += 1 minn = self.get_top_heap(min_heap, beg, end) maxx = -1*self.get_top_heap(max_heap, beg, end) return ans
e5c185
b5412c
You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: nums.length == n nums[i] is a positive integer where 0 <= i < n. abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. The sum of all the elements of nums does not exceed maxSum. nums[index] is maximized. Return nums[index] of the constructed array. Note that abs(x) equals x if x >= 0, and -x otherwise.   Example 1: Input: n = 4, index = 2, maxSum = 6 Output: 2 Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2]. Example 2: Input: n = 6, index = 1, maxSum = 10 Output: 3   Constraints: 1 <= n <= maxSum <= 10^9 0 <= index < n
def minSum(span, start): end = start - span + 1 if end > 0: return (start + end) * span // 2 return (span - start) + (start + 1)*start // 2 class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: def ok(t): right = n - index left = index + 1 theSum = minSum(left, t) + minSum(right, t) - t return theSum <= maxSum low = 1 high = maxSum + 1 assert(ok(low)) assert(not ok(high)) while high - low > 2: mid = (low + high) // 2 if ok(mid): low = mid else: high = mid for t in range(low, low + 10): if not ok(t): return t-1
f42a66
b5412c
You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: nums.length == n nums[i] is a positive integer where 0 <= i < n. abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. The sum of all the elements of nums does not exceed maxSum. nums[index] is maximized. Return nums[index] of the constructed array. Note that abs(x) equals x if x >= 0, and -x otherwise.   Example 1: Input: n = 4, index = 2, maxSum = 6 Output: 2 Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2]. Example 2: Input: n = 6, index = 1, maxSum = 10 Output: 3   Constraints: 1 <= n <= maxSum <= 10^9 0 <= index < n
class Solution(object): def maxValue(self, n, index, maxSum): """ :type n: int :type index: int :type maxSum: int :rtype: int """ maxSum -= n def f(h, w): w = min(w, h) return ((2*h+1-w)*w) // 2 def test(val): return f(val, index+1) + f(val, n-index) - val <= maxSum a, b = 0, 1 while test(b): b <<= 1 while a + 1 < b: c = (a + b) >> 1 if test(c): a = c else: b = c return b
7fcdd9
f790da
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.   Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. Example 2: Input: richer = [], quiet = [0] Output: [0]   Constraints: n == quiet.length 1 <= n <= 500 0 <= quiet[i] < n All the values of quiet are unique. 0 <= richer.length <= n * (n - 1) / 2 0 <= ai, bi < n ai != bi All the pairs of richer are unique. The observations in richer are all logically consistent.
class Solution: def dfs(self, x): if self.ret[x] is not None: return # print(x, self.edge[x]) self.ret[x] = x for i in self.edge[x]: self.dfs(i) if self.q[self.ret[i]] < self.q[self.ret[x]]: self.ret[x] = self.ret[i] def loudAndRich(self, richer, quiet): """ :type richer: List[List[int]] :type quiet: List[int] :rtype: List[int] """ import collections self.q = quiet self.n = len(quiet) self.edge = [collections.deque() for _ in range(self.n)] for (p, q) in richer: self.edge[q].append(p) self.ret = [None for _ in range(self.n)] for i in range(self.n): self.dfs(i) return self.ret
37f9dc
f790da
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.   Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. Example 2: Input: richer = [], quiet = [0] Output: [0]   Constraints: n == quiet.length 1 <= n <= 500 0 <= quiet[i] < n All the values of quiet are unique. 0 <= richer.length <= n * (n - 1) / 2 0 <= ai, bi < n ai != bi All the pairs of richer are unique. The observations in richer are all logically consistent.
class Solution(object): def loudAndRich(self, richer, quiet): graph = [[] for _ in quiet] graph2 = [[] for _ in quiet] count = [0 for _ in quiet] for x, y in richer: graph[x].append(y) graph2[y].append(x) count[y] += 1 zeroes = [] for i, x in enumerate(count): if x == 0: zeroes.append(i) res = [] while zeroes: node = zeroes.pop() res.append(node) for child in graph[node]: count[child] -= 1 if count[child] == 0: zeroes.append(child) answer = range(len(quiet)) for node in res: for richer in graph2[node]: answer[node] = min(answer[node], answer[richer], key=lambda x: quiet[answer[x]]) return answer
99dcad
b03f50
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: Input: s = "aba", t = "baba" Output: 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: Input: s = "ab", t = "bb" Output: 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.   Constraints: 1 <= s.length, t.length <= 100 s and t consist of lowercase English letters only.
class Solution: def countSubstrings(self, s: str, t: str) -> int: if len(s) > len(t): s, t = t, s Ns = len(s) Nt = len(t) N = len(s) total = 0 for i in range(len(s)): for j in range(len(t)): count = 0 for L in range(N): if i + L >= Ns or j + L >= Nt: break if s[i+L] != t[j+L]: count += 1 if count == 1: total += 1 #print(i, j, L, total) return total
fced54
b03f50
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: Input: s = "aba", t = "baba" Output: 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: Input: s = "ab", t = "bb" Output: 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.   Constraints: 1 <= s.length, t.length <= 100 s and t consist of lowercase English letters only.
class Solution(object): def countSubstrings(self, S, T): ans = 0 for i in xrange(len(S)): for j in xrange(len(T)): if S[i] != T[j]: lo = hi = 0 while i-(lo+1) >= 0 and j-(lo+1) >= 0 and S[i-(lo+1)] == T[j-(lo+1)]: lo += 1 while i+(hi+1) < len(S) and j+(hi+1) < len(T) and S[i+(hi+1)] == T[j+(hi+1)]: hi += 1 lo+=1;hi+=1 # print("!", i, j, lo, hi) ans += lo * hi return ans
20d8e7
6665c5
Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: houses = [1,4,8,10,20], k = 3 Output: 5 Explanation: Allocate mailboxes in position 3, 9 and 20. Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 Example 2: Input: houses = [2,3,5,12,18], k = 2 Output: 9 Explanation: Allocate mailboxes in position 3 and 14. Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.   Constraints: 1 <= k <= houses.length <= 100 1 <= houses[i] <= 10000 All the integers of houses are unique.
class Solution: def minDistance(self, x: List[int], k: int) -> int: inf = 10**9 n = len(x) x = sorted(x) b = [[inf] * n for i in range(n)] for i in range(n): for j in range(i, n): b[i][j] = 0 for t in range(i, j + 1): b[i][j] += abs(x[t] - x[(i + j) // 2]) d = [[inf] * (n + 1) for i in range(k + 1)] d[0][0] = 0 for p in range(1, k + 1): d[p][0] = 0 for i in range(1, n + 1): d[p][i] = min(d[p][i], d[p-1][i]) for j in range(i): d[p][i] = min(d[p][i], d[p-1][j] + b[j][i-1]) return d[k][n]
e24d4d
6665c5
Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: houses = [1,4,8,10,20], k = 3 Output: 5 Explanation: Allocate mailboxes in position 3, 9 and 20. Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 Example 2: Input: houses = [2,3,5,12,18], k = 2 Output: 9 Explanation: Allocate mailboxes in position 3 and 14. Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.   Constraints: 1 <= k <= houses.length <= 100 1 <= houses[i] <= 10000 All the integers of houses are unique.
class Solution(object): def minDistance(self, houses, k): """ :type houses: List[int] :type k: int :rtype: int """ h,n = sorted(houses), len(houses) dis = {} for i in range(n): for j in range(i, n): m=(i+j)/2 s=0 for kk in range(i, m): s+=h[m]-h[kk] for kk in range(m+1, j+1): s += h[kk]-h[m] dis[(i,j)]=s # print (i,j), s dp = {} def dfs(i, k): if n-i<=k: return 0; if k==0: return -1 kk = (i, k) if kk in dp: return dp[kk] r = -1 j=i; while j<n: t = dfs(j+1, k-1) if t>=0: t+=dis[(i,j)] if r<0 or r>t: r=t j+=1 # print kk, r dp[kk]=r return r return dfs(0, k)
a7890e
85b315
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.   Example 1: Input: s = "cczazcc", repeatLimit = 3 Output: "zzcccac" Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac". The letter 'a' appears at most 1 time in a row. The letter 'c' appears at most 3 times in a row. The letter 'z' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac". Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString. Example 2: Input: s = "aababab", repeatLimit = 2 Output: "bbabaa" Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa". The letter 'a' appears at most 2 times in a row. The letter 'b' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa". Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.   Constraints: 1 <= repeatLimit <= s.length <= 100000 s consists of lowercase English letters.
class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: cnt = [0] * 26 for ch in s: cnt[ord(ch) - ord('a')] += 1 last = -1 ans = [] while True: seen = False change = False for i in range(25, -1, -1): if i != last and cnt[i] > 0: change = True if seen: ans.append(i) cnt[i] -= 1 last = i else: ans.extend([i] * min(cnt[i], repeatLimit)) cnt[i] -= min(cnt[i], repeatLimit) last = i break elif cnt[i] > 0: seen = True if not change: break return "".join([chr(ord('a') + i) for i in ans])
b6741f
85b315
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.   Example 1: Input: s = "cczazcc", repeatLimit = 3 Output: "zzcccac" Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac". The letter 'a' appears at most 1 time in a row. The letter 'c' appears at most 3 times in a row. The letter 'z' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac". Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString. Example 2: Input: s = "aababab", repeatLimit = 2 Output: "bbabaa" Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa". The letter 'a' appears at most 2 times in a row. The letter 'b' appears at most 2 times in a row. Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString. The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa". Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.   Constraints: 1 <= repeatLimit <= s.length <= 100000 s consists of lowercase English letters.
class Solution(object): def repeatLimitedString(self, s, repeatLimit): """ :type s: str :type repeatLimit: int :rtype: str """ n = len(s) fre = [0]*26 for c in s: fre[ord(c)-97] += 1 ans = [] pre = -1 times = 0 for _ in range(n): flag = False for i in range(25,-1,-1): if fre[i] > 0: if pre==i and times>=repeatLimit: continue fre[i] -= 1 ans += [chr(97+i)] if i==pre: times += 1 else: times = 1 pre = i flag = True break if not flag: break return "".join(ans)
fdad7d
ad74fd
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents: A land cell if grid[r][c] = 0, or A water cell containing grid[r][c] fish, if grid[r][c] > 0. A fisher can start at any water cell (r, c) and can do the following operations any number of times: Catch all the fish at cell (r, c), or Move to any adjacent water cell. Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists. An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) or (r - 1, c) if it exists.   Example 1: Input: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] Output: 7 Explanation: The fisher can start at cell (1,3) and collect 3 fish, then move to cell (2,3) and collect 4 fish. Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] Output: 1 Explanation: The fisher can start at cells (0,0) or (3,3) and collect a single fish.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10 0 <= grid[i][j] <= 10
class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) vis = [[0] * m for _ in range(n)] ans = 0 for i in range(n): for j in range(m): if not vis[i][j] and grid[i][j]: dq = deque([[i, j]]) vis[i][j] = 1 res = 0 while dq: x, y = dq.popleft() res += grid[x][y] for dx, dy in pairwise([1, 0, -1, 0, 1]): if 0 <= x + dx < n and 0 <= y + dy < m and grid[x + dx][y + dy] and not vis[x + dx][y + dy]: vis[x + dx][y + dy] = 1 dq.append([x + dx, y + dy]) ans = max(ans, res) return ans
849346
ad74fd
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents: A land cell if grid[r][c] = 0, or A water cell containing grid[r][c] fish, if grid[r][c] > 0. A fisher can start at any water cell (r, c) and can do the following operations any number of times: Catch all the fish at cell (r, c), or Move to any adjacent water cell. Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists. An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) or (r - 1, c) if it exists.   Example 1: Input: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] Output: 7 Explanation: The fisher can start at cell (1,3) and collect 3 fish, then move to cell (2,3) and collect 4 fish. Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] Output: 1 Explanation: The fisher can start at cells (0,0) or (3,3) and collect a single fish.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10 0 <= grid[i][j] <= 10
class Solution(object): def findMaxFish(self, grid): """ :type grid: List[List[int]] :rtype: int """ ans = 0 n = len(grid) m = len(grid[0]) for i in range(n): for j in range(m): if grid[i][j] > 0: fish = grid[i][j] grid[i][j] = 0 q = [(i, j)] while len(q) > 0: x, y = q.pop(0) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: a = x+dx b = y+dy if 0 <= a < n and 0 <= b < m and grid[a][b] > 0: fish += grid[a][b] grid[a][b] = 0 q.append((a, b)) if fish > ans: ans = fish return ans
1818fb
bbc45e
You are given a string s that consists of the digits '1' to '9' and two integers k and minLength. A partition of s is called beautiful if: s is partitioned into k non-intersecting substrings. Each substring has a length of at least minLength. Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime. Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 10^9 + 7. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "23542185131", k = 3, minLength = 2 Output: 3 Explanation: There exists three ways to create a beautiful partition: "2354 | 218 | 5131" "2354 | 21851 | 31" "2354218 | 51 | 31" Example 2: Input: s = "23542185131", k = 3, minLength = 3 Output: 1 Explanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131". Example 3: Input: s = "3312958", k = 3, minLength = 1 Output: 1 Explanation: There exists one way to create a beautiful partition: "331 | 29 | 58".   Constraints: 1 <= k, minLength <= s.length <= 1000 s consists of the digits '1' to '9'.
class Solution(object): def beautifulPartitions(self, s, k, minLength): """ :type s: str :type k: int :type minLength: int :rtype: int """ s, d = '1' + s, [[0] * (len(s) + 1) for _ in range(k)] for i in range(k): if i == 0: for j in range(minLength, len(s)): d[i][j] = 1 if s[1] in '2357' and not s[j] in '2357' else 0 else: c = 0 for j in range(minLength, len(s)): c, d[i][j] = (c + d[i - 1][j - minLength]) % 1000000007 if j - minLength >= 0 and s[j - minLength + 1] in '2357' and not s[j - minLength] in '2357' else c, 0 if s[j] in '2357' else (c + d[i - 1][j - minLength]) % 1000000007 if j - minLength >= 0 and s[j - minLength + 1] in '2357' and not s[j - minLength] in '2357' else c return d[k - 1][len(s) - 1]
076f3c
bbc45e
You are given a string s that consists of the digits '1' to '9' and two integers k and minLength. A partition of s is called beautiful if: s is partitioned into k non-intersecting substrings. Each substring has a length of at least minLength. Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime. Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 10^9 + 7. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "23542185131", k = 3, minLength = 2 Output: 3 Explanation: There exists three ways to create a beautiful partition: "2354 | 218 | 5131" "2354 | 21851 | 31" "2354218 | 51 | 31" Example 2: Input: s = "23542185131", k = 3, minLength = 3 Output: 1 Explanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131". Example 3: Input: s = "3312958", k = 3, minLength = 1 Output: 1 Explanation: There exists one way to create a beautiful partition: "331 | 29 | 58".   Constraints: 1 <= k, minLength <= s.length <= 1000 s consists of the digits '1' to '9'.
class Solution: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: p = 10 ** 9 + 7 primes = set('2357') n = len(s) dp = [[0 for j in range(n + 1)] for i in range(k + 1)] dp[0][-1] = 1 for i in range(1, k + 1): total = 0 for j in range(n): if j + 1 >= minLength and s[j + 1 - minLength] in primes: total += dp[i - 1][j - minLength] total %= p if s[j] in primes: continue dp[i][j] = total # print(dp[i]) return dp[k][n - 1]
5f5069
846d28
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: Input: aliceValues = [1,3], bobValues = [2,1] Output: 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: Input: aliceValues = [1,2], bobValues = [3,1] Output: 0 Explanation: If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. Draw. Example 3: Input: aliceValues = [2,4,3], bobValues = [1,6,7] Output: -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.   Constraints: n == aliceValues.length == bobValues.length 1 <= n <= 100000 1 <= aliceValues[i], bobValues[i] <= 100
class Solution: def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int: f = [] for i in range(len(aliceValues)): f.append([aliceValues[i], bobValues[i]]) f.sort(key = lambda x:(-(x[0] + x[1]))) x = 0 y = 0 for i in range(len(f)): if i % 2 == 0: x += f[i][0] else: y += f[i][1] if x > y: return 1 elif x == y: return 0 else: return -1
ed7511
846d28
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: Input: aliceValues = [1,3], bobValues = [2,1] Output: 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: Input: aliceValues = [1,2], bobValues = [3,1] Output: 0 Explanation: If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. Draw. Example 3: Input: aliceValues = [2,4,3], bobValues = [1,6,7] Output: -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.   Constraints: n == aliceValues.length == bobValues.length 1 <= n <= 100000 1 <= aliceValues[i], bobValues[i] <= 100
class Solution(object): def stoneGameVI(self, A, B): A = sorted(zip(A, B), key=lambda a_b: +a_b[0] + a_b[1]) return cmp(sum(a for a, b in A[-1::-2]), sum(b for a, b in A[-2::-2]))
e14d00
85fcf3
A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.   Example 1: Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]] Output: 3 Explanation: The largest magic square has a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 12. - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums: 5+4+3 = 6+4+2 = 12 Example 2: Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]] Output: 2   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j] <= 1000000
class Solution(object): def largestMagicSquare(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) s = min(m, n) rsum = [[0]*(n+1) for _ in range(m)] for i in range(m): for j in range(n): rsum[i][j+1]=rsum[i][j]+grid[i][j] csum = [[0]*(m+1) for _ in range(n)] for i in range(n): for j in range(m): csum[i][j+1]=csum[i][j]+grid[j][i] def check(s): i=0 while i+s<=m: j=0 ei=i+s-1 while j+s<=n: ej = j+s-1 v = rsum[i][ej+1]-rsum[i][j] k=i+1 while k<=ei: t = rsum[k][ej+1]-rsum[k][j] if t!=v: break k+=1 if k<=ei: j+=1 continue k=j while k<=ej: t = csum[k][ei+1]-csum[k][i] if t!=v: break k+=1 if k<=ej: j+=1 continue k=0 t=0 while k<s: t+=grid[i+k][j+k] k+=1 if t!=v: j+=1 continue k, t = 0, 0 while k<s: t+=grid[i+s-1-k][j+k] k+=1 if t==v: return True j+=1 i+=1 return False while s>1: if check(s): break s-=1 return s
6f5bf4
85fcf3
A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.   Example 1: Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]] Output: 3 Explanation: The largest magic square has a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 12. - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums: 5+4+3 = 6+4+2 = 12 Example 2: Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]] Output: 2   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j] <= 1000000
class Solution: def largestMagicSquare(self, grid: List[List[int]]) -> int: def check(u, v, l): nonlocal grid, sumu, sumv s = 0 for i in range(0, l): s += grid[u - i][v - i] t = 0 for i in range(0, l): t += grid[u - i][v - ((l - 1) - i)] if s != t: return False for i in range(u - l + 1, u + 1): if sumv[i][v] - sumv[i][v - l] != s: return False for i in range(v - l + 1, v + 1): if sumu[u][i] - sumu[u - l][i] != s: return False return True m = len(grid) n = len(grid[0]) sumu = [[0 for j in range(n + 1)] for i in range(m + 1)] sumv = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(m): for j in range(n): sumu[i][j] = grid[i][j] + sumu[i - 1][j] sumv[i][j] = grid[i][j] + sumv[i][j - 1] for k in range(min(m, n), 1, -1): for i in range(k - 1, m): for j in range(k - 1, n): if check(i, j, k): return k return 1
185832
caca49
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 10^9 + 7.   Example 1: Input: n = 3, k = 0 Output: 1 Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. Example 2: Input: n = 3, k = 1 Output: 2 Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.   Constraints: 1 <= n <= 1000 0 <= k <= 1000
MODULUS = 10**9 + 7 class Solution(object): def kInversePairs(self, n, k): """ :type n: int :type k: int :rtype: int """ # f(n, k) := sum of f(n-1, k-i) for i in xrange(n) def computeNext(w, n): r = [0] * len(w) s = 0 for i, v in enumerate(w): s = (s + v) % MODULUS if i-n >= 0: s = (s - w[i-n]) % MODULUS r[i] = s return r # f(0, k) := 1 if k==0 else 0 ways = [1] + [0]*k for m in xrange(n): ways = computeNext(ways, m+1) return ways[-1]
eb4038
0a9d01
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked. Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user. Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors. Implement the LockingTree class: LockingTree(int[] parent) initializes the data structure with the parent array. lock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user. unlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked. upgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded.   Example 1: Input ["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"] [[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]] Output [null, true, false, true, true, true, false] Explanation LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]); lockingTree.lock(2, 2); // return true because node 2 is unlocked. // Node 2 will now be locked by user 2. lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2. lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2. // Node 2 will now be unlocked. lockingTree.lock(4, 5); // return true because node 4 is unlocked. // Node 4 will now be locked by user 5. lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4). // Node 0 will now be locked by user 1 and node 4 will now be unlocked. lockingTree.lock(0, 1); // return false because node 0 is already locked.   Constraints: n == parent.length 2 <= n <= 2000 0 <= parent[i] <= n - 1 for i != 0 parent[0] == -1 0 <= num <= n - 1 1 <= user <= 10000 parent represents a valid tree. At most 2000 calls in total will be made to lock, unlock, and upgrade.
class LockingTree(object): def __init__(self, parent): self.p = parent self.locked = {} self.lc = collections.defaultdict(set) def lock(self, i, user): if i in self.locked: return False self.locked[i] = user j = self.p[i] while j != -1: self.lc[j].add(i) j = self.p[j] return True def unlock(self, i, user): if self.locked.get(i, -1) != user: return False del self.locked[i] j = self.p[i] while j != -1: self.lc[j].remove(i) j = self.p[j] return True def upgrade(self, i, user): if i in self.locked: return False if not self.lc[i]: return False j = self.p[i] while j != -1: if j in self.locked: return False j = self.p[j] for j in list(self.lc[i]): self.unlock(j, self.locked[j]) self.lock(i, user) return True # Your LockingTree object will be instantiated and called as such: # obj = LockingTree(parent) # param_1 = obj.lock(num,user) # param_2 = obj.unlock(num,user) # param_3 = obj.upgrade(num,user)
4e839d
0a9d01
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked. Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user. Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors. Implement the LockingTree class: LockingTree(int[] parent) initializes the data structure with the parent array. lock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user. unlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked. upgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded.   Example 1: Input ["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"] [[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]] Output [null, true, false, true, true, true, false] Explanation LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]); lockingTree.lock(2, 2); // return true because node 2 is unlocked. // Node 2 will now be locked by user 2. lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2. lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2. // Node 2 will now be unlocked. lockingTree.lock(4, 5); // return true because node 4 is unlocked. // Node 4 will now be locked by user 5. lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4). // Node 0 will now be locked by user 1 and node 4 will now be unlocked. lockingTree.lock(0, 1); // return false because node 0 is already locked.   Constraints: n == parent.length 2 <= n <= 2000 0 <= parent[i] <= n - 1 for i != 0 parent[0] == -1 0 <= num <= n - 1 1 <= user <= 10000 parent represents a valid tree. At most 2000 calls in total will be made to lock, unlock, and upgrade.
class LockingTree: def __init__(self, parent: List[int]): self.parent = parent N = len(parent) children = [[] for _ in range(N)] for c, p in enumerate(parent): if p >= 0: children[p].append(c) self.children = children lock_status = [None] * N self.lock_status = lock_status def lock(self, num: int, user: int) -> bool: if self.lock_status[num] is None: self.lock_status[num] = user return True else: return False def unlock(self, num: int, user: int) -> bool: if self.lock_status[num] == user: self.lock_status[num] = None return True else: return False def upgrade(self, num: int, user: int) -> bool: p = num while p != -1: if self.lock_status[p] is not None: return False p = self.parent[p] def _check(num): if self.lock_status[num] is not None: return True else: return any(_check(n) for n in self.children[num]) if not _check(num): return False def _unlock(num): if self.lock_status[num] is not None: self.lock_status[num] = None for n in self.children[num]: _unlock(n) _unlock(num) self.lock_status[num] = user return True # Your LockingTree object will be instantiated and called as such: # obj = LockingTree(parent) # param_1 = obj.lock(num,user) # param_2 = obj.unlock(num,user) # param_3 = obj.upgrade(num,user)
6a38ba
85f401
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 10^9 + 7.   Example 1: Input: arr = [2,4] Output: 3 Explanation: We can make these trees: [2], [4], [4, 2, 2] Example 2: Input: arr = [2,4,5,10] Output: 7 Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].   Constraints: 1 <= arr.length <= 1000 2 <= arr[i] <= 10^9 All the values of arr are unique.
class Solution(object): def numFactoredBinaryTrees(self, A): """ :type A: List[int] :rtype: int """ m=10**9+7 s=set(A) A.sort() n=len(A) dp=[1]*n for i in range(n): for j in range(i): if A[i]%A[j]==0: q=A[i]//A[j] if q==A[j]: dp[i]+=dp[j]**2 elif q in s: dp[i]+=dp[j]*dp[A.index(q)] dp[i]%=m return sum(dp)%m
022540
85f401
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 10^9 + 7.   Example 1: Input: arr = [2,4] Output: 3 Explanation: We can make these trees: [2], [4], [4, 2, 2] Example 2: Input: arr = [2,4,5,10] Output: 7 Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].   Constraints: 1 <= arr.length <= 1000 2 <= arr[i] <= 10^9 All the values of arr are unique.
class Solution: def numFactoredBinaryTrees(self, A): """ :type A: List[int] :rtype: int """ M = 10 ** 9 + 7 # make all possible binary trees # asc order A = sorted(A) avail = set(A) from collections import defaultdict combos = defaultdict(int) for i, x in enumerate(A): # try as a root combos[x] = 1 for j in range(i): # try smaller divisor if x % A[j] == 0: combos[x] += combos[A[j]] * combos[x // A[j]] return sum(combos.values()) % M
ab8cd4
9e5d3f
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually.   Example 1: Input: p = 2, q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. Example 2: Input: p = 3, q = 1 Output: 1   Constraints: 1 <= q <= p <= 1000
class Solution(object): def mirrorReflection(self, p, q): """ :type p: int :type q: int :rtype: int """ if 0 == q: return 0 x, y = 0, 0 while 1: x += p y += q if 0 == y % p: break # print x, y, x / p, y / p if (x / p) % 2: if (y / p) % 2: return 1 return 0 return 2
64ff17
9e5d3f
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually.   Example 1: Input: p = 2, q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. Example 2: Input: p = 3, q = 1 Output: 1   Constraints: 1 <= q <= p <= 1000
class Solution: def mirrorReflection(self, p, q): """ :type p: int :type q: int :rtype: int """ def gcd(x, y): if x % y == 0: return y return gcd(y, x % y) lcm = p * q // gcd(p, q) y = lcm // p x = lcm // q return 0 if x % 2 == 1 and y % 2 == 0 else \ 1 if x % 2 == 1 and y % 2 == 1 else \ 2
db8fd2
2644de
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.   Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.   Constraints: 1 <= s.length <= 100000 s consists of only uppercase English letters. 0 <= k <= s.length
class Solution(object): def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ table = {} res = 0 p1 = p2 = 0 while p2 < len(s): table[s[p2]] = table.get(s[p2], 0) + 1 p2 += 1 while sum(table.values()) - max(table.values()) > k: table[s[p1]] -= 1 p1 += 1 res = max(res, p2 - p1) return res
5a6b66
94df7e
You are given a string s and an array of strings words. You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in words. If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag. If two substrings wrapped by bold tags are consecutive, you should combine them. Return s after adding the bold tags. Example 1: Input: s = "abcxyz123", words = ["abc","123"] Output: "<b>abc</b>xyz<b>123</b>" Explanation: The two strings of words are substrings of s as following: "abcxyz123". We add <b> before each substring and </b> after each substring. Example 2: Input: s = "aaabbb", words = ["aa","b"] Output: "<b>aaabbb</b>" Explanation: "aa" appears as a substring two times: "aaabbb" and "aaabbb". "b" appears as a substring three times: "aaabbb", "aaabbb", and "aaabbb". We add <b> before each substring and </b> after each substring: "<b>a<b>a</b>a</b><b>b</b><b>b</b><b>b</b>". Since the first two <b>'s overlap, we merge them: "<b>aaa</b><b>b</b><b>b</b><b>b</b>". Since now the four <b>'s are consecuutive, we merge them: "<b>aaabbb</b>". Constraints: 1 <= s.length <= 1000 0 <= words.length <= 100 1 <= words[i].length <= 1000 s and words[i] consist of English letters and digits. All the values of words are unique.
class Solution(object): def addBoldTag(self, s, dict): """ :type s: str :type dict: List[str] :rtype: str """ res = "" i = 0 while i < len(s): first = i last = i j = i while j <= last: for d in dict: if s[j:j+len(d)] == d: last = max(j+len(d), last) j += 1 if last > first: res += "<b>" + s[first:last] + "</b>" i = last else: res += s[i] i += 1 return res
400a52
94df7e
You are given a string s and an array of strings words. You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in words. If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag. If two substrings wrapped by bold tags are consecutive, you should combine them. Return s after adding the bold tags. Example 1: Input: s = "abcxyz123", words = ["abc","123"] Output: "<b>abc</b>xyz<b>123</b>" Explanation: The two strings of words are substrings of s as following: "abcxyz123". We add <b> before each substring and </b> after each substring. Example 2: Input: s = "aaabbb", words = ["aa","b"] Output: "<b>aaabbb</b>" Explanation: "aa" appears as a substring two times: "aaabbb" and "aaabbb". "b" appears as a substring three times: "aaabbb", "aaabbb", and "aaabbb". We add <b> before each substring and </b> after each substring: "<b>a<b>a</b>a</b><b>b</b><b>b</b><b>b</b>". Since the first two <b>'s overlap, we merge them: "<b>aaa</b><b>b</b><b>b</b><b>b</b>". Since now the four <b>'s are consecuutive, we merge them: "<b>aaabbb</b>". Constraints: 1 <= s.length <= 1000 0 <= words.length <= 100 1 <= words[i].length <= 1000 s and words[i] consist of English letters and digits. All the values of words are unique.
class Solution: def addBoldTag(self, s, d): """ :type s: str :type dict: List[str] :rtype: str """ import re interval = [] for word in d: l = len(word) q = '(?=' + word + ')' starts = [m.start() for m in re.finditer(q, s)] for t in starts: interval.append((t, t + l - 1)) interval.sort() final = [] cur = None for i in range(len(interval)): if cur is None: cur = interval[i] continue if interval[i][0] <= cur[1] + 1: if interval[i][1] > cur[1]: cur = (cur[0], interval[i][1]) else: final.append(cur) cur = interval[i] if (cur is not None): final.append(cur) print(interval) print(final) final.sort() res = '' index = 0 for i in range(len(final)): res += s[index:final[i][0]] res += '<b>' res += s[final[i][0]:final[i][1] + 1] res += '</b>' index = final[i][1] + 1 res += s[index:] return res
0f2983
0599ca
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.   Example 1: Input: nums = [1,4,3,7,4,5], k = 3 Output: 15 Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. Example 2: Input: nums = [5,5,4,5,4,1,1,1], k = 0 Output: 20 Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 2 * 10000 0 <= k < nums.length
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: nums = [0] + nums + [0] N = len(nums) k += 1 i, j = k, k cur = nums[k] ans = 0 while i > 0 or j < N - 1: while i > 0 and nums[i] >= cur: i -= 1 while j < N - 1 and nums[j] >= cur: j += 1 ans = max(ans, (j - i - 1) * cur) cur = nums[j] if nums[j] > nums[i] else nums[i] return ans
00a273
0599ca
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.   Example 1: Input: nums = [1,4,3,7,4,5], k = 3 Output: 15 Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. Example 2: Input: nums = [5,5,4,5,4,1,1,1], k = 0 Output: 20 Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 2 * 10000 0 <= k < nums.length
class Solution(object): def maximumScore(self, A, k): res = A[k] i = j = k leftm = rightm = A[k] n = len(A) while True: if i == 0: j += 1 elif j == n - 1: i -= 1 elif A[i - 1] < A[j + 1]: j += 1 else: i -= 1 if not (0 <= i and j < len(A)): break leftm = min(leftm, A[i]) rightm = min(rightm, A[j]) cur = min(leftm, rightm) * (j - i + 1) res = max(res, cur) return res
5748a6
735db7
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions. In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character. Return true if and only if you can transform str1 into str2. Example 1: Input: str1 = "aabcc", str2 = "ccdee" Output: true Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter. Example 2: Input: str1 = "leetcode", str2 = "codeleet" Output: false Explanation: There is no way to transform str1 to str2. Constraints: 1 <= str1.length == str2.length <= 10000 str1 and str2 contain only lowercase English letters.
class Solution: def canConvert(self, str1: str, str2: str) -> bool: s1 = dict() for i, ch in enumerate(str1): if ch not in s1: s1[ch] = list() s1[ch].append(i) s2 = dict() for i, ch in enumerate(str2): if ch not in s2: s2[ch] = list() s2[ch].append(i) if len(s1) == len(s2) == 26 and str1 != str2: return False for k, v in s1.items(): pivot = str2[v[0]] for pos in v: if str2[pos] != pivot: return False return True
9cf969
735db7
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions. In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character. Return true if and only if you can transform str1 into str2. Example 1: Input: str1 = "aabcc", str2 = "ccdee" Output: true Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter. Example 2: Input: str1 = "leetcode", str2 = "codeleet" Output: false Explanation: There is no way to transform str1 to str2. Constraints: 1 <= str1.length == str2.length <= 10000 str1 and str2 contain only lowercase English letters.
class Solution(object): def canConvert(self, s1, s2): """ :type str1: str :type str2: str :rtype: bool """ if s1 == s2: return True dp = {} for i,j in zip(s1,s2): if i not in dp: dp[i] = j else: if dp[i] != j: return False return len(set(dp.values())) < 26
b62793
773e13
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: The number of elements currently in nums that are strictly less than instructions[i]. The number of elements currently in nums that are strictly greater than instructions[i]. 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]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 10^9 + 7   Example 1: Input: instructions = [1,5,6,2] Output: 1 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. The total cost is 0 + 0 + 0 + 1 = 1. Example 2: Input: instructions = [1,2,3,6,5,4] Output: 3 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. Example 3: Input: instructions = [1,3,3,3,2,4,2,1,2] Output: 4 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. ​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.   Constraints: 1 <= instructions.length <= 100000 1 <= instructions[i] <= 100000
class Solution: def createSortedArray(self, instructions: List[int]) -> int: mod=10**9+7 from sortedcontainers import SortedList s=SortedList() ans=0 for x in instructions: l=s.bisect_left(x) r=s.bisect(x) ans+=min(l,len(s)-r) ans%=mod s.add(x) return ans
1d9f86
773e13
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: The number of elements currently in nums that are strictly less than instructions[i]. The number of elements currently in nums that are strictly greater than instructions[i]. 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]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 10^9 + 7   Example 1: Input: instructions = [1,5,6,2] Output: 1 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. The total cost is 0 + 0 + 0 + 1 = 1. Example 2: Input: instructions = [1,2,3,6,5,4] Output: 3 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. Example 3: Input: instructions = [1,3,3,3,2,4,2,1,2] Output: 4 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. ​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.   Constraints: 1 <= instructions.length <= 100000 1 <= instructions[i] <= 100000
class Solution(object): def createSortedArray(self, instructions): """ :type instructions: List[int] :rtype: int """ n = max(instructions) + 1 fen = [0] * (n+1) c = [0] * n def _get(i): r = 0 while i: r += fen[i] i -= i & -i return r def _upd(i): i += 1 while i <= n: fen[i] += 1 i += i & -i r = 0 for i, v in enumerate(instructions): below = _get(v) above = i - c[v] - below r += min(below, above) _upd(v) c[v] += 1 return r % (10**9 + 7)
df2a0a
3cbe09
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.   Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Example 2: Input: nums = [4,2,3,4] Output: 4   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000
class Solution(object): def triangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ m=max(nums) co=[0 for i in range(m+1)] cul=[0 for i in range(m+1)] for i in nums: co[i]+=1 tot=0 def s2(n): return n*(n-1)//2 def s3(n): return n*(n-1)*(n-2)//6 for i in range(1,m+1): cul[i]=cul[i-1]+co[i] for i in range(1,m+1): if co[i]<1: continue if co[i]>=2: if co[i]>=3: tot+=s3(co[i]) tot+=s2(co[i])*((cul[2*i-1] if 2*i-1<=m else cul[-1])-cul[i]) for j in range(i+1,m+1): if co[j]>=2: tot+=co[i]*s2(co[j]) tot+=co[i]*co[j]*((cul[(i+j-1)] if i+j-1<=m else cul[-1])-cul[j]) return tot
4fb498
4bf313
You are given the root of a binary tree with unique values. In one operation, you can choose any two nodes at the same level and swap their values. Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order. The level of a node is the number of edges along the path between it and the root node.   Example 1: Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10] Output: 3 Explanation: - Swap 4 and 3. The 2nd level becomes [3,4]. - Swap 7 and 5. The 3rd level becomes [5,6,8,7]. - Swap 8 and 7. The 3rd level becomes [5,6,7,8]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 2: Input: root = [1,3,2,7,6,5,4] Output: 3 Explanation: - Swap 3 and 2. The 2nd level becomes [2,3]. - Swap 7 and 4. The 3rd level becomes [4,6,5,7]. - Swap 6 and 5. The 3rd level becomes [4,5,6,7]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 3: Input: root = [1,2,3,4,5,6] Output: 0 Explanation: Each level is already sorted in increasing order so return 0.   Constraints: The number of nodes in the tree is in the range [1, 100000]. 1 <= Node.val <= 100000 All the values of the tree are unique.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: l = [root] ans = 0 edges = [[] for i in range(100005)] seen = [False] * 100005 def dfs(x): seen[x] = True tot = 1 for i in edges[x]: if not seen[i]: tot += dfs(i) return tot while l: c = [i.val for i in l] x = sorted(c) for i, j in zip(c, x): edges[i].append(j) edges[j].append(i) for i in c: if not seen[i]: ans += dfs(i)-1 nxt = [] for i in l: if i.left is not None: nxt.append(i.left) if i.right is not None: nxt.append(i.right) l = nxt[:] return ans
21e474
4bf313
You are given the root of a binary tree with unique values. In one operation, you can choose any two nodes at the same level and swap their values. Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order. The level of a node is the number of edges along the path between it and the root node.   Example 1: Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10] Output: 3 Explanation: - Swap 4 and 3. The 2nd level becomes [3,4]. - Swap 7 and 5. The 3rd level becomes [5,6,8,7]. - Swap 8 and 7. The 3rd level becomes [5,6,7,8]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 2: Input: root = [1,3,2,7,6,5,4] Output: 3 Explanation: - Swap 3 and 2. The 2nd level becomes [2,3]. - Swap 7 and 4. The 3rd level becomes [4,6,5,7]. - Swap 6 and 5. The 3rd level becomes [4,5,6,7]. We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed. Example 3: Input: root = [1,2,3,4,5,6] Output: 0 Explanation: Each level is already sorted in increasing order so return 0.   Constraints: The number of nodes in the tree is in the range [1, 100000]. 1 <= Node.val <= 100000 All the values of the tree are unique.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def minimumOperations(self, root): """ :type root: Optional[TreeNode] :rtype: int """ r, q = 0, [root] while q: a, c, m, v = [0] * len(q), [0] * len(q), {}, [False] * len(q) for i in range(len(a)): a[i], c[i], n = q[0].val, q[0].val, q.pop(0) if n.left: q.append(n.left) if n.right: q.append(n.right) c.sort() for i in range(len(a)): m[c[i]] = i for i in range(len(a)): if not v[i]: v[i], j = True, m[a[i]] while j != i: v[j], j, r = True, m[a[j]], r + 1 return r
735ceb
12b0d0
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array. Note that a swap exchanges the positions of two numbers arr[i] and arr[j]   Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.   Constraints: 1 <= arr.length <= 10000 1 <= arr[i] <= 10000
class Solution: def prevPermOpt1(self, A: List[int]) -> List[int]: n = len(A) for i in range(n - 1, 0, -1): if A[i - 1] > A[i]: for j in range(n - 1, 0, -1): if A[j] < A[i - 1]: A[j], A[i - 1] = A[i - 1], A[j] return A return A
a14f3e
12b0d0
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array. Note that a swap exchanges the positions of two numbers arr[i] and arr[j]   Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.   Constraints: 1 <= arr.length <= 10000 1 <= arr[i] <= 10000
class Solution(object): def prevPermOpt1(self, A): """ :type A: List[int] :rtype: List[int] """ # 4 1 1 3 3 # 3 1 2 3 4 5 2 n = len(A) for i in xrange(n-2, -1, -1): if A[i] <= A[i+1]: continue _, t = min((-A[j], j) for j in xrange(i+1, n) if A[j] < A[i]) A = A[:] A[i], A[t] = A[t], A[i] return A return A
0ce346
9d841d
You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m. You have to perform m independent queries on the tree where in the ith query you do the following: Remove the subtree rooted at the node with the value queries[i] from the tree. It is guaranteed that queries[i] will not be equal to the value of the root. Return an array answer of size m where answer[i] is the height of the tree after performing the ith query. Note: The queries are independent, so the tree returns to its initial state after each query. The height of a tree is the number of edges in the longest simple path from the root to some node in the tree.   Example 1: Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4] Output: [2] Explanation: The diagram above shows the tree after removing the subtree rooted at node with value 4. The height of the tree is 2 (The path 1 -> 3 -> 2). Example 2: Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8] Output: [3,2,3,2] Explanation: We have the following queries: - Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4). - Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1). - Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6). - Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).   Constraints: The number of nodes in the tree is n. 2 <= n <= 100000 1 <= Node.val <= n All the values in the tree are unique. m == queries.length 1 <= m <= min(n, 10000) 1 <= queries[i] <= n queries[i] != root.val
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def treeQueries(self, root, queries): """ :type root: Optional[TreeNode] :type queries: List[int] :rtype: List[int] """ def c(node): return 1 + c(node.left) + c(node.right) if node else 0 m, d, p, r, s, n, a = [0], [root.val], [0] * (c(root) + 1), [0] * (c(root) + 1), set(), [0], [0] * len(queries) def e(o, g): if o: r[o.val], n[0] = n[0] if o.val in s else m[0], max(n[0], g) if (not o.left or not o.left.val in s) and o.right and o.right.val in s: e(o.left, g + 1) e(o.right, g + 1) else: e(o.right, g + 1) e(o.left, g + 1) def f(o, g, q): if o: p[o.val], m[0], d[0] = q, max(m[0], g), o.val if g > m[0] else d[0] f(o.left, g + 1, o.val) f(o.right, g + 1, o.val) f(root, 0, -1) while d[0] != -1: s.add(d[0]) d[0] = p[d[0]] e(root, 0) for i in range(len(queries)): a[i] = r[queries[i]] return a
ab1ca7
9d841d
You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m. You have to perform m independent queries on the tree where in the ith query you do the following: Remove the subtree rooted at the node with the value queries[i] from the tree. It is guaranteed that queries[i] will not be equal to the value of the root. Return an array answer of size m where answer[i] is the height of the tree after performing the ith query. Note: The queries are independent, so the tree returns to its initial state after each query. The height of a tree is the number of edges in the longest simple path from the root to some node in the tree.   Example 1: Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4] Output: [2] Explanation: The diagram above shows the tree after removing the subtree rooted at node with value 4. The height of the tree is 2 (The path 1 -> 3 -> 2). Example 2: Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8] Output: [3,2,3,2] Explanation: We have the following queries: - Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4). - Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1). - Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6). - Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).   Constraints: The number of nodes in the tree is n. 2 <= n <= 100000 1 <= Node.val <= n All the values in the tree are unique. m == queries.length 1 <= m <= min(n, 10000) 1 <= queries[i] <= n queries[i] != root.val
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sz(self, node): if node == None: return 0 node.val -= 1 return 1 + self.sz(node.left) + self.sz(node.right) def ch(self, node, dep, par): if node == None: return self.h[node.val] = dep self.par[node.val] = par self.ti[node.val] = self.nex self.early[dep] = min(self.early[dep], self.nex) self.late[dep] = max(self.late[dep], self.nex) self.topo.append(node.val) assert self.topo[self.nex] == node.val self.nex += 1 self.ch(node.left, dep + 1, node.val) self.ch(node.right, dep + 1, node.val) def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]: n = self.sz(root) self.par = [-1] * n self.h = [-1] * n self.ti = [-1] * n self.early = [n] * (n + 5) self.late = [-1] * (n + 5) self.nex = 0 self.topo = [] self.ch(root, 0, -1) self.end = self.ti[:] for v in self.topo[::-1]: if self.par[v] != -1: self.end[self.par[v]] = max(self.end[self.par[v]], self.end[v]) out = [] for q in queries: q -= 1 lo = 0 hi = n + 1 while hi - lo > 1: mid = (lo + hi) // 2 if self.early[mid] >= self.ti[q] and self.late[mid] <= self.end[q]: hi = mid else: lo = mid out.append(lo) return out
15c52c
bf9196
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1], k = 1 Output: 1 Example 2: Input: nums = [1,2], k = 4 Output: -1 Example 3: Input: nums = [2,-1,2], k = 3 Output: 3   Constraints: 1 <= nums.length <= 100000 -100000 <= nums[i] <= 100000 1 <= k <= 10^9
class Solution: def shortestSubarray(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ ps = [0] for a in A: ps.append(a + ps[-1]) INF = len(ps) ans = INF q = collections.deque() for i in range(len(ps)): while q and ps[i] - ps[q[0]] >= K: ans = min(ans, i - q[0]) q.popleft() while q and ps[i] <= ps[q[-1]]: q.pop() q.append(i) return ans if ans < INF else -1
6eb7e7
bf9196
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1], k = 1 Output: 1 Example 2: Input: nums = [1,2], k = 4 Output: -1 Example 3: Input: nums = [2,-1,2], k = 3 Output: 3   Constraints: 1 <= nums.length <= 100000 -100000 <= nums[i] <= 100000 1 <= k <= 10^9
from collections import deque class Solution(object): def shortestSubarray(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ ans = self.find_minimal_length_subarr(A,K); if ans[0] == -1 or ans[1] == -1:return -1; return ans[1] - ans[0] + 1 def find_minimal_length_subarr(self,arr, k): sumBefore = [0] for x in arr: sumBefore.append(sumBefore[-1] + x) bestStart = -1 bestEnd = len(arr) startPoints = deque() start = 0 for end in range(len(arr)): totalToEnd = sumBefore[end+1] while startPoints and totalToEnd - sumBefore[startPoints[0]] >= k: start = startPoints.popleft() if totalToEnd - sumBefore[start] >= k and end-start < bestEnd-bestStart: bestStart,bestEnd = start,end while startPoints and totalToEnd <= sumBefore[startPoints[-1]]: startPoints.pop() startPoints.append(end+1) return (bestStart,bestEnd)
3f5b85
843c43
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.   Example 1: Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]] Output: [0,1,4] Explanation: Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4]. Example 2: Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]] Output: [0,1] Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1]. Example 3: Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]] Output: [0,1,2,3]   Constraints: 1 <= favoriteCompanies.length <= 100 1 <= favoriteCompanies[i].length <= 500 1 <= favoriteCompanies[i][j].length <= 20 All strings in favoriteCompanies[i] are distinct. All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j]. All strings consist of lowercase English letters only.
class Solution: def peopleIndexes(self, fc: List[List[str]]) -> List[int]: n = len(fc) a = [set(v) for v in fc] ret = [] for i in range(n): ok = 1 for j in range(n): if i != j and a[i] == (a[i] & a[j]): ok = 0 break if ok: ret += i, return ret
1e2614
843c43
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.   Example 1: Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]] Output: [0,1,4] Explanation: Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4]. Example 2: Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]] Output: [0,1] Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1]. Example 3: Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]] Output: [0,1,2,3]   Constraints: 1 <= favoriteCompanies.length <= 100 1 <= favoriteCompanies[i].length <= 500 1 <= favoriteCompanies[i][j].length <= 20 All strings in favoriteCompanies[i] are distinct. All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j]. All strings consist of lowercase English letters only.
class Solution(object): def peopleIndexes(self, favoriteCompanies): """ :type favoriteCompanies: List[List[str]] :rtype: List[int] """ r = [] a = map(set, favoriteCompanies) for i, v in enumerate(favoriteCompanies): if any(all(y in w for y in v) for j, w in enumerate(a) if i != j): continue r.append(i) return r
66a28a
6802c1
There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.   Example 1: Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = [], source = [0,0], target = [999999,999999] Output: true Explanation: Because there are no blocked cells, it is possible to reach the target square.   Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi, yi < 1000000 source.length == target.length == 2 0 <= sx, sy, tx, ty < 1000000 source != target It is guaranteed that source and target are not blocked.
class Solution(object): def isEscapePossible(self, blocked, source, target): """ :type blocked: List[List[int]] :type source: List[int] :type target: List[int] :rtype: bool """ if source in blocked or target in blocked: return False xlim=ylim=10**6 lim=10**4+10 blocked=set(tuple(p) for p in blocked) source=tuple(source) target=tuple(target) def dfs(p1,t): if find[0]: return if len(seen)>=lim: return seen.add(p1) for i,j in [[0,1],[0,-1],[1,0],[-1,0]]: if 0<=p1[0]+i<xlim and 0<=p1[1]+j<ylim: p2=(p1[0]+i,p1[1]+j) if p2==t: find[0]=True return if p2 not in blocked and p2 not in seen: dfs(p2,t) find=[False] seen=set() dfs(source,target) if find[0]: return True if len(seen)<lim: return False find=[False] seen=set() dfs(target,source) if find[0]: return True if len(seen)<lim: return False return True
b33292
6802c1
There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.   Example 1: Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = [], source = [0,0], target = [999999,999999] Output: true Explanation: Because there are no blocked cells, it is possible to reach the target square.   Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi, yi < 1000000 source.length == target.length == 2 0 <= sx, sy, tx, ty < 1000000 source != target It is guaranteed that source and target are not blocked.
class Solution: def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool: blocked = {(x, y) for x, y in blocked} source = tuple(source) target = tuple(target) def bfs(s, e): visited = {s} frontier = collections.deque([s]) while frontier: sz = len(frontier) if sz > len(blocked) * 4: return 1 for i in range(sz): r, c = frontier.popleft() if (r, c) == e: return 2 for newr, newc in (r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1): if 0 <= newr < 1000000 and 0 <= newc < 1000000 and (newr, newc) not in blocked and (newr, newc) not in visited: visited.add((newr, newc)) frontier.append((newr, newc)) return 0 return bfs(source, target) + bfs(target, source) > 1
559086
61e5d4
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1. speedi is the initial speed of the ith car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.   Example 1: Input: cars = [[1,2],[2,1],[4,3],[7,2]] Output: [1.00000,-1.00000,3.00000,-1.00000] Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. Example 2: Input: cars = [[3,4],[5,4],[6,3],[9,1]] Output: [2.00000,1.00000,1.50000,-1.00000]   Constraints: 1 <= cars.length <= 100000 1 <= positioni, speedi <= 1000000 positioni < positioni+1
class Solution: def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: h = [] ans = [-1] * len(cars) prv = [-1] + list(range(len(cars)-1)) nxt = list(range(1, len(cars))) + [-1] for i in range(len(cars)-1): a, b = cars[i] c, d = cars[i+1] if b > d: t = (c - a) / (b - d) heapq.heappush(h, (t, i, i+1)) while h: x, y, z = heapq.heappop(h) if ans[y] != -1: continue ans[y] = x a, b = prv[y], nxt[y] if b != -1: prv[b] = a if a != -1: nxt[a] = b if a != -1 and b != -1: y, z = a, b a, b = cars[y] c, d = cars[z] if b > d: t = (c - a) / (b - d) heapq.heappush(h, (t, y, z)) return ans
b640a1
61e5d4
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1. speedi is the initial speed of the ith car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.   Example 1: Input: cars = [[1,2],[2,1],[4,3],[7,2]] Output: [1.00000,-1.00000,3.00000,-1.00000] Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. Example 2: Input: cars = [[3,4],[5,4],[6,3],[9,1]] Output: [2.00000,1.00000,1.50000,-1.00000]   Constraints: 1 <= cars.length <= 100000 1 <= positioni, speedi <= 1000000 positioni < positioni+1
class Solution(object): def getCollisionTimes(self, cars): """ :type cars: List[List[int]] :rtype: List[float] """ n = len(cars) r = [-1] * n stack = [] for i in xrange(n-1, -1, -1): pos, speed = cars[i] while stack and cars[i][1] <= stack[-1][1]: stack.pop() while len(stack) >= 2: t1 = (stack[-1][0]-cars[i][0]) * (stack[-1][1]-stack[-2][1]) t2 = (stack[-2][0]-stack[-1][0]) * (cars[i][1]-stack[-1][1]) if t1 < t2: break stack.pop() if stack: r[i] = float(stack[-1][0]-cars[i][0]) / float(cars[i][1]-stack[-1][1]) stack.append(cars[i]) return r
5aeff2
ec18d9
In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. You are given an integer n. There is originally an array consisting of n integers from 1 to n in ascending order, return the number of derangements it can generate. Since the answer may be huge, return it modulo 10^9 + 7. Example 1: Input: n = 3 Output: 2 Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. Example 2: Input: n = 2 Output: 1 Constraints: 1 <= n <= 1000000
class Solution(object): def findDerangement(self, n): """ :type n: int :rtype: int """ # d(n) = d(n-2)*(n-1) + d(n-1)*(n-1) dp = [0]*max(3,n+1) dp[2] = 1 for i in xrange(3, n+1): dp[i] = ((i-1)*(dp[i-1]+dp[i-2])) % 1000000007 return dp[n]
963560
ec18d9
In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. You are given an integer n. There is originally an array consisting of n integers from 1 to n in ascending order, return the number of derangements it can generate. Since the answer may be huge, return it modulo 10^9 + 7. Example 1: Input: n = 3 Output: 2 Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. Example 2: Input: n = 2 Output: 1 Constraints: 1 <= n <= 1000000
class Solution: def findDerangement(self, n): """ :type n: int :rtype: int """ dp = [0 for _ in range(max(n+1, 3))] dp[2] = 1 for i in range(3, n+1): dp[i] = ((dp[i-1]+dp[i-2])*(i-1)) % (10**9+7) return dp[n]
801603
f9861f
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).   Example 1: Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] Explanation: Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. Example 2: Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]   Constraints: 1 <= people.length <= 2000 0 <= hi <= 1000000 0 <= ki < people.length It is guaranteed that the queue can be reconstructed.
class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ if not people: return [] n = len(people) ans = [(-1, -1)] * n for times in xrange(n): minx = (9999999, 9999999) minid = -1 for i, t in enumerate(people): if t < minx: minx = t minid = i h, kk = minx k = kk i = 0 while k: if ans[i][0] == -1 or ans[i][0] >= h: k -= 1 i += 1 while ans[i][0] != -1: i += 1 ans[i] = h, kk # print i, h, kk people[minid] = 99999999, 99999999 return ans
57254c
240673
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: All elements in nums are unique. The difference between the maximum element and the minimum element in nums equals nums.length - 1. For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.   Example 1: Input: nums = [4,2,5,3] Output: 0 Explanation: nums is already continuous. Example 2: Input: nums = [1,2,3,5,6] Output: 1 Explanation: One possible solution is to change the last element to 4. The resulting array is [1,2,3,5,4], which is continuous. Example 3: Input: nums = [1,10,100,1000] Output: 3 Explanation: One possible solution is to: - Change the second element to 2. - Change the third element to 3. - Change the fourth element to 4. The resulting array is [1,2,3,4], which is continuous.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
from typing import List from sortedcontainers import SortedList class Solution: def minOperations(self, nums: List[int]) -> int: n = len(nums) sort = SortedList(set(nums)) ans = n for idx, num in enumerate(sort): end = sort.bisect_right(num + n - 1) ans = min(ans, n - end + idx) return ans
fa20a9
240673
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: All elements in nums are unique. The difference between the maximum element and the minimum element in nums equals nums.length - 1. For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.   Example 1: Input: nums = [4,2,5,3] Output: 0 Explanation: nums is already continuous. Example 2: Input: nums = [1,2,3,5,6] Output: 1 Explanation: One possible solution is to change the last element to 4. The resulting array is [1,2,3,5,4], which is continuous. Example 3: Input: nums = [1,10,100,1000] Output: 3 Explanation: One possible solution is to: - Change the second element to 2. - Change the third element to 3. - Change the fourth element to 4. The resulting array is [1,2,3,4], which is continuous.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ vs = set() for v in nums: vs.add(v) vvs = sorted(list(vs)) i, n = 0, len(vvs) m = len(nums) r = m # print vvs while i<n: v=vvs[i] nv = v+m-1 j = bisect_right(vvs, nv) c = m-(j-i) if r>c: r=c i+=1 return r
b446c6
5a6583
You are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows: Let i0, i1, ... ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]). Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7.   Example 1: Input: nums = [2,1,4] Output: 141 Explanation: 1st group: [2] has power = 22 * 2 = 8. 2nd group: [1] has power = 12 * 1 = 1. 3rd group: [4] has power = 42 * 4 = 64. 4th group: [2,1] has power = 22 * 1 = 4. 5th group: [2,4] has power = 42 * 2 = 32. 6th group: [1,4] has power = 42 * 1 = 16. 7th group: [2,1,4] has power = 42 * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. Example 2: Input: nums = [1,1,1] Output: 7 Explanation: A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7.   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9
class Solution: def sumOfPower(self, nums: List[int]) -> int: MOD = 10 ** 9 + 7 out = 0 nums.sort() below = 0 for v in nums: sq = (v * v) out += (sq * below) % MOD out += (sq * v) % MOD below *= 2 below += v below %= MOD return out % MOD
fa927a
5a6583
You are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows: Let i0, i1, ... ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]). Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7.   Example 1: Input: nums = [2,1,4] Output: 141 Explanation: 1st group: [2] has power = 22 * 2 = 8. 2nd group: [1] has power = 12 * 1 = 1. 3rd group: [4] has power = 42 * 4 = 64. 4th group: [2,1] has power = 22 * 1 = 4. 5th group: [2,4] has power = 42 * 2 = 32. 6th group: [1,4] has power = 42 * 1 = 16. 7th group: [2,1,4] has power = 42 * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. Example 2: Input: nums = [1,1,1] Output: 7 Explanation: A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7.   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9
class Solution(object): def sumOfPower(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() n = len(nums) mod = 10**9+7 ans = pow(nums[0], 3, mod) s_till_now = nums[0] for i in range(1, n): ans = (ans + pow(nums[i], 3, mod))%mod ans = (ans + (nums[i]*nums[i]*s_till_now)%mod)%mod s_till_now = (s_till_now*2)%mod s_till_now += nums[i] return ans
54850e
9c01d2
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking. Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1. Example 1: Input: n = 3, relations = [[1,3],[2,3]] Output: 2 Explanation: The figure above represents the given graph. In the first semester, you can take courses 1 and 2. In the second semester, you can take course 3. Example 2: Input: n = 3, relations = [[1,2],[2,3],[3,1]] Output: -1 Explanation: No course can be studied because they are prerequisites of each other. Constraints: 1 <= n <= 5000 1 <= relations.length <= 5000 relations[i].length == 2 1 <= prevCoursei, nextCoursei <= n prevCoursei != nextCoursei All the pairs [prevCoursei, nextCoursei] are unique.
from collections import deque class Solution: def minimumSemesters(self, N: int, relations: List[List[int]]) -> int: in_cnt = [0 for _ in range(N + 1)] links = [[] for _ in range(N + 1)] for s, e in relations: links[s].append(e) in_cnt[e] += 1 c = 0 sem = [1e9 for _ in range(N + 1)] q = deque() for i in range(1, N + 1): if in_cnt[i] == 0: q.append(i) sem[i] = 1 while q: n = q.popleft() for nn in links[n]: in_cnt[nn] -= 1 if in_cnt[nn] == 0: q.append(nn) sem[nn] = sem[n] + 1 return max(sem[1:]) if max(sem[1:]) < 1e8 else -1
a5997e
9c01d2
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking. Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1. Example 1: Input: n = 3, relations = [[1,3],[2,3]] Output: 2 Explanation: The figure above represents the given graph. In the first semester, you can take courses 1 and 2. In the second semester, you can take course 3. Example 2: Input: n = 3, relations = [[1,2],[2,3],[3,1]] Output: -1 Explanation: No course can be studied because they are prerequisites of each other. Constraints: 1 <= n <= 5000 1 <= relations.length <= 5000 relations[i].length == 2 1 <= prevCoursei, nextCoursei <= n prevCoursei != nextCoursei All the pairs [prevCoursei, nextCoursei] are unique.
class Solution(object): def minimumSemesters(self, N, relations): """ :type N: int :type relations: List[List[int]] :rtype: int """ degs = [0] * N inputs, outputs = collections.defaultdict(set), collections.defaultdict(set) for i, j in relations: i -= 1 j -= 1 inputs[j].add(i) outputs[i].add(j) ans = 0 q = [i for i in range(N) if len(inputs[i]) == 0] visits = set(q) while q: q0 = [] for i in q: for j in list(outputs[i]): outputs[i].remove(j) inputs[j].remove(i) if not inputs[j]: q0.append(j) visits.add(j) q = q0 ans += 1 if len(visits) != N: return -1 return ans
c2e66f
d1615f
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: Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 Output: -1 Example 3: Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.   Constraints: 1 <= forbidden.length <= 1000 1 <= a, b, forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: queue = collections.deque() queue.append((0, 0, 0)) seen = set() forb = set(forbidden) while len(queue) > 0: d, now, used = queue[0] queue.popleft() #print(queue, d, now, used) if now == x: return d if now + a not in forb and now + a - b - b <= 4000 and (now + a, False) not in seen: queue.append((d + 1, now + a, False)) seen.add((now + a, False)) if now - b not in forb and now - b >= 0 and not used and (now - b, used) not in seen: queue.append((d + 1, now - b, True)) seen.add((now - b, True)) return -1
e1bb14
d1615f
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: Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 Output: -1 Example 3: Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.   Constraints: 1 <= forbidden.length <= 1000 1 <= a, b, forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.
class Solution(object): def minimumJumps(self, forbidden, a, b, x): """ :type forbidden: List[int] :type a: int :type b: int :type x: int :rtype: int """ ff = set() for i in forbidden: ff.add(i) from collections import deque q = deque() q.append((0,0)) ss = {} ss[(0, 0)]=0 def gcd(a, b): while b: a, b = b, a%b return a if a<b: g=gcd(b-a, a) else: g=-1 # print g while q: i, d = q.popleft() ck = (i, d) ni = i+a nk = (ni, 0) if ni not in ff and nk not in ss and ni<40000: q.append(nk) ss[nk]=ss[ck]+1 if d==0: ni = i-b nk = (ni, 1) if ni>=0 and ni not in ff and nk not in ss: q.append(nk) ss[nk]=ss[ck]+1 r = -1 if (x, 0) in ss: r = ss[(x,0)] if (x,1) in ss: t = ss[(x,1)] if r<0 or r>t: r=t return r
85b080
6dec6e
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1.   Example 1: Input: grid = ["@.a..","###.#","b.A.B"] Output: 8 Explanation: Note that the goal is to obtain all the keys not to open all the locks. Example 2: Input: grid = ["@..aA","..B#.","....b"] Output: 6 Example 3: Input: grid = ["@Aa"] Output: -1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 30 grid[i][j] is either an English letter, '.', '#', or '@'. The number of keys in the grid is in the range [1, 6]. Each key in the grid is unique. Each key in the grid has a matching lock.
from collections import deque class Solution(object): def shortestPathAllKeys(self, grid): """ :type grid: List[str] :rtype: int """ si, sj = 0, 0 n = len(grid) m = len(grid[0]) k = 0 for i in xrange(n): for j in xrange(m): if grid[i][j] == '@': si, sj = i, j if grid[i][j] >= 'a' and grid[i][j] <= 'f': k = max(k, ord(grid[i][j])-ord('a')+1) print k keys = 0 q = deque([(si, sj, 0, keys)]) vis = set([(si, sj, keys)]) while q: i, j, dst, keys = q.pop() for di, dj in [(-1, 0), (1, 0), (0, 1), (0, -1)]: ni, nj = i + di, j + dj if ni < 0 or ni == n or nj < 0 or nj == m: continue if grid[ni][nj] == '#': continue if grid[ni][nj] >= 'A' and grid[ni][nj] <= 'F': if (keys >> (ord(grid[ni][nj]) - ord('A'))) & 1 == 0: continue nkeys = keys if grid[ni][nj] >= 'a' and grid[ni][nj] <= 'f': nkeys |= (1 << (ord(grid[ni][nj]) - ord('a'))) if nkeys == (1 << k) - 1: return dst + 1 if (ni, nj, nkeys) in vis: continue q.appendleft((ni, nj, dst+1, nkeys)) vis.add((ni, nj, nkeys)) return -1
658226
6dec6e
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1.   Example 1: Input: grid = ["@.a..","###.#","b.A.B"] Output: 8 Explanation: Note that the goal is to obtain all the keys not to open all the locks. Example 2: Input: grid = ["@..aA","..B#.","....b"] Output: 6 Example 3: Input: grid = ["@Aa"] Output: -1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 30 grid[i][j] is either an English letter, '.', '#', or '@'. The number of keys in the grid is in the range [1, 6]. Each key in the grid is unique. Each key in the grid has a matching lock.
class Solution: def shortestPathAllKeys(self, grid): """ :type grid: List[str] :rtype: int """ n, m = len(grid), len(grid[0]) k = 0 for i in range(n): for j in range(m): if grid[i][j] == '@': si, sj = i, j elif 'a' <= grid[i][j] <= 'z': k += 1 if k == 0: return 0 kc = 1 << k allkeys = kc - 1 s = [[[False] * kc for j in range(m)] for i in range(n)] cur = [(si, sj, 0)] s[si][sj][0] = True step = 1 ds = [(1,0),(-1,0),(0,1),(0,-1)] while cur: next = [] for i, j, msk in cur: for di,dj in ds: ni,nj = i+di,j+dj nmsk = msk if not (0 <= ni < n and 0 <= nj < m): continue if grid[ni][nj] == '#': continue if 'A' <= grid[ni][nj] <= 'Z': door = ord(grid[ni][nj]) - ord('A') if (msk & (1 << door)) == 0: continue if 'a' <= grid[ni][nj] <= 'z': key = ord(grid[ni][nj]) - ord('a') nmsk |= 1 << key if nmsk == allkeys: return step if not s[ni][nj][nmsk]: s[ni][nj][nmsk] = True next.append((ni,nj,nmsk)) step, cur = step + 1, next return -1
eefde6
521ec7
Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it. You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]). The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, 'T' or 'F'. Example 1: Input: expression = "T?2:3" Output: "2" Explanation: If true, then result is 2; otherwise result is 3. Example 2: Input: expression = "F?1:T?4:5" Output: "4" Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: "(F ? 1 : (T ? 4 : 5))" --> "(F ? 1 : 4)" --> "4" or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4" Example 3: Input: expression = "T?T?F:5:3" Output: "F" Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: "(T ? (T ? F : 5) : 3)" --> "(T ? F : 3)" --> "F" "(T ? (T ? F : 5) : 3)" --> "(T ? F : 5)" --> "F" Constraints: 5 <= expression.length <= 10000 expression consists of digits, 'T', 'F', '?', and ':'. It is guaranteed that expression is a valid ternary expression and that each number is a one-digit number.
class Solution(object): def calc(self, a): if a[-1] == 'T': return a[-3] else: return a[-5] def parseTernary(self, expression): """ :type expression: str :rtype: str """ l = [] for c in reversed(expression): l.append(c) while len(l) >= 5 and l[-2] == '?' and l[-4] == ':': val = self.calc(l[-5:]) del l[-5:] l.append(val) return l[0]
ad89cc
884f96
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: Replace keyi and the bracket pair with the key's corresponding valuei. If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks). Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs.   Example 1: Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] Output: "bobistwoyearsold" Explanation: The key "name" has a value of "bob", so replace "(name)" with "bob". The key "age" has a value of "two", so replace "(age)" with "two". Example 2: Input: s = "hi(name)", knowledge = [["a","b"]] Output: "hi?" Explanation: As you do not know the value of the key "name", replace "(name)" with "?". Example 3: Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] Output: "yesyesyesaaa" Explanation: The same key can appear multiple times. The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". Notice that the "a"s not in a bracket pair are not evaluated.   Constraints: 1 <= s.length <= 100000 0 <= knowledge.length <= 100000 knowledge[i].length == 2 1 <= keyi.length, valuei.length <= 10 s consists of lowercase English letters and round brackets '(' and ')'. Every open bracket '(' in s will have a corresponding close bracket ')'. The key in each bracket pair of s will be non-empty. There will not be any nested bracket pairs in s. keyi and valuei consist of lowercase English letters. Each keyi in knowledge is unique.
class Solution(object): def evaluate(self, s, knowledge): M = {} for k,v in knowledge: M[k] = v ans = [] i = 0 while i < len(s): c = s[i] if c != '(': ans.append(c) i += 1 continue else: j = i while s[j] != ')': j += 1 inner = s[i+1:j] if inner in M: ans.append(M[inner]) else: ans.append('?') i = j + 1 return "".join(ans)
f7f49e
884f96
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: Replace keyi and the bracket pair with the key's corresponding valuei. If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks). Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs.   Example 1: Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] Output: "bobistwoyearsold" Explanation: The key "name" has a value of "bob", so replace "(name)" with "bob". The key "age" has a value of "two", so replace "(age)" with "two". Example 2: Input: s = "hi(name)", knowledge = [["a","b"]] Output: "hi?" Explanation: As you do not know the value of the key "name", replace "(name)" with "?". Example 3: Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] Output: "yesyesyesaaa" Explanation: The same key can appear multiple times. The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". Notice that the "a"s not in a bracket pair are not evaluated.   Constraints: 1 <= s.length <= 100000 0 <= knowledge.length <= 100000 knowledge[i].length == 2 1 <= keyi.length, valuei.length <= 10 s consists of lowercase English letters and round brackets '(' and ')'. Every open bracket '(' in s will have a corresponding close bracket ')'. The key in each bracket pair of s will be non-empty. There will not be any nested bracket pairs in s. keyi and valuei consist of lowercase English letters. Each keyi in knowledge is unique.
class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: d = dict() for key, val in knowledge: d[key] = val ans = [] l = 0 while l < len(s): if s[l] == '(': r = l + 1 while s[r] != ')': r += 1 key = s[l+1:r] if key in d: ans.append(d[key]) else: ans.append('?') l = r + 1 else: ans.append(s[l]) l += 1 return ''.join(ans)
c88d0c
8ed062
You are given two string arrays username and website and an integer array timestamp. All the given arrays are of the same length and the tuple [username[i], website[i], timestamp[i]] indicates that the user username[i] visited the website website[i] at time timestamp[i]. A pattern is a list of three websites (not necessarily distinct). For example, ["home", "away", "love"], ["leetcode", "love", "leetcode"], and ["luffy", "luffy", "luffy"] are all patterns. The score of a pattern is the number of users that visited all the websites in the pattern in the same order they appeared in the pattern. For example, if the pattern is ["home", "away", "love"], the score is the number of users x such that x visited "home" then visited "away" and visited "love" after that. Similarly, if the pattern is ["leetcode", "love", "leetcode"], the score is the number of users x such that x visited "leetcode" then visited "love" and visited "leetcode" one more time after that. Also, if the pattern is ["luffy", "luffy", "luffy"], the score is the number of users x such that x visited "luffy" three different times at different timestamps. Return the pattern with the largest score. If there is more than one pattern with the same largest score, return the lexicographically smallest such pattern. Example 1: Input: username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"] Output: ["home","about","career"] Explanation: The tuples in this example are: ["joe","home",1],["joe","about",2],["joe","career",3],["james","home",4],["james","cart",5],["james","maps",6],["james","home",7],["mary","home",8],["mary","about",9], and ["mary","career",10]. The pattern ("home", "about", "career") has score 2 (joe and mary). The pattern ("home", "cart", "maps") has score 1 (james). The pattern ("home", "cart", "home") has score 1 (james). The pattern ("home", "maps", "home") has score 1 (james). The pattern ("cart", "maps", "home") has score 1 (james). The pattern ("home", "home", "home") has score 0 (no user visited home 3 times). Example 2: Input: username = ["ua","ua","ua","ub","ub","ub"], timestamp = [1,2,3,4,5,6], website = ["a","b","a","a","b","c"] Output: ["a","b","a"] Constraints: 3 <= username.length <= 50 1 <= username[i].length <= 10 timestamp.length == username.length 1 <= timestamp[i] <= 10^9 website.length == username.length 1 <= website[i].length <= 10 username[i] and website[i] consist of lowercase English letters. It is guaranteed that there is at least one user who visited at least three websites. All the tuples [username[i], timestamp[i], website[i]] are unique.
class Solution: def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]: user_to_visit = dict() for i, user in enumerate(username): if user not in user_to_visit: user_to_visit[user] = list() user_to_visit[user].append((timestamp[i], website[i])) user_to_visit_ordered = dict() for k, v in user_to_visit.items(): user_to_visit_ordered[k] = sorted(v, key=lambda x: x[0]) three_sequence = dict() for k, v in user_to_visit_ordered.items(): user_three_sequence = set() if len(v) > 2: dd = len(v) for i in range(dd): for j in range(i + 1, dd): for k in range(j + 1, dd): user_three_sequence.add((v[i][1], v[j][1], v[k][1])) for key in user_three_sequence: if key not in three_sequence: three_sequence[key] = 1 else: three_sequence[key] += 1 ans = sorted(three_sequence.items(), key=lambda x: (-x[1], x[0][0], x[0][1], x[0][2]))[0] return list(ans[0])
5b16e7
8ed062
You are given two string arrays username and website and an integer array timestamp. All the given arrays are of the same length and the tuple [username[i], website[i], timestamp[i]] indicates that the user username[i] visited the website website[i] at time timestamp[i]. A pattern is a list of three websites (not necessarily distinct). For example, ["home", "away", "love"], ["leetcode", "love", "leetcode"], and ["luffy", "luffy", "luffy"] are all patterns. The score of a pattern is the number of users that visited all the websites in the pattern in the same order they appeared in the pattern. For example, if the pattern is ["home", "away", "love"], the score is the number of users x such that x visited "home" then visited "away" and visited "love" after that. Similarly, if the pattern is ["leetcode", "love", "leetcode"], the score is the number of users x such that x visited "leetcode" then visited "love" and visited "leetcode" one more time after that. Also, if the pattern is ["luffy", "luffy", "luffy"], the score is the number of users x such that x visited "luffy" three different times at different timestamps. Return the pattern with the largest score. If there is more than one pattern with the same largest score, return the lexicographically smallest such pattern. Example 1: Input: username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"] Output: ["home","about","career"] Explanation: The tuples in this example are: ["joe","home",1],["joe","about",2],["joe","career",3],["james","home",4],["james","cart",5],["james","maps",6],["james","home",7],["mary","home",8],["mary","about",9], and ["mary","career",10]. The pattern ("home", "about", "career") has score 2 (joe and mary). The pattern ("home", "cart", "maps") has score 1 (james). The pattern ("home", "cart", "home") has score 1 (james). The pattern ("home", "maps", "home") has score 1 (james). The pattern ("cart", "maps", "home") has score 1 (james). The pattern ("home", "home", "home") has score 0 (no user visited home 3 times). Example 2: Input: username = ["ua","ua","ua","ub","ub","ub"], timestamp = [1,2,3,4,5,6], website = ["a","b","a","a","b","c"] Output: ["a","b","a"] Constraints: 3 <= username.length <= 50 1 <= username[i].length <= 10 timestamp.length == username.length 1 <= timestamp[i] <= 10^9 website.length == username.length 1 <= website[i].length <= 10 username[i] and website[i] consist of lowercase English letters. It is guaranteed that there is at least one user who visited at least three websites. All the tuples [username[i], timestamp[i], website[i]] are unique.
class Solution(object): def mostVisitedPattern(self, username, timestamp, website): """ :type username: List[str] :type timestamp: List[int] :type website: List[str] :rtype: List[str] """ dp = {} count = collections.Counter() for t, u, w in sorted(zip(timestamp, username, website)): if u not in dp: dp[u] = [] dp[u].append(w) for u in dp: # print u, dp[u] for seq in set(seq for seq in itertools.combinations(dp[u], 3)): count[seq] += 1 target = max(count.values()) return min(list(k) for k in count if count[k] == target)
8d0e27
5113e5
There is a 0-indexed array nums of length n. Initially, all elements are uncolored (has a value of 0). You are given a 2D integer array queries where queries[i] = [indexi, colori]. For each query, you color the index indexi with the color colori in the array nums. Return an array answer of the same length as queries where answer[i] is the number of adjacent elements with the same color after the ith query. More formally, answer[i] is the number of indices j, such that 0 <= j < n - 1 and nums[j] == nums[j + 1] and nums[j] != 0 after the ith query.   Example 1: Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]] Output: [0,1,1,0,2] Explanation: Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [2,0,0,0]. The count of adjacent elements with the same color is 0. - After the 2nd query nums = [2,2,0,0]. The count of adjacent elements with the same color is 1. - After the 3rd query nums = [2,2,0,1]. The count of adjacent elements with the same color is 1. - After the 4th query nums = [2,1,0,1]. The count of adjacent elements with the same color is 0. - After the 5th query nums = [2,1,1,1]. The count of adjacent elements with the same color is 2. Example 2: Input: n = 1, queries = [[0,100000]] Output: [0] Explanation: Initially array nums = [0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [100000]. The count of adjacent elements with the same color is 0.   Constraints: 1 <= n <= 10^5 1 <= queries.length <= 10^5 queries[i].length == 2 0 <= indexi <= n - 1 1 <=  colori <= 10^5
class Solution: def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]: color = [0] * (n+2) tempv = 0 to_ret = [] for idt, cot in queries : idt += 1 if not color[idt] == 0 and color[idt] == color[idt-1] : tempv -= 1 if not color[idt] == 0 and color[idt] == color[idt+1] : tempv -= 1 color[idt] = cot if color[idt] == color[idt-1] : tempv += 1 if color[idt] == color[idt+1] : tempv += 1 to_ret.append(tempv) return to_ret
820ebe
5113e5
There is a 0-indexed array nums of length n. Initially, all elements are uncolored (has a value of 0). You are given a 2D integer array queries where queries[i] = [indexi, colori]. For each query, you color the index indexi with the color colori in the array nums. Return an array answer of the same length as queries where answer[i] is the number of adjacent elements with the same color after the ith query. More formally, answer[i] is the number of indices j, such that 0 <= j < n - 1 and nums[j] == nums[j + 1] and nums[j] != 0 after the ith query.   Example 1: Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]] Output: [0,1,1,0,2] Explanation: Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [2,0,0,0]. The count of adjacent elements with the same color is 0. - After the 2nd query nums = [2,2,0,0]. The count of adjacent elements with the same color is 1. - After the 3rd query nums = [2,2,0,1]. The count of adjacent elements with the same color is 1. - After the 4th query nums = [2,1,0,1]. The count of adjacent elements with the same color is 0. - After the 5th query nums = [2,1,1,1]. The count of adjacent elements with the same color is 2. Example 2: Input: n = 1, queries = [[0,100000]] Output: [0] Explanation: Initially array nums = [0], where 0 denotes uncolored elements of the array. - After the 1st query nums = [100000]. The count of adjacent elements with the same color is 0.   Constraints: 1 <= n <= 10^5 1 <= queries.length <= 10^5 queries[i].length == 2 0 <= indexi <= n - 1 1 <=  colori <= 10^5
class Solution(object): def colorTheArray(self, n, queries): """ :type n: int :type queries: List[List[int]] :rtype: List[int] """ a, b, c = [i + 131 for i in range(n)], [0] * len(queries), 0 for i in range(len(queries)): c, a[queries[i][0]], b[i] = c - (1 if queries[i][0] > 0 and a[queries[i][0]] == a[queries[i][0] - 1] else 0) - (1 if queries[i][0] < n - 1 and a[queries[i][0]] == a[queries[i][0] + 1] else 0) + (1 if queries[i][0] > 0 and queries[i][1] == a[queries[i][0] - 1] else 0) + (1 if queries[i][0] < n - 1 and queries[i][1] == a[queries[i][0] + 1] else 0), queries[i][1], c - (1 if queries[i][0] > 0 and a[queries[i][0]] == a[queries[i][0] - 1] else 0) - (1 if queries[i][0] < n - 1 and a[queries[i][0]] == a[queries[i][0] + 1] else 0) + (1 if queries[i][0] > 0 and queries[i][1] == a[queries[i][0] - 1] else 0) + (1 if queries[i][0] < n - 1 and queries[i][1] == a[queries[i][0] + 1] else 0) return b
fd192e
28b49f
There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.   Example 1: Input: heights = [10,6,8,5,11,9] Output: [3,1,2,1,1,0] Explanation: Person 0 can see person 1, 2, and 4. Person 1 can see person 2. Person 2 can see person 3 and 4. Person 3 can see person 4. Person 4 can see person 5. Person 5 can see no one since nobody is to the right of them. Example 2: Input: heights = [5,1,2,3,10] Output: [4,1,1,1,0]   Constraints: n == heights.length 1 <= n <= 100000 1 <= heights[i] <= 100000 All the values of heights are unique.
class Solution: def canSeePersonsCount(self, heights: List[int]) -> List[int]: n = len(heights) stack = [(999999, -1)] res = [0] * n for i, x in enumerate(heights): while x > stack[-1][0]: h, idx = stack.pop() res[idx] += 1 if stack[-1][1] != -1: res[stack[-1][1]] += 1 stack.append((x, i)) return res
9e500f
28b49f
There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.   Example 1: Input: heights = [10,6,8,5,11,9] Output: [3,1,2,1,1,0] Explanation: Person 0 can see person 1, 2, and 4. Person 1 can see person 2. Person 2 can see person 3 and 4. Person 3 can see person 4. Person 4 can see person 5. Person 5 can see no one since nobody is to the right of them. Example 2: Input: heights = [5,1,2,3,10] Output: [4,1,1,1,0]   Constraints: n == heights.length 1 <= n <= 100000 1 <= heights[i] <= 100000 All the values of heights are unique.
class Solution(object): def canSeePersonsCount(self, A): n = len(A) res = [0] * n stack = [] for i, v in enumerate(A): while stack and A[stack[-1]] <= v: j = stack.pop() res[j] +=1 if stack: res[stack[-1]] += 1 stack.append(i) return res
fb1299
630511
You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. Return the number of non-empty subarrays in nums that have a median equal to k. Note: The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4. A subarray is a contiguous part of an array.   Example 1: Input: nums = [3,2,1,4,5], k = 4 Output: 3 Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5]. Example 2: Input: nums = [2,3,1], k = 3 Output: 1 Explanation: [3] is the only subarray that has a median equal to 3.   Constraints: n == nums.length 1 <= n <= 100000 1 <= nums[i], k <= n The integers in nums are distinct.
class Solution(object): def countSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ i, m, s, r, t = -1, defaultdict(int), 0, 1, 0 for j in range(len(nums)): if nums[j] == k: i = j break m[0] = 1 for j in range(i - 1, -1, -1): s, r, m[s] = s + 1 if nums[j] < k else s - 1, r if nums[j] < k and s + 1 and s + 2 or nums[j] > k and s - 1 and s else r + 1, m[s + 1 if nums[j] < k else s - 1] + 1 for j in range(i + 1, len(nums)): t, r = t + 1 if nums[j] < k else t - 1, r + m[-t - 1 if nums[j] < k else 1 - t] + m[-t - 2 if nums[j] < k else -t] return r
be1127
630511
You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. Return the number of non-empty subarrays in nums that have a median equal to k. Note: The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4. A subarray is a contiguous part of an array.   Example 1: Input: nums = [3,2,1,4,5], k = 4 Output: 3 Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5]. Example 2: Input: nums = [2,3,1], k = 3 Output: 1 Explanation: [3] is the only subarray that has a median equal to 3.   Constraints: n == nums.length 1 <= n <= 100000 1 <= nums[i], k <= n The integers in nums are distinct.
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: cnt = Counter([0]) flag = False cur = 0 res = 0 for x in nums: cur += -1 if x < k else 1 if x > k else 0 flag = flag or x == k if not flag: cnt[cur] += 1 else: res += cnt[cur] + cnt[cur-1] return res
28abf7
af8ed3
You are given a 0-indexed binary string s which represents the types of buildings along a street where: s[i] = '0' denotes that the ith building is an office and s[i] = '1' denotes that the ith building is a restaurant. As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that would form "011" which is not allowed due to having two consecutive buildings of the same type. Return the number of valid ways to select 3 buildings.   Example 1: Input: s = "001101" Output: 6 Explanation: The following sets of indices selected are valid: - [0,2,4] from "001101" forms "010" - [0,3,4] from "001101" forms "010" - [1,2,4] from "001101" forms "010" - [1,3,4] from "001101" forms "010" - [2,4,5] from "001101" forms "101" - [3,4,5] from "001101" forms "101" No other selection is valid. Thus, there are 6 total ways. Example 2: Input: s = "11100" Output: 0 Explanation: It can be shown that there are no valid selections.   Constraints: 3 <= s.length <= 100000 s[i] is either '0' or '1'.
class Solution: def numberOfWays(self, s: str) -> int: def F(s, t): f = [0] * (len(t) + 1) f[0] = 1 for i in s: for j in range(len(t))[::-1]: if t[j] == i: f[j + 1] += f[j] return f[len(t)] return F(s, '010') + F(s, '101')
0525fb
40bcd3
You are given the head of a linked list. Remove every node which has a node with a strictly greater value anywhere to the right side of it. Return the head of the modified linked list.   Example 1: Input: head = [5,2,13,3,8] Output: [13,8] Explanation: The nodes that should be removed are 5, 2 and 3. - Node 13 is to the right of node 5. - Node 13 is to the right of node 2. - Node 8 is to the right of node 3. Example 2: Input: head = [1,1,1,1] Output: [1,1,1,1] Explanation: Every node has value 1, so no nodes are removed.   Constraints: The number of the nodes in the given list is in the range [1, 100000]. 1 <= Node.val <= 100000
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNodes(self, head): """ :type head: Optional[ListNode] :rtype: Optional[ListNode] """ s, p = [], head while p: while s and s[-1].val < p.val: s.pop() s.append(p) p = p.next while s: n = s.pop() n.next, p = p, n return p
cc81e4
40bcd3
You are given the head of a linked list. Remove every node which has a node with a strictly greater value anywhere to the right side of it. Return the head of the modified linked list.   Example 1: Input: head = [5,2,13,3,8] Output: [13,8] Explanation: The nodes that should be removed are 5, 2 and 3. - Node 13 is to the right of node 5. - Node 13 is to the right of node 2. - Node 8 is to the right of node 3. Example 2: Input: head = [1,1,1,1] Output: [1,1,1,1] Explanation: Every node has value 1, so no nodes are removed.   Constraints: The number of the nodes in the given list is in the range [1, 100000]. 1 <= Node.val <= 100000
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: st = [] p = head while p: while st and st[-1] < p.val: st.pop() st.append(p.val) p = p.next dh = ListNode() p = dh for x in st: p.next = ListNode(x) p = p.next return dh.next
251a29
f60415
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0.   Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. Example 2: Input: stones = [31,26,33,21,40] Output: 5   Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 100
class Solution: def lastStoneWeightII(self, a: List[int]) -> int: n = len(a) n1 = n // 2 a1 = a[:n1] n2 = n - n1 a2 = a[n1:] ar = [] for s in range(2**n1): t = 0 for k in range(n1): if s >> k & 1: t += a1[k] else: t -= a1[k] ar += [(t, 1)] for s in range(2**n2): t = 0 for k in range(n2): if s >> k & 1: t += a2[k] else: t -= a2[k] ar += [(t, 2)] ar = sorted(ar) ans = sum(a) for i in range(1, len(ar)): if ar[i][1] != ar[i - 1][1]: ans = min(ans, (ar[i][0] - ar[i-1][0])) return ans
12e970
f60415
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0.   Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. Example 2: Input: stones = [31,26,33,21,40] Output: 5   Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 100
class Solution(object): def lastStoneWeightII(self, stones): """ :type stones: List[int] :rtype: int """ self.D = {} return min(self.dp(stones, 0, len(stones)-1)) def dp(self, stones, i, j): if i > j: return [0] if i == j: return [stones[i]] if (i, j) in self.D: return self.D[(i,j)] s = set() for k in range(i, j): for num in self.dp(stones, i, k): s.update({abs(x - num) for x in self.dp(stones, k+1, j)}) self.D[(i,j)] = s return s
c70f08
af7c2c
You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free. You have a memory allocator with the following functionalities: Allocate a block of size consecutive free memory units and assign it the id mID. Free all memory units with the given id mID. Note that: Multiple blocks can be allocated to the same mID. You should free all the memory units with mID, even if they were allocated in different blocks. Implement the Allocator class: Allocator(int n) Initializes an Allocator object with a memory array of size n. int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. Return the block's first index. If such a block does not exist, return -1. int free(int mID) Free all memory units with the id mID. Return the number of memory units you have freed.   Example 1: Input ["Allocator", "allocate", "allocate", "allocate", "free", "allocate", "allocate", "allocate", "free", "allocate", "free"] [[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]] Output [null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0] Explanation Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free. loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0. loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1. loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2. loc.free(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2. loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3. loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1. loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6. loc.free(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1. loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1. loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.   Constraints: 1 <= n, size, mID <= 1000 At most 1000 calls will be made to allocate and free.
class Allocator: def __init__(self, n: int): self.lst = [-1]*n self.n = n def allocate(self, size: int, mID: int) -> int: pre = 0 for i in range(self.n): if self.lst[i] == -1: pre += 1 else: pre = 0 if pre == size: self.lst[i-pre+1:i+1] = [mID]*size return i-pre+1 return -1 def free(self, mID: int) -> int: ans = 0 for i in range(self.n): if self.lst[i] == mID: ans += 1 self.lst[i] = -1 return ans
955bef
af7c2c
You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free. You have a memory allocator with the following functionalities: Allocate a block of size consecutive free memory units and assign it the id mID. Free all memory units with the given id mID. Note that: Multiple blocks can be allocated to the same mID. You should free all the memory units with mID, even if they were allocated in different blocks. Implement the Allocator class: Allocator(int n) Initializes an Allocator object with a memory array of size n. int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. Return the block's first index. If such a block does not exist, return -1. int free(int mID) Free all memory units with the id mID. Return the number of memory units you have freed.   Example 1: Input ["Allocator", "allocate", "allocate", "allocate", "free", "allocate", "allocate", "allocate", "free", "allocate", "free"] [[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]] Output [null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0] Explanation Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free. loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0. loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1. loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2. loc.free(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2. loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3. loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1. loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6. loc.free(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1. loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1. loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.   Constraints: 1 <= n, size, mID <= 1000 At most 1000 calls will be made to allocate and free.
class Allocator(object): def __init__(self, n): self.mem = [0] * n self.n=n def allocate(self, size, mID): s = 0 for i in range(self.n): if self.mem[i] == 0: s += 1 else: s = 0 if s == size: for j in range(i - size + 1, i + 1): self.mem[j] = mID return i - size + 1 return -1 def free(self, mID): o = 0 for i in range(self.n): if self.mem[i] == mID: self.mem[i] = 0 o += 1 return o # Your Allocator object will be instantiated and called as such: # obj = Allocator(n) # param_1 = obj.allocate(size,mID) # param_2 = obj.free(mID)
e9883c
dcdca8
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: Input: nums = [1,3,1] Output: 0 Explanation: The array itself is a mountain array so we do not need to remove any elements. Example 2: Input: nums = [2,1,1,5,6,2,3,1] Output: 3 Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].   Constraints: 3 <= nums.length <= 1000 1 <= nums[i] <= 10^9 It is guaranteed that you can make a mountain array out of nums.
class Solution(object): def minimumMountainRemovals(self, A): def longest(A): stack = [] for a in A: i = bisect.bisect_left(stack, a) if i < len(stack): stack[i] = a else: stack.append(a) return stack.index(A[-1]) res = 0 for i in xrange(1, len(A) - 1): res = max(res, longest(A[:i+1]) + longest(A[i:][::-1]) + 1) return len(A) - res
873fe9
dcdca8
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: Input: nums = [1,3,1] Output: 0 Explanation: The array itself is a mountain array so we do not need to remove any elements. Example 2: Input: nums = [2,1,1,5,6,2,3,1] Output: 3 Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].   Constraints: 3 <= nums.length <= 1000 1 <= nums[i] <= 10^9 It is guaranteed that you can make a mountain array out of nums.
class Solution: def minimumMountainRemovals(self, nums: List[int]) -> int: n = len(nums) inc = [1] * n dec = inc[:] for i in range(0,len(inc)): for j in range(0,i): if nums[i] > nums[j]: inc[i] = max(inc[i],inc[j]+1) for i in range(n-1,-1,-1): for j in range(i+1,n): if nums[i] > nums[j]: dec[i] = max(dec[i],dec[j]+1) ans = 0 for i in range(0,n): if inc[i] > 1 and dec[i] > 1: ans = max(ans,inc[i]+dec[i]-1) return n-ans
f1f536
71518e
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.   Example 1: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] Output: 8 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 2: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] Output: 6 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 3: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] Output: 0   Constraints: 1 <= n <= 100000 edges.length == n - 1 edges[i].length == 2 0 <= ai < bi <= n - 1 hasApple.length == n
from collections import defaultdict class Solution(object): def minTime(self, n, edges, hasApple): """ :type n: int :type edges: List[List[int]] :type hasApple: List[bool] :rtype: int """ adj = defaultdict(list) for u, v in edges: adj[u].append(v) adj[v].append(u) r = [0] def f(u, p): s = hasApple[u] for v in adj[u]: if v == p: continue if f(v, u): r[0] += 2 s = True return s f(0, -1) return r[0]
f7e34d
71518e
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.   Example 1: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] Output: 8 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 2: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] Output: 6 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 3: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] Output: 0   Constraints: 1 <= n <= 100000 edges.length == n - 1 edges[i].length == 2 0 <= ai < bi <= n - 1 hasApple.length == n
class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: graph = [[] for __ in range(n)] for x in edges: graph[x[0]].append(x[1]) graph[x[1]].append(x[0]) def dfs(node, par): ans = 0 nhas = hasApple[node] for nxt in graph[node]: if nxt != par: has, res = dfs(nxt, node) if has: ans += res + 2 nhas |= has return nhas, ans has, res = dfs(0, -1) return res