sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
c452e8
b21185
You are given a string s and a positive integer k. Select a set of non-overlapping substrings from the string s that satisfy the following conditions: The length of each substring is at least k. Each substring is a palindrome. Return the maximum number of substrings in an optimal selection. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abaccdbbd", k = 3 Output: 2 Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3. It can be shown that we cannot find a selection with more than two valid substrings. Example 2: Input: s = "adbcda", k = 2 Output: 0 Explanation: There is no palindrome substring of length at least 2 in the string.   Constraints: 1 <= k <= s.length <= 2000 s consists of lowercase English letters.
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) ans = [] for i in range(n): st = i ed = i while st>=0 and ed<n and s[st]==s[ed]: st-=1 ed+=1 if ed-st-1>=k: ans.append([st+1,ed-1]) break st = i ed = i+1 while st>=0 and ed<n and s[st]==s[ed]: st-=1 ed+=1 if ed-st-1>=k: ans.append([st+1,ed-1]) break ans.sort(key = lambda x:x[1]) res = 0 last = -1 for st,ed in ans: if st>last: last = ed res+=1 return res
ded774
b21185
You are given a string s and a positive integer k. Select a set of non-overlapping substrings from the string s that satisfy the following conditions: The length of each substring is at least k. Each substring is a palindrome. Return the maximum number of substrings in an optimal selection. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abaccdbbd", k = 3 Output: 2 Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3. It can be shown that we cannot find a selection with more than two valid substrings. Example 2: Input: s = "adbcda", k = 2 Output: 0 Explanation: There is no palindrome substring of length at least 2 in the string.   Constraints: 1 <= k <= s.length <= 2000 s consists of lowercase English letters.
class Solution(object): def maxPalindromes(self, s, k): """ :type s: str :type k: int :rtype: int """ if k == 1: return len(s) r, d = [-1] * len(s), [0] * len(s) for i in range(len(s)): j, l = i, i - 1 while j < len(s) and s[j] == s[i]: r[j], j = r[j] if j - i + 1 < k else i if r[i] == -1 else max(r[j], i), j + 1 while l >= 0 and j < len(s) and s[l] == s[j]: r[j], j, l = r[j] if j - l + 1 < k else l if r[j] == -1 else max(r[j], l), j + 1, l - 1 for i in range(len(s)): d[i] = d[i - 1] if r[i] == -1 else max(d[i - 1], 1 + d[r[i] - 1] if r[i] else 1) return d[len(s) - 1]
f39c50
7c61cb
You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times: Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value. Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1. The gcd of two integers is the greatest common divisor of the two integers.   Example 1: Input: nums = [2,6,3,4] Output: 4 Explanation: We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. Example 2: Input: nums = [2,10,6,14] Output: -1 Explanation: It can be shown that it is impossible to make all the elements equal to 1.   Constraints: 2 <= nums.length <= 50 1 <= nums[i] <= 10^6 Follow-up: The O(n) time complexity solution works, but could you find an O(1) constant time complexity solution?
class Solution: def minOperations(self, nums: List[int]) -> int: if 1 in nums: return len(nums) - nums.count(1) res = -1 for i in range(len(nums)): for j in range(i, len(nums)): d = nums[j] for k in range(i, j): d = gcd(d, nums[k]) if d == 1: if res == -1 or j - i + 1 < res: res = j - i + 1 if res == -1: return -1 return len(nums) + res - 2
f36218
7c61cb
You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times: Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value. Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1. The gcd of two integers is the greatest common divisor of the two integers.   Example 1: Input: nums = [2,6,3,4] Output: 4 Explanation: We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. Example 2: Input: nums = [2,10,6,14] Output: -1 Explanation: It can be shown that it is impossible to make all the elements equal to 1.   Constraints: 2 <= nums.length <= 50 1 <= nums[i] <= 10^6 Follow-up: The O(n) time complexity solution works, but could you find an O(1) constant time complexity solution?
class Solution(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ def g(a, b): return g(b, a % b) if b else a c, h, a = 1 if nums[-1] == 1 else 0, 0, float('inf') for i in range(len(nums) - 1): c += 1 if nums[i] == 1 else 0 h += 1 if g(nums[i], nums[i + 1]) == 1 else 0 if c + h > 0: return len(nums) - c for i in range(len(nums) - 1): b = nums[i] for j in range(i + 1, len(nums)): a, b = min(a, j - i + len(nums) - 1) if g(b, nums[j]) == 1 else a, g(b, nums[j]) return -1 if a == float('inf') else a
e87571
3a7bf3
You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. For example, if nums = [1, 2, 3, 4]: [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively. Return the number of different good subsets in nums modulo 10^9 + 7. A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [1,2,3,4] Output: 6 Explanation: The good subsets are: - [1,2]: product is 2, which is the product of distinct prime 2. - [1,2,3]: product is 6, which is the product of distinct primes 2 and 3. - [1,3]: product is 3, which is the product of distinct prime 3. - [2]: product is 2, which is the product of distinct prime 2. - [2,3]: product is 6, which is the product of distinct primes 2 and 3. - [3]: product is 3, which is the product of distinct prime 3. Example 2: Input: nums = [4,2,3,15] Output: 5 Explanation: The good subsets are: - [2]: product is 2, which is the product of distinct prime 2. - [2,3]: product is 6, which is the product of distinct primes 2 and 3. - [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5. - [3]: product is 3, which is the product of distinct prime 3. - [15]: product is 15, which is the product of distinct primes 3 and 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 30
class Solution(object): def numberOfGoodSubsets(self, A): mod = 10 ** 9 + 7 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] dp = [0 for i in xrange(1 << 10)] dp[0] = 1 one = 0 count = collections.Counter(A) for a in count: if a == 1: continue if any(a % (p * p) == 0 for p in primes): continue mask = 0 for i, p in enumerate(primes): if a % p == 0: mask |= 1 << i for i in xrange(1 << 10): if i & mask == 0: dp[i | mask] += count[a] * dp[i] dp[i | mask] %= mod return (1 << count[1]) * (sum(dp) - 1) % mod
4e9545
3a7bf3
You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. For example, if nums = [1, 2, 3, 4]: [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively. Return the number of different good subsets in nums modulo 10^9 + 7. A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [1,2,3,4] Output: 6 Explanation: The good subsets are: - [1,2]: product is 2, which is the product of distinct prime 2. - [1,2,3]: product is 6, which is the product of distinct primes 2 and 3. - [1,3]: product is 3, which is the product of distinct prime 3. - [2]: product is 2, which is the product of distinct prime 2. - [2,3]: product is 6, which is the product of distinct primes 2 and 3. - [3]: product is 3, which is the product of distinct prime 3. Example 2: Input: nums = [4,2,3,15] Output: 5 Explanation: The good subsets are: - [2]: product is 2, which is the product of distinct prime 2. - [2,3]: product is 6, which is the product of distinct primes 2 and 3. - [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5. - [3]: product is 3, which is the product of distinct prime 3. - [15]: product is 15, which is the product of distinct primes 3 and 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 30
prims = [2,3,5,7,11,13,17,19,23,29] lookup_table = [None, 0] for i in range(2, 31): result = 0 for j, p in enumerate(prims): if i % p == 0: if (i // p) % p == 0: lookup_table.append(None) break else: result |= (1 << j) else: lookup_table.append(result) from collections import Counter class Solution: def numberOfGoodSubsets(self, nums: List[int]) -> int: dp = [0] * (1 << len(prims)) dp[0] = 1 c = Counter(nums) for k, v in sorted(c.items()): if k == 1: mul = pow(2, v, 1000000007) dp[0] = mul else: r = lookup_table[k] if r is None: continue for j in range(len(dp) - 1, -1, -1): if (j & r) == 0: dp[j | r] = (dp[j | r] + dp[j] * v) % 1000000007 return sum(dp[1:]) % 1000000007
881eb9
75e55a
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".   Example 1: Input: s = "banana" Output: "ana" Example 2: Input: s = "abcd" Output: ""   Constraints: 2 <= s.length <= 3 * 10000 s consists of lowercase English letters.
class Solution: def longestDupSubstring(self, S: str) -> str: oS = S S = [ord(i) - ord('a') for i in S] l, r = 0, len(S) ans = "" def check(s, l): if l == 0: return '' init = 0 sub = 1 for i in range(l - 1): sub *= 1007 sub %= int(1e20 + 7) for i in s[:l]: init *= 1007 init += i init %= int(1e20 + 7) occur = set([init]) for i, c in enumerate(s[l:]): init -= s[i] * sub init *= 1007 init += c init %= int(1e20 + 7) if init in occur: return oS[i + 1: i + l + 1] occur.add(init) return False while l <= r: m = (l + r) // 2 if type(check(S, m)) is str: ans = check(S, m) l = m + 1 else: r = m - 1 return ans
c04bb0
49776d
Given an array of unique strings words, return all the word squares you can build from words. The same word from words can be used multiple times. You can return the answer in any order. A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns). For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. Example 1: Input: words = ["area","lead","wall","lady","ball"] Output: [["ball","area","lead","lady"],["wall","area","lead","lady"]] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). Example 2: Input: words = ["abat","baba","atan","atal"] Output: [["baba","abat","baba","atal"],["baba","abat","baba","atan"]] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 4 All words[i] have the same length. words[i] consists of only lowercase English letters. All words[i] are unique.
class Solution(object): def wordSquares(self, words): """ :type words: List[str] :rtype: List[List[str]] """ self.l = len(words[0]) self.trie = self.build(words) self.res = [] for word in words: self.dfs(words, self.trie, [word]) return self.res def dfs(self, words, trie, lst): if len(lst) == self.l: self.res.append(lst) return prefix = '' for i in range(len(lst)): prefix += lst[i][len(lst)] for s in self.get(trie, prefix): self.dfs(words, trie, lst + [s]) def build(self, words): trie = {} for word in words: t = trie for c in word: if c not in t: t[c] = {} t = t[c] t['#'] = '#' return trie def get(self, trie, prefix): res = [] t = trie for c in prefix: if c not in t: return res t = t[c] for s in self.getall(t): res.append(prefix + s) return res def getall(self, t): res = [] if '#' in t: return [''] for c in t: if c != '#': for s in self.getall(t[c]): res.append(c + s) return res
41ba11
783878
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k.   Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 5 Output: 0 Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 100000
class Solution: def coutPairs(self, nums: List[int], k: int) -> int: n = len(nums) M = max(nums) cnt = [0] * (M + 1) for num in nums: cnt[num] += 1 cum = [0] * (M + 1) for i in range(1, M + 1): for j in range(i, M + 1, i): cum[i] += cnt[j] ans = 0 for i in range(1, M + 1): if cnt[i] > 0: g = k // math.gcd(i, k) if g <= M: ans += cnt[i] * cum[g] for num in nums: if (num * num) % k == 0: ans -= 1 return ans // 2
5bded5
783878
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k.   Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 5 Output: 0 Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 100000
class Solution(object): def coutPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ divs = [] ind = [0]*(k+1) for i in range(1,k+1): if k%i==0: divs.append(i) for i in range(len(divs)): ind[divs[i]]=i cnt = [0]*len(divs) for n in nums: g = self.gcd(n,k) cnt[ind[g]] += 1 #print(cnt) ans = 0 for i in range(len(divs)): for j in range(i,len(divs)): if (divs[i]*divs[j]) % k != 0: continue if i==j: ans += cnt[i]*(cnt[i]-1)//2 else: ans += cnt[i]*cnt[j] return ans def gcd(self,a,b): if a<b: return self.gcd(b,a) while b: a, b = b, a % b return a
436a87
550a36
You are given an integer array nums containing distinct numbers, and you can perform the following operations until the array is empty: If the first element has the smallest value, remove it Otherwise, put the first element at the end of the array. Return an integer denoting the number of operations it takes to make nums empty.   Example 1: Input: nums = [3,4,-1] Output: 5 OperationArray1[4, -1, 3]2[-1, 3, 4]3[3, 4]4[4]5[] Example 2: Input: nums = [1,2,4,3] Output: 5 OperationArray1[2, 4, 3]2[4, 3]3[3, 4]4[4]5[] Example 3: Input: nums = [1,2,3] Output: 3 OperationArray1[2, 3]2[3]3[]   Constraints: 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 All values in nums are distinct.
class FenwickTree: def __init__(self, n): self.n = n self.bit = [0] * n length = (self.n + 1).bit_length() - 1 self.powers = [1 << i for i in range(length, -1, -1)] self.tot = 0 def sum(self, r): res = 0 while r >= 0: res += self.bit[r] r = (r & (r + 1)) - 1 return res def rsum(self, l, r): return self.sum(r) - self.sum(l - 1) def add(self, idx, delta): while idx < self.n: self.bit[idx] += delta idx = idx | (idx + 1) self.tot += delta class Solution: def countOperationsToEmptyArray(self, nums: List[int]) -> int: n = len(nums) fen = FenwickTree(n) for i in range(n): fen.add(i, 1) d = Counter() for i, v in enumerate(nums): d[v] = i pos = 0 ans = 0 for v in sorted(d): if d[v] >= pos: ans += fen.rsum(pos, d[v]) else: ans += fen.rsum(pos, n-1) + fen.rsum(0, d[v]) fen.add(d[v], -1) pos = d[v] return ans
d70ad8
550a36
You are given an integer array nums containing distinct numbers, and you can perform the following operations until the array is empty: If the first element has the smallest value, remove it Otherwise, put the first element at the end of the array. Return an integer denoting the number of operations it takes to make nums empty.   Example 1: Input: nums = [3,4,-1] Output: 5 OperationArray1[4, -1, 3]2[-1, 3, 4]3[3, 4]4[4]5[] Example 2: Input: nums = [1,2,4,3] Output: 5 OperationArray1[2, 4, 3]2[4, 3]3[3, 4]4[4]5[] Example 3: Input: nums = [1,2,3] Output: 3 OperationArray1[2, 3]2[3]3[]   Constraints: 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 All values in nums are distinct.
from sortedcontainers import SortedList class Solution(object): def countOperationsToEmptyArray(self, nums): """ :type nums: List[int] :rtype: int """ sl = SortedList() data = [] for i, num in enumerate(nums): data.append((num, i)) data.sort() n = len(nums) ans = 0 now = -1 for num, idx in data: t = 0 if idx > now: i = sl.bisect_right(idx) j = sl.bisect_right(now) t += idx - now - (i - j) else: i = sl.bisect_right(idx) j = sl.bisect_right(now) # print(num, now, i, j, idx, n, idx - i + 1, n - 1 - now - (len(sl) - j)) t += idx - i + 1 + n - 1 - now - (len(sl) - j) # print(num, t) now = idx ans += t sl.add(idx) return ans
4c21ec
022a2c
Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7. The floor() function returns the integer part of the division.   Example 1: Input: nums = [2,5,9] Output: 10 Explanation: floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 floor(5 / 2) = 2 floor(9 / 2) = 4 floor(9 / 5) = 1 We calculate the floor of the division for every pair of indices in the array then sum them up. Example 2: Input: nums = [7,7,7,7,7,7,7] Output: 49   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: A = 100100 a = [0] * A c = [0] * A for x in nums: a[x] += 1 for x in range(1, A): c[x] = c[x - 1] + a[x] ret = 0 for x in range(1, A): if a[x]: for y in range(x, A, x): ret += a[x] * (c[-1] - c[y - 1]) return ret % 1000000007
c3a234
022a2c
Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7. The floor() function returns the integer part of the division.   Example 1: Input: nums = [2,5,9] Output: 10 Explanation: floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 floor(5 / 2) = 2 floor(9 / 2) = 4 floor(9 / 5) = 1 We calculate the floor of the division for every pair of indices in the array then sum them up. Example 2: Input: nums = [7,7,7,7,7,7,7] Output: 49   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution(object): def sumOfFlooredPairs(self, nums): """ :type nums: List[int] :rtype: int """ count = Counter(nums) ret = 0 mod = 10**9+7 nums = count.keys() nums.sort() A = [0 for i in range(nums[-1]+1)] for x in nums: p = x while p <= nums[-1]: A[p] += count[x] p += x ret = 0 psum = 0 for i in range(nums[-1]+1): psum += A[i] if i in count: ret = (ret + psum*count[i])%mod #for x in count: # if count[x] > 1: # ret = (ret + count[x]*(count[x]-1))%mod return ret ''' count = Counter(nums) ret = 0 mod = 10**9+7 for x in count: for y in count: ret = (ret + (x/y)*count[x]*count[y])%mod return ret ''' ''' mod = 10**9+7 ret = 0 for x in nums: for y in nums: ret = (ret + x/y)%mod return ret '''
9a14af
27eedb
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. Example 2: Input: rectangles = [[0,0,1000000000,1000000000]] Output: 49 Explanation: The answer is 10^18 modulo (10^9 + 7), which is 49.   Constraints: 1 <= rectangles.length <= 200 rectanges[i].length == 4 0 <= xi1, yi1, xi2, yi2 <= 10^9 xi1 <= xi2 yi1 <= yi2
class Solution: def rectangleArea(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ MOD = 1000000007 xset = set([]) yset = set([]) area = 0 for (x1, y1, x2, y2) in rectangles: xset.add(x1) xset.add(x2) yset.add(y1) yset.add(y2) xlist = sorted(list(xset)) ylist = sorted(list(yset)) # print(xlist) # print(ylist) area = 0 for i in range(len(xlist) - 1): for j in range(len(ylist) - 1): cnt = 0 for (x1, y1, x2, y2) in rectangles: if all([ xlist[i] >= x1, xlist[i + 1] <= x2, ylist[j] >= y1, ylist[j + 1] <= y2]): cnt += 1 break if cnt == 1: area += (xlist[i + 1] - xlist[i]) * (ylist[j + 1] - ylist[j]) area %= MOD return area
954fed
27eedb
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. Example 2: Input: rectangles = [[0,0,1000000000,1000000000]] Output: 49 Explanation: The answer is 10^18 modulo (10^9 + 7), which is 49.   Constraints: 1 <= rectangles.length <= 200 rectanges[i].length == 4 0 <= xi1, yi1, xi2, yi2 <= 10^9 xi1 <= xi2 yi1 <= yi2
class Solution(object): def rectangleArea(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ allX = set() allY = set() for x1,y1,x2,y2 in rectangles: allX.add(x1) allX.add(x2) allY.add(y1) allY.add(y2) allX = sorted(list(allX)) allY = sorted(list(allY)) # print allX # print allY xhm = {} yhm = {} for i in range(len(allX)): xhm[allX[i]] = i for i in range(len(allY)): yhm[allY[i]] = i # print xhm # print yhm nX = len(allX) - 1 nY = len(allY) - 1 m = 10**9 + 7 fill = [[0 for _ in range(nX)] for _ in range(nY)] area = [[0 for _ in range(nX)] for _ in range(nY)] for i in range(nY): ySize = allY[i+1] - allY[i] for j in range(nX): area[i][j] = (ySize * (allX[j+1] - allX[j]) ) % m for x1,y1,x2,y2 in rectangles: # print x1,y1,x2,y2 xStart = xhm[x1] xEnd = xhm[x2] yStart = yhm[y1] yEnd = yhm[y2] for i in range(yStart, yEnd): for j in range(xStart, xEnd): fill[i][j] = 1 # print area # print fill result = 0 for i in range(nY): for j in range(nX): if fill[i][j] == 1: result += area[i][j] return result % m
42561d
a5e58a
Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks.   Example 1: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. Example 2: Input: tasks = ["A","A","A","B","B","B"], n = 0 Output: 6 Explanation: On this case any permutation of size 6 would work since n = 0. ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... And so on. Example 3: Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 Output: 16 Explanation: One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A   Constraints: 1 <= task.length <= 10000 tasks[i] is upper-case English letter. The integer n is in the range [0, 100].
from collections import Counter class Solution: def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ total = len(tasks) my_dict = Counter(tasks) m = total count = 0 max_happen = 0 for k in my_dict.keys(): if my_dict[k] > max_happen: max_happen = my_dict[k] count = 1 elif my_dict[k] == max_happen: count += 1 m1 = (n + 1)*(max_happen - 1) + count return max(m1, m)
73a9bf
a5e58a
Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks.   Example 1: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. Example 2: Input: tasks = ["A","A","A","B","B","B"], n = 0 Output: 6 Explanation: On this case any permutation of size 6 would work since n = 0. ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... And so on. Example 3: Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 Output: 16 Explanation: One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A   Constraints: 1 <= task.length <= 10000 tasks[i] is upper-case English letter. The integer n is in the range [0, 100].
class Solution(object): def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ from heapq import * hp = [] for i in range(26): c = chr(ord('A') + i) t = (-tasks.count(c) ,c) if t[0] != 0: heappush(hp, t) lst = [] time = 0 while hp or lst: # print hp, lst if lst and time == lst[0][2]: count, c, _ = lst[0] lst = lst[1:] heappush(hp, (-count, c)) if not hp: pass else: count, c = heappop(hp) count = -count count -= 1 if count != 0: lst.append((count, c, time + n + 1)) time += 1 return time
4f027d
e2e4cc
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. There is a meeting for the representatives of each city. The meeting is in the capital city. There is a car in each city. You are given an integer seats that indicates the number of seats in each car. A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel. Return the minimum number of liters of fuel to reach the capital city.   Example 1: Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed. Example 2: Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed. Example 3: Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.   Constraints: 1 <= n <= 100000 roads.length == n - 1 roads[i].length == 2 0 <= ai, bi < n ai != bi roads represents a valid tree. 1 <= seats <= 100000
class Solution(object): def minimumFuelCost(self, roads, seats): """ :type roads: List[List[int]] :type seats: int :rtype: int """ g, f = defaultdict(list), [0] def d(n, p): t = 1 for o in g[n]: if o != p: q, r = d(o, n) f[0], t = f[0] + q, t + r return [(t - 1) / seats + 1, t] for r, s in roads: g[r].append(s) g[s].append(r) d(0, -1) return f[0]
e3d8e4
e2e4cc
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. There is a meeting for the representatives of each city. The meeting is in the capital city. There is a car in each city. You are given an integer seats that indicates the number of seats in each car. A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel. Return the minimum number of liters of fuel to reach the capital city.   Example 1: Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed. Example 2: Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed. Example 3: Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.   Constraints: 1 <= n <= 100000 roads.length == n - 1 roads[i].length == 2 0 <= ai, bi < n ai != bi roads represents a valid tree. 1 <= seats <= 100000
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: def dfs(u, fa): nonlocal graph, seats siz = 1 cost = 0 for v in graph[u]: if v != fa: siz_v, cost_v, vehicle_v = dfs(v, u) cost += cost_v cost += vehicle_v siz += siz_v vehicle = siz // seats if siz % seats: vehicle += 1 return siz, cost, vehicle n = len(roads) + 1 graph = [[] for i in range(n)] for u, v in roads: graph[u].append(v) graph[v].append(u) _, ans, _ = dfs(0, -1) return ans
51205b
a85404
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight. ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.   Example 1: Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 Output: 4 Explanation: The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). Example 2: Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. Example 3: Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6.   Constraints: 1 <= boxes.length <= 100000 1 <= portsCount, maxBoxes, maxWeight <= 100000 1 <= ports​​i <= portsCount 1 <= weightsi <= maxWeight
class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: n = len(boxes) if n == 1: return 2 dp = [100000000] * (n + 1) dp[0] = 0 g = [0] * (n + 1) g[1] = 1 for i in range(1, n): if boxes[i][0] == boxes[i - 1][0]: g[i + 1] = g[i] else: g[i + 1] = g[i] + 1 s = [0] * (n + 1) s[0] = 0 for i in range(n): s[i + 1] = s[i] + boxes[i][1] l = [0] * (n + 1) r = [0] * (n + 1) l[1] = 1 for i in range(1, n): if boxes[i][0] == boxes[i - 1][0]: l[i + 1] = l[i] else: l[i + 1] = i + 1 r[n] = n for i in range(n - 2, -1, -1): if boxes[i][0] == boxes[i + 1][0]: r[i + 1] = r[i + 2] else: r[i + 1] = i + 1 for i in range(1, n + 1): left = 0 right = i - 1 ans = -1 while left <= right: mid = (left + right) // 2 if s[i] - s[mid] <= maxWeight: ans = mid; right = mid - 1 else: left = mid + 1 ans = max(i - maxBoxes, ans) tmp_x = g[i] - g[ans] + 1 if ans != 0 and boxes[ans - 1][0] == boxes[ans][0]: tmp_x += 1 dp[i] = dp[ans] + tmp_x if ans != 0: tmp_y = r[ans] dp[i] = min(dp[i], dp[tmp_y] + g[i] - g[tmp_y] + 1) return dp[n]
a4d591
a85404
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight. ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.   Example 1: Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 Output: 4 Explanation: The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). Example 2: Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. Example 3: Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7 Output: 6 Explanation: The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6.   Constraints: 1 <= boxes.length <= 100000 1 <= portsCount, maxBoxes, maxWeight <= 100000 1 <= ports​​i <= portsCount 1 <= weightsi <= maxWeight
class Solution(object): def boxDelivering(self, A, portsCount, maxB, maxW): n = len(A) curP = curB = curW = j = 0 j = lastj = -1 res = [0] + [float('inf')] * n for i in xrange(n): while j + 1 < n and curB + 1 <= maxB and curW + A[j + 1][1] <= maxW: j += 1 curB += 1 curW += A[j][1] if j == 0 or A[j][0] != A[j - 1][0]: lastj = j curP += 1 res[j + 1] = min(res[j + 1], res[i] + curP + 1) # print i, j, curP res[j + 1] = min(res[j + 1], res[i] + curP + 1) res[lastj] = min(res[lastj], res[i] + curP) curB -= 1 curW -= A[i][1] if i == n - 1 or A[i][0] != A[i + 1][0]: curP -= 1 i += 1 # print res return res[-1]
94c87a
16a3e7
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485   Constraints: 1 <= classes.length <= 100000 classes[i].length == 2 1 <= passi <= totali <= 100000 1 <= extraStudents <= 100000
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: h = [] for x, y in classes: inc = (x + 1) / (y + 1) - x / y heapq.heappush(h, (-inc, x, y)) for i in range(extraStudents): ratio, x, y = heapq.heappop(h) x += 1 y += 1 inc = (x + 1) / (y + 1) - x / y heapq.heappush(h, (-inc, x, y)) ans = list(map(lambda l:l[1] / l[2], h)) return sum(ans) / len(ans)
e1a82d
16a3e7
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485   Constraints: 1 <= classes.length <= 100000 classes[i].length == 2 1 <= passi <= totali <= 100000 1 <= extraStudents <= 100000
class Solution(object): def com(self, x, y): return -(1.0 - float(x)/float(y))/(y+1) def maxAverageRatio(self, classes, extraStudents): """ :type classes: List[List[int]] :type extraStudents: int :rtype: float """ h = [] for p, t in classes: heappush(h, (self.com(p, t), p, t)) for i in range(extraStudents): _, p, t = heappop(h) heappush(h,(self.com(p+1,t+1),p+1,t+1)) ans = 0 for _, p, t in h: ans += float(p) / t return ans / len(classes)
803eee
4bb522
There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: quality = [10,20,5], wage = [70,50,30], k = 2 Output: 105.00000 Explanation: We pay 70 to 0th worker and 35 to 2nd worker. Example 2: Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3 Output: 30.66667 Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.   Constraints: n == quality.length == wage.length 1 <= k <= n <= 10000 1 <= quality[i], wage[i] <= 10000
from heapq import heapify, heappushpop class Solution: def mincostToHireWorkers(self, quality, wage, K): """ :type quality: List[int] :type wage: List[int] :type K: int :rtype: float """ wq = [ (w/q, q) for w,q in zip(wage, quality)] wq.sort() q = [-x[1] for x in wq[:K]] sumq = -sum(q) heapify(q) minp = sumq * (wq[K-1][0]) for i in range(K, len(wq)): sumq += wq[i][1] sumq += heappushpop(q, -wq[i][1]) minp = min(minp, sumq * wq[i][0]) return minp
710bc6
4bb522
There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: quality = [10,20,5], wage = [70,50,30], k = 2 Output: 105.00000 Explanation: We pay 70 to 0th worker and 35 to 2nd worker. Example 2: Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3 Output: 30.66667 Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.   Constraints: n == quality.length == wage.length 1 <= k <= n <= 10000 1 <= quality[i], wage[i] <= 10000
class Solution(object): def mincostToHireWorkers(self, quality, wage, K): """ :type quality: List[int] :type wage: List[int] :type K: int :rtype: float """ import heapq data = sorted(zip(quality, wage)) minheap = [] total_quality = 0 for i in range(K): q, w = data[i] total_quality += q heapq.heappush(minheap, (float(q) / w, i)) # (quality per wage, index) price = 1.0 / minheap[0][0] # wage per quality best = price * total_quality for i in range(K, len(data)): _, index = heapq.heappop(minheap) total_quality -= data[index][0] q, w = data[i] total_quality += q heapq.heappush(minheap, (float(q) / w, i)) now = 1.0 / minheap[0][0] * total_quality best = min(best, now) return best
8e87c6
98c5f8
Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.   Example 1: Input: balls = [1,1] Output: 1.00000 Explanation: Only 2 ways to divide the balls equally: - A ball of color 1 to box 1 and a ball of color 2 to box 2 - A ball of color 2 to box 1 and a ball of color 1 to box 2 In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1 Example 2: Input: balls = [2,1,1] Output: 0.66667 Explanation: We have the set of balls [1, 1, 2, 3] This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12): [1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1] After that, we add the first two balls to the first box and the second two balls to the second box. We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box. Probability is 8/12 = 0.66667 Example 3: Input: balls = [1,2,1,2] Output: 0.60000 Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box. Probability = 108 / 180 = 0.6   Constraints: 1 <= balls.length <= 8 1 <= balls[i] <= 6 sum(balls) is even.
class Solution(object): def comb(self, n, k): ans = 1 for i in range(k): ans *= (n - i) ans //= i + 1 return ans def getProbability(self, balls): """ :type balls: List[int] :rtype: float """ dp = [[[0 for _ in range(50)] for _ in range(10)] for _ in range(10)] n = len(balls) dp[0][0][0] = 1 for idx in range(n): curr = balls[idx] new_dp = [[[0 for _ in range(50)] for _ in range(10)] for _ in range(10)] for j in range(10): for k in range(10): for s in range(0, curr + 1): jp = j if s == 0 else j - 1 kp = k if s == curr else k - 1 if jp >= 0 and kp >= 0: for curr_cnt in range(50): prev_cnt = curr_cnt - s if prev_cnt >= 0: new_dp[j][k][curr_cnt] += dp[jp][kp][prev_cnt] * self.comb(curr, s) if new_dp[j][k][curr_cnt] and False: print((jp,kp,prev_cnt)) print((j,k,curr_cnt)) print(new_dp[j][k][curr_cnt]) dp = new_dp #print(dp) target = sum(balls) // 2 tot = 0 for j in range(10): for k in range(10): tot += dp[j][k][target] now = 0 for j in range(10): now += dp[j][j][target] return float(now) / float(tot)
0b6f2d
98c5f8
Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.   Example 1: Input: balls = [1,1] Output: 1.00000 Explanation: Only 2 ways to divide the balls equally: - A ball of color 1 to box 1 and a ball of color 2 to box 2 - A ball of color 2 to box 1 and a ball of color 1 to box 2 In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1 Example 2: Input: balls = [2,1,1] Output: 0.66667 Explanation: We have the set of balls [1, 1, 2, 3] This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12): [1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1] After that, we add the first two balls to the first box and the second two balls to the second box. We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box. Probability is 8/12 = 0.66667 Example 3: Input: balls = [1,2,1,2] Output: 0.60000 Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box. Probability = 108 / 180 = 0.6   Constraints: 1 <= balls.length <= 8 1 <= balls[i] <= 6 sum(balls) is even.
from math import factorial def ncr(n, r): if r > n: return 0 return factorial(n) / factorial(r) / factorial(n - r) class Solution: def getProbability(self, balls: List[int]) -> float: S = sum(balls) @lru_cache(None) def f(kd, cd, i): if i == len(balls): return int(kd == 0 and cd == 0) else: cnt = balls[i] r = 0 for c in range(balls[i] + 1): k = -1 if c == 0 else 1 if c == balls[i] else 0 cc = ncr(cnt, c) r += cc * f(kd + k, cd + c - cnt +c, i +1) return r return f(0, 0, 0) / ncr(S, S//2)
2622e3
ecee0b
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.   Example 1: Input: stones = [7,4,9] Output: [1,2] Explanation: We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. Example 2: Input: stones = [6,5,4,3,10] Output: [2,3] Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.   Constraints: 3 <= stones.length <= 10000 1 <= stones[i] <= 10^9 All the values of stones are unique.
class Solution: def numMovesStonesII(self, a: List[int]) -> List[int]: a = sorted(a) n = len(a) mx = a[-1] - a[0] - n - min(a[1] - a[0], a[-1] - a[-2]) + 2 mn = mx j = 0 for i in range(n): while a[i] - a[j] >= n: j += 1 print(i, j) mn = min(mn, n - (i - j + 1)) # print() if a[-2] != a[0] + n - 2 and a[1] != a[-1] - (n - 2): pass else: mn = min(mx, mn + 1) return [mn, mx]
186797
ecee0b
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.   Example 1: Input: stones = [7,4,9] Output: [1,2] Explanation: We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. Example 2: Input: stones = [6,5,4,3,10] Output: [2,3] Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.   Constraints: 3 <= stones.length <= 10000 1 <= stones[i] <= 10^9 All the values of stones are unique.
class Solution(object): def numMovesStonesII(self, stones): """ :type stones: List[int] :rtype: List[int] """ stones.sort() if stones[-1]==stones[0]+len(stones)-1: return [0,0] else: maxx=max(stones[-2]-stones[0],stones[-1]-stones[1])-len(stones)+2 n=len(stones) i,j=0,0 L=[] while(i<n): if j<n and stones[j]-stones[i]<len(stones): j+=1 else: L.append(j) i+=1 minn=float("inf") for i in xrange(n): if stones[L[i]-1]-stones[i]==len(stones)-2==L[i]-1-i: minn=min(minn,n-(L[i]-i)+1) else: minn=min(minn,n-(L[i]-i)) return [minn,maxx]
035d0c
7ff2be
You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns: -1 if word is not from words, or an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word). For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: "Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or "You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).   Example 1: Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. Example 2: Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: Since there are two words, you can guess both.   Constraints: 1 <= words.length <= 100 words[i].length == 6 words[i] consist of lowercase English letters. All the strings of wordlist are unique. secret exists in words. 10 <= allowedGuesses <= 30
# """ # This is Master's API interface. # You should not implement it, or speculate about its implementation # """ #class Master(object): # def guess(self, word): # """ # :type word: str # :rtype int # """ from collections import defaultdict class Solution(object): def findSecretWord(self, wordlist, master): while len(wordlist) > 1: match = {} for word in wordlist: match[word] = defaultdict(int) for word2 in wordlist: match[word][sum(1 for x, y in zip(word, word2) if x == y)] += 1 best = min(wordlist, key=lambda word: max(match[word][i] for i in range(7))) score = master.guess(best) wordlist = [word for word in wordlist if sum(1 for x, y in zip(word, best) if x == y) == score] master.guess(wordlist[0])
bf10f0
7ff2be
You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns: -1 if word is not from words, or an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word). For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: "Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or "You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).   Example 1: Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. Example 2: Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: Since there are two words, you can guess both.   Constraints: 1 <= words.length <= 100 words[i].length == 6 words[i] consist of lowercase English letters. All the strings of wordlist are unique. secret exists in words. 10 <= allowedGuesses <= 30
# """ # This is Master's API interface. # You should not implement it, or speculate about its implementation # """ #class Master: # def guess(self, word): # """ # :type word: str # :rtype int # """ class Solution: def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] :type master: Master :rtype: None """ check = lambda x,y: sum(int(i==j) for i,j in zip(x,y)) w=set(wordlist) while len(w)>0: temp=set() for i in w: match=master.guess(i) if match==6: return for j in w: if check(i,j)==match: temp.add(j) break w=temp
84e1f5
b2f93e
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.   Example 1: Input: answerKey = "TTFF", k = 2 Output: 4 Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". There are four consecutive 'T's. Example 2: Input: answerKey = "TFFT", k = 1 Output: 3 Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". In both cases, there are three consecutive 'F's. Example 3: Input: answerKey = "TTFTTFTT", k = 1 Output: 5 Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". In both cases, there are five consecutive 'T's.   Constraints: n == answerKey.length 1 <= n <= 5 * 10000 answerKey[i] is either 'T' or 'F' 1 <= k <= n
class Solution: def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: n = len(answerKey) left = k right = n def helper(mid): numf = 0 numt = 0 for answer in answerKey[:mid]: if answer == 'T': numt += 1 else: numf += 1 if numf <= k or numt <= k: return True for i in range(mid, n): if answerKey[i] == 'T': numt += 1 else: numf += 1 if answerKey[i - mid] == 'T': numt -= 1 else: numf -= 1 if numf <= k or numt <= k: return True return False while left < right: mid = (left + right + 1) >> 1 if helper(mid): left = mid else: right = mid - 1 return left
bad955
b2f93e
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.   Example 1: Input: answerKey = "TTFF", k = 2 Output: 4 Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". There are four consecutive 'T's. Example 2: Input: answerKey = "TFFT", k = 1 Output: 3 Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". In both cases, there are three consecutive 'F's. Example 3: Input: answerKey = "TTFTTFTT", k = 1 Output: 5 Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". In both cases, there are five consecutive 'T's.   Constraints: n == answerKey.length 1 <= n <= 5 * 10000 answerKey[i] is either 'T' or 'F' 1 <= k <= n
class Solution(object): def maxConsecutiveAnswers(self, s, k): count = {'T': 0, 'F': 0} i = 0 n = len(s) res = 0 for j in xrange(n): count[s[j]] += 1 while min(count.values()) > k: count[s[i]] -= 1 i += 1 res = max(res, j - i + 1) return res
daadb2
00fe44
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. Given an array houses, an m x n matrix cost and an integer target where: houses[i]: is the color of the house i, and 0 if the house is not painted yet. cost[i][j]: is the cost of paint the house i with the color j + 1. Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.   Example 1: Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 9 Explanation: Paint houses of this way [1,2,2,1,1] This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. Example 2: Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 11 Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2] This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. Cost of paint the first and last house (10 + 1) = 11. Example 3: Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3 Output: -1 Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.   Constraints: m == houses.length == cost.length n == cost[i].length 1 <= m <= 100 1 <= n <= 20 1 <= target <= m 0 <= houses[i] <= n 1 <= cost[i][j] <= 10000
from functools import lru_cache memo = lru_cache(None) class Solution: def minCost(self, houses, C, N, num_colors, target): # C is matrix , C[i][j] cost to paint ith house jth color INF = float('inf') @memo def dp(i, j, k): # prev color was j # min cost, currently k neighborhoods if i == N: return 0 if k == target else INF ans = INF for new_color in (range(num_colors) if houses[i] == 0 else [houses[i] - 1]): cost = C[i][new_color] bns = cost + dp(i+1, new_color, k + (new_color != j)) if bns<ans: ans=bns return ans ans = dp(0,-1,0) if ans == INF: return -1 for i,x in enumerate(houses): if x: ans -= C[i][x-1] return ans
41005c
00fe44
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. Given an array houses, an m x n matrix cost and an integer target where: houses[i]: is the color of the house i, and 0 if the house is not painted yet. cost[i][j]: is the cost of paint the house i with the color j + 1. Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.   Example 1: Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 9 Explanation: Paint houses of this way [1,2,2,1,1] This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. Example 2: Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 11 Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2] This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. Cost of paint the first and last house (10 + 1) = 11. Example 3: Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3 Output: -1 Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.   Constraints: m == houses.length == cost.length n == cost[i].length 1 <= m <= 100 1 <= n <= 20 1 <= target <= m 0 <= houses[i] <= n 1 <= cost[i][j] <= 10000
class Solution(object): def minCost(self, houses, cost, m, n, target): """ :type houses: List[int] :type cost: List[List[int]] :type m: int :type n: int :type target: int :rtype: int """ # paint first i houses ending on color j with total k neighborhoods f = [[[float('inf')]*(target+1) for _ in xrange(n+1)] for i in xrange(m+1)] f[0][0][0] = 0 for i, x in enumerate(houses): if x > 0: for j in xrange(n+1): # color j -> color x-1 d = 1 if j!=x else 0 for k in xrange(target+1-d): f[i+1][x][k+d] = min(f[i+1][x][k+d], f[i][j][k]) else: for j in xrange(n+1): for jj in xrange(1,n+1): d = 1 if j!=jj else 0 for k in xrange(target+1-d): f[i+1][jj][k+d] = min(f[i+1][jj][k+d], f[i][j][k]+cost[i][jj-1]) r = min(f[m][j][target] for j in xrange(n+1)) return r if r < float('inf') else -1
03b95a
04121a
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti. If isLefti == 0, then childi is the right child of parenti. Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.   Example 1: Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] Output: [50,20,80,15,17,19] Explanation: The root node is the node with value 50 since it has no parent. The resulting binary tree is shown in the diagram. Example 2: Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] Output: [1,2,null,null,3,4] Explanation: The root node is the node with value 1 since it has no parent. The resulting binary tree is shown in the diagram.   Constraints: 1 <= descriptions.length <= 10000 descriptions[i].length == 3 1 <= parenti, childi <= 100000 0 <= isLefti <= 1 The binary tree described by descriptions is valid.
# 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 createBinaryTree(self, A: List[List[int]]) -> Optional[TreeNode]: vals = set() for p, c, isl in A: vals.add(p) vals.add(c) parents = set(vals) adj = defaultdict(list) for p, c, isl in A: parents.discard(c) adj[p].append([c, isl]) def dfs(v): ans = TreeNode(v) for c, isl in adj[v]: if isl: ans.left = dfs(c) else: ans.right = dfs(c) return ans root, = parents return dfs(root)
e02164
04121a
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti. If isLefti == 0, then childi is the right child of parenti. Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.   Example 1: Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] Output: [50,20,80,15,17,19] Explanation: The root node is the node with value 50 since it has no parent. The resulting binary tree is shown in the diagram. Example 2: Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] Output: [1,2,null,null,3,4] Explanation: The root node is the node with value 1 since it has no parent. The resulting binary tree is shown in the diagram.   Constraints: 1 <= descriptions.length <= 10000 descriptions[i].length == 3 1 <= parenti, childi <= 100000 0 <= isLefti <= 1 The binary tree described by descriptions is valid.
# 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 createBinaryTree(self, descriptions): """ :type descriptions: List[List[int]] :rtype: Optional[TreeNode] """ nodes = {} def _getnode(i): if i not in nodes: nodes[i] = TreeNode(i) return nodes[i] a = set() b = set() for par, ch, left in descriptions: a.add(par) b.add(ch) u = _getnode(par) v = _getnode(ch) if left: u.left = v else: u.right = v return _getnode(min(a-b))
dab431
8d65f9
Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defined as a non-empty contiguous sequence of elements in an array.   Example 1: Input: nums = [2,3,3,2,2], k = 2, p = 2 Output: 11 Explanation: The elements at indices 0, 3, and 4 are divisible by p = 2. The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2]. Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once. The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 4, p = 1 Output: 10 Explanation: All element of nums are divisible by p = 1. Also, every subarray of nums will have at most 4 elements that are divisible by 1. Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.   Constraints: 1 <= nums.length <= 200 1 <= nums[i], p <= 200 1 <= k <= nums.length   Follow up: Can you solve this problem in O(n2) time complexity?
class Solution(object): def countDistinct(self, nums, k, p): """ :type nums: List[int] :type k: int :type p: int :rtype: int """ ans = set([]) n = len(nums) for l in range(n): cnt = 0 for r in range(l, n): if nums[r] % p == 0: cnt += 1 if cnt <= k: ans.add(','.join(map(str,nums[l:r+1]))) return len(ans)
9dc3dc
8d65f9
Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defined as a non-empty contiguous sequence of elements in an array.   Example 1: Input: nums = [2,3,3,2,2], k = 2, p = 2 Output: 11 Explanation: The elements at indices 0, 3, and 4 are divisible by p = 2. The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2]. Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once. The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 4, p = 1 Output: 10 Explanation: All element of nums are divisible by p = 1. Also, every subarray of nums will have at most 4 elements that are divisible by 1. Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.   Constraints: 1 <= nums.length <= 200 1 <= nums[i], p <= 200 1 <= k <= nums.length   Follow up: Can you solve this problem in O(n2) time complexity?
class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: presum = [0] for t in nums : presum.append(presum[-1] + (1 if t % p == 0 else 0)) print(presum) sett = set() for s in range(len(nums)) : for e in range(s+1, len(nums)+1) : vt = presum[e] - presum[s] if vt <= k : sett.add(tuple(nums[s:e])) return len(sett)
9d32cb
158bea
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell). The character '.' represents the floor which means a free cell to walk. The character '#' represents the wall which means an obstacle (impossible to walk there). There is only one box 'B' and one target cell 'T' in the grid. The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push. The player cannot walk through the box. Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.   Example 1: Input: grid = [["#","#","#","#","#","#"], ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#",".","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: 3 Explanation: We return only the number of times the box is pushed. Example 2: Input: grid = [["#","#","#","#","#","#"], ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#","#","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: -1 Example 3: Input: grid = [["#","#","#","#","#","#"], ["#","T",".",".","#","#"], ["#",".","#","B",".","#"], ["#",".",".",".",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: 5 Explanation: push the box down, left, left, up and up.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 grid contains only characters '.', '#', 'S', 'T', or 'B'. There is only one character 'S', 'B', and 'T' in the grid.
class Solution(object): def minPushBox(self, A): R, C = len(A), len(A[0]) for r, row in enumerate(A): for c, v in enumerate(row): if v == 'S': sr, sc = r, c if v == 'T': tr, tc = r, c if v == 'B': br, bc = r, c def neighbors(sr, sc, br, bc): for nr, nc, dr, dc in ((sr+1, sc, 1, 0), (sr, sc+1, 0,1), (sr-1, sc, -1, 0), (sr, sc-1, 0, -1)): if 0 <= nr < R and 0 <= nc < C and A[nr][nc] != '#': if (nr != br or nc != bc): yield 0, nr, nc, br, bc else: # trying to push box zr = br + dr zc = bc + dc if 0 <= zr < R and 0 <= zc < C and A[zr][zc] != '#': yield 1, nr, nc, zr, zc pq = [(0, sr, sc, br, bc)] dist = {(sr, sc, br, bc): 0} INF = float('inf') while pq: d, sr, sc, br, bc = heapq.heappop(pq) if br==tr and bc==tc: return d if dist.get((sr, sc, br, bc), INF) < d: continue for nei in neighbors(sr, sc, br, bc): node = nei[1:] w = nei[0] if d + w < dist.get(node, INF): dist[node] = d + w heapq.heappush(pq, (d+w, ) + node) return -1
ab99b7
158bea
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell). The character '.' represents the floor which means a free cell to walk. The character '#' represents the wall which means an obstacle (impossible to walk there). There is only one box 'B' and one target cell 'T' in the grid. The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push. The player cannot walk through the box. Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.   Example 1: Input: grid = [["#","#","#","#","#","#"], ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#",".","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: 3 Explanation: We return only the number of times the box is pushed. Example 2: Input: grid = [["#","#","#","#","#","#"], ["#","T","#","#","#","#"], ["#",".",".","B",".","#"], ["#","#","#","#",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: -1 Example 3: Input: grid = [["#","#","#","#","#","#"], ["#","T",".",".","#","#"], ["#",".","#","B",".","#"], ["#",".",".",".",".","#"], ["#",".",".",".","S","#"], ["#","#","#","#","#","#"]] Output: 5 Explanation: push the box down, left, left, up and up.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 grid contains only characters '.', '#', 'S', 'T', or 'B'. There is only one character 'S', 'B', and 'T' in the grid.
class Solution: def minPushBox(self, grid: List[List[str]]) -> int: n, m = len(grid), len(grid[0]) for i in range(n): for j in range(m): if grid[i][j] == 'T': t = (i, j) elif grid[i][j] == 'S': s = (i, j) elif grid[i][j] == 'B': b = (i, j) dirs = [[1,0],[-1,0],[0,1],[0,-1]] q = [tuple(s + b)] seen = set(q) steps = 0 while q: nq = [] for si, sj, bi, bj in q: if t == (bi, bj): return steps for di, dj in dirs: nsi, nsj = si+di, sj+dj if nsi==bi and nsj==bj: nbi, nbj = bi+di, bj+dj ds = 1 else: nbi, nbj = bi, bj ds = 0 if not (0 <= nsi < n and 0 <= nsj < m): continue if not (0 <= nbi < n and 0 <= nbj < m): continue if grid[nsi][nsj] == '#' or grid[nbi][nbj] == '#': continue nsb = (nsi, nsj, nbi, nbj) if nsb in seen: continue seen.add(nsb) if ds == 0: q.append(nsb) else: nq.append(nsb) q = nq steps += 1 return -1
a11c6b
319633
Given an integer n represented as a string, return the smallest good base of n. We call k >= 2 a good base of n, if all digits of n base k are 1's.   Example 1: Input: n = "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: n = "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: n = "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.   Constraints: n is an integer in the range [3, 10^18]. n does not contain any leading zeros.
class Solution(object): def smallestGoodBase(self, n): """ :type n: str :rtype: str """ n = int(n) for i in xrange(64, 0, -1): ok, l, r = False, 2, n; while l <= r and ok == False: val, mid = 0, (l+r) / 2 for j in xrange(i): val = val * mid + 1 if val == n: ok = True elif val > n: r = mid-1 else: l = mid+1 if ok: return str((l+r)>>1)
61891a
f28207
You are given a string s, an integer k, a letter letter, and an integer repetition. Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.   Example 1: Input: s = "leet", k = 3, letter = "e", repetition = 1 Output: "eet" Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time: - "lee" (from "leet") - "let" (from "leet") - "let" (from "leet") - "eet" (from "leet") The lexicographically smallest subsequence among them is "eet". Example 2: Input: s = "leetcode", k = 4, letter = "e", repetition = 2 Output: "ecde" Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times. Example 3: Input: s = "bb", k = 2, letter = "b", repetition = 2 Output: "bb" Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.   Constraints: 1 <= repetition <= k <= s.length <= 5 * 10000 s consists of lowercase English letters. letter is a lowercase English letter, and appears in s at least repetition times.
class Solution: def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str: position = [[] for _ in range(26)] idx = [0] * 26 num = [s.count(letter)] for i, c in enumerate(s): if c == letter: num.append(num[-1] - 1) else: num.append(num[-1]) l = ord(c) - 97 position[l].append(i) length = [len(p) for p in position] choice = ord(letter) - 97 cnt = 0 n = len(s) ans = [] for i in range(k): for j in range(26): if idx[j] < length[j] and num[position[j][idx[j]]] >= repetition - cnt and n - position[j][idx[j]] >= k - len(ans) >= repetition - cnt + (0 if j == choice else 1): ans.append(chr(97 + j)) if j == choice: cnt += 1 break now = position[j][idx[j]] for j in range(26): while idx[j] < length[j] and position[j][idx[j]] <= now: idx[j] += 1 return ''.join(ans)
053f58
f28207
You are given a string s, an integer k, a letter letter, and an integer repetition. Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.   Example 1: Input: s = "leet", k = 3, letter = "e", repetition = 1 Output: "eet" Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time: - "lee" (from "leet") - "let" (from "leet") - "let" (from "leet") - "eet" (from "leet") The lexicographically smallest subsequence among them is "eet". Example 2: Input: s = "leetcode", k = 4, letter = "e", repetition = 2 Output: "ecde" Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times. Example 3: Input: s = "bb", k = 2, letter = "b", repetition = 2 Output: "bb" Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.   Constraints: 1 <= repetition <= k <= s.length <= 5 * 10000 s consists of lowercase English letters. letter is a lowercase English letter, and appears in s at least repetition times.
class Solution(object): def smallestSubsequence(self, s, k, letter, repetition): """ :type s: str :type k: int :type letter: str :type repetition: int :rtype: str """ a = [ord(ch) - ord('a') for ch in s] r = [] target = ord(letter) - ord('a') n = len(a) lim = [] m = max(a) + 1 loc = [[] for _ in xrange(m)] for i in xrange(n-1, -1, -1): if a[i] == target and len(lim) < repetition: lim.append(i) loc[a[i]].append(i) prev = -1 frq = [0] * 26 while k > 0: if k == len(lim): r += [target]*k break ub = min(lim[-1] if lim else n-1, n-k) for v, l in enumerate(loc): while l and l[-1] <= prev: l.pop() if l and l[-1] <= ub: prev = l[-1] r.append(v) k -= 1 if v == target and lim: lim.pop() break return ''.join(chr(v+ord('a')) for v in r)
04c349
fca008
You are given two strings s and t. You are allowed to remove any number of characters from the string t. The score of the string is 0 if no characters are removed from the string t, otherwise: Let left be the minimum index among all removed characters. Let right be the maximum index among all removed characters. Then the score of the string is right - left + 1. Return the minimum possible score to make t a subsequence of s. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).   Example 1: Input: s = "abacaba", t = "bzaa" Output: 1 Explanation: In this example, we remove the character "z" at index 1 (0-indexed). The string t becomes "baa" which is a subsequence of the string "abacaba" and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. Example 2: Input: s = "cde", t = "xyz" Output: 3 Explanation: In this example, we remove characters "x", "y" and "z" at indices 0, 1, and 2 (0-indexed). The string t becomes "" which is a subsequence of the string "cde" and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve.   Constraints: 1 <= s.length, t.length <= 100000 s and t consist of only lowercase English letters.
class Solution(object): def minimumScore(self, s, t): """ :type s: str :type t: str :rtype: int """ i, j, l, r, k, m = 0, 0, [0] * len(t), [0] * len(t), len(s) - 1, len(t) - 1 while i < len(s) and j < len(t): l[j], j, i = i if s[i] == t[j] else l[j], j + 1 if s[i] == t[j] else j, i + 1 if j == len(t): return 0 while k >= 0 and m >= 0: r[m], m, k = k if s[k] == t[m] else r[m], m - 1 if s[k] == t[m] else m, k - 1 u = min(len(t) - j, m + 1) for i in range(j): while m < len(t) and r[m] <= l[i]: m += 1 if m == len(t): break u = min(u, m - 1 - i) return u
d48407
fca008
You are given two strings s and t. You are allowed to remove any number of characters from the string t. The score of the string is 0 if no characters are removed from the string t, otherwise: Let left be the minimum index among all removed characters. Let right be the maximum index among all removed characters. Then the score of the string is right - left + 1. Return the minimum possible score to make t a subsequence of s. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).   Example 1: Input: s = "abacaba", t = "bzaa" Output: 1 Explanation: In this example, we remove the character "z" at index 1 (0-indexed). The string t becomes "baa" which is a subsequence of the string "abacaba" and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. Example 2: Input: s = "cde", t = "xyz" Output: 3 Explanation: In this example, we remove characters "x", "y" and "z" at indices 0, 1, and 2 (0-indexed). The string t becomes "" which is a subsequence of the string "cde" and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve.   Constraints: 1 <= s.length, t.length <= 100000 s and t consist of only lowercase English letters.
class Solution: def minimumScore(self, s: str, t: str) -> int: n, m = len(s), len(t) s = " " + s t = " " + t pre = [0] * (n + 2) suf = [0] * (n + 2) for i in range(1, n + 1): pre[i] = pre[i - 1] if pre[i] < m and s[i] == t[pre[i] + 1]: pre[i] += 1 suf[n + 1] = m + 1 for i in range(n, 0, -1): suf[i] = suf[i + 1] if suf[i] > 1 and s[i] == t[suf[i] - 1]: suf[i] -= 1 res = m for i in range(n + 1): res = min(res, suf[i + 1] - pre[i] - 1) return max(res, 0)
6365ee
86838b
You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once). Return the bitwise XOR of all integers in nums3.   Example 1: Input: nums1 = [2,1,3], nums2 = [10,2,5,0] Output: 13 Explanation: A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3]. The bitwise XOR of all these numbers is 13, so we return 13. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 0 Explanation: All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0], and nums1[1] ^ nums2[1]. Thus, one possible nums3 array is [2,5,1,6]. 2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.   Constraints: 1 <= nums1.length, nums2.length <= 100000 0 <= nums1[i], nums2[j] <= 10^9
class Solution: def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: a = 0 if len(nums2)%2: for i in nums1: a ^= i if len(nums1)%2: for i in nums2: a ^= i return a
02116c
86838b
You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once). Return the bitwise XOR of all integers in nums3.   Example 1: Input: nums1 = [2,1,3], nums2 = [10,2,5,0] Output: 13 Explanation: A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3]. The bitwise XOR of all these numbers is 13, so we return 13. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 0 Explanation: All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0], and nums1[1] ^ nums2[1]. Thus, one possible nums3 array is [2,5,1,6]. 2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.   Constraints: 1 <= nums1.length, nums2.length <= 100000 0 <= nums1[i], nums2[j] <= 10^9
class Solution(object): def xorAllNums(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ ans = 0 if len(nums1)%2==1: for num in nums2: ans = ans ^ num if len(nums2)%2==1: for num in nums1: ans = ans ^ num return ans
3b44be
070c32
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.   Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Example 2: Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa" Output: "aaaaaaaa"   Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of lowercase English letters.
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: def compute_lcs(s, t): m, n = len(s), len(t) dp = [[""] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s[i - 1] != t[j - 1]: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], key=len) else: dp[i][j] = dp[i - 1][j - 1] + s[i - 1] return dp[-1][-1] # print(compute_lcs(str1, str2)) cs = compute_lcs(str1, str2) ans = [] i, j = 0, 0 m, n = len(str1), len(str2) for ch in cs: while i < m and str1[i] != ch: ans.append(str1[i]) i += 1 while j < n and str2[j] != ch: ans.append(str2[j]) j += 1 ans.append(ch) i += 1 j += 1 return ''.join(ans) + str1[i:] + str2[j:]
3360a9
070c32
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.   Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Example 2: Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa" Output: "aaaaaaaa"   Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of lowercase English letters.
class Solution(object): def shortestCommonSupersequence(self, str1, str2): """ :type str1: str :type str2: str :rtype: str """ # f(i,j) := shortest length substring containing str1[:i], str2[:j] n, m = len(str1), len(str2) f = [[i+j for i in xrange(m+1)] for j in xrange(n+1)] for i in xrange(n): for j in xrange(m): f[i+1][j+1] = 1 + (f[i][j] if str1[i]==str2[j] else min(f[i+1][j], f[i][j+1])) i, j = n, m r = [] while i and j: i -= 1 j -= 1 if str1[i] == str2[j]: r.append(str1[i]) continue if f[i][j+1] < f[i+1][j]: r.append(str1[i]) j += 1 else: r.append(str2[j]) i += 1 return str1[:i] + str2[:j] + ''.join(reversed(r))
c8cd3d
b25460
Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.   Example 1: Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. Example 2: Input: arr1 = [0], arr2 = [0] Output: [0] Example 3: Input: arr1 = [0], arr2 = [1] Output: [1]   Constraints: 1 <= arr1.length, arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros
class Solution: def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: x = 0 for i in arr1: x *= -2 x += i y = 0 for i in arr2: y *= -2 y += i z = x + y r = [] t = 1 b = -2 k = 2 while z != 0: m = (z * t) % k r.append(m) z = z - m * t z = z // k t = t * (b // k) if len(r) == 0: r.append(0) return r[::-1]
5f70d0
b25460
Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.   Example 1: Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. Example 2: Input: arr1 = [0], arr2 = [0] Output: [0] Example 3: Input: arr1 = [0], arr2 = [1] Output: [1]   Constraints: 1 <= arr1.length, arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros
class Solution(object): def addNegabinary(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ count = [0] * 2000 n1 = len(arr1) n2 = len(arr2) for i, x in enumerate(arr1): actual = n1 - i - 1 if x: count[actual] += 1 for i, x in enumerate(arr2): actual = n2 - i - 1 if x: count[actual] += 1 for i in range(1500): while count[i] > 1: if count[i + 1]: count[i] -= 2 count[i + 1] -= 1 else: count[i] -= 2 count[i + 1] += 1 count[i + 2] += 1 count.reverse() if 1 not in count: return [0] return count[count.index(1):]
0cf41f
08cde9
You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally.   Example 1: Input: nums = [1,1,2] Output: false Explanation: Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. Example 2: Input: nums = [0,1] Output: true Example 3: Input: nums = [1,2,3] Output: true   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < 216
class Solution(object): def xorGame(self, nums): n = 0 for num in nums: n = n^num if n==0: return True return len(nums)%2==0 """ :type nums: List[int] :rtype: bool """
b96444
08cde9
You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally.   Example 1: Input: nums = [1,1,2] Output: false Explanation: Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. Example 2: Input: nums = [0,1] Output: true Example 3: Input: nums = [1,2,3] Output: true   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < 216
class Solution: def xorGame(self, nums): """ :type nums: List[int] :rtype: bool """ a = 0 for i in nums: a=a^i if a==0: return True return len(nums)%2!=1 # if len(nums)%2 and a in nums: # return False # return True s=Solution() print(s.xorGame([1,1,2])) print(s.xorGame([1,2,3]))
3764a5
fff3d0
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). You are given a string array sentences and an integer array times both of length n where sentences[i] is a previously typed sentence and times[i] is the corresponding number of times the sentence was typed. For each input character except '#', return the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed. Here are the specific rules: The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first). If less than 3 hot sentences exist, return as many as you can. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list. Implement the AutocompleteSystem class: AutocompleteSystem(String[] sentences, int[] times) Initializes the object with the sentences and times arrays. List<String> input(char c) This indicates that the user typed the character c. Returns an empty array [] if c == '#' and stores the inputted sentence in the system. Returns the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than 3 matches, return them all. Example 1: Input ["AutocompleteSystem", "input", "input", "input", "input"] [[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]] Output [null, ["i love you", "island", "i love leetcode"], ["i love you", "i love leetcode"], [], []] Explanation AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]); obj.input("i"); // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored. obj.input(" "); // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ". obj.input("a"); // return []. There are no sentences that have prefix "i a". obj.input("#"); // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search. Constraints: n == sentences.length n == times.length 1 <= n <= 100 1 <= sentences[i].length <= 100 1 <= times[i] <= 50 c is a lowercase English letter, a hash '#', or space ' '. Each tested sentence will be a sequence of characters c that end with the character '#'. Each tested sentence will have a length in the range [1, 200]. The words in each input sentence are separated by single spaces. At most 5000 calls will be made to input.
from collections import defaultdict class AutocompleteSystem(object): def __init__(self, sentences, times): """ :type sentences: List[str] :type times: List[int] """ self.history = defaultdict(lambda: 0) for i in xrange(len(sentences)): self.history[sentences[i]] += times[i] self.cur = "" self.last_result = list(self.history.iterkeys()) self.store = {} def input(self, c): """ :type c: str :rtype: List[str] """ if c == '#': self.history[self.cur] += 1 self.cur = "" self.last_result = list(self.history.iterkeys()) return [] else: self.cur += c answer = [] next_result = [] for sentence in self.last_result: if sentence.startswith(self.cur): next_result.append(sentence) time = self.history[sentence] answer.append((-time, sentence)) self.last_result = next_result answer.sort() answer = answer[:3] answer = map(lambda x: x[1], answer) return answer # s = AutocompleteSystem(["i love you", "island", "ironman", "i love leetcode"], [5, 3, 2, 2]) # print s.input('i') # print s.input(' ') # print s.input('#') # print s.input('i')
c7fa00
fff3d0
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). You are given a string array sentences and an integer array times both of length n where sentences[i] is a previously typed sentence and times[i] is the corresponding number of times the sentence was typed. For each input character except '#', return the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed. Here are the specific rules: The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first). If less than 3 hot sentences exist, return as many as you can. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list. Implement the AutocompleteSystem class: AutocompleteSystem(String[] sentences, int[] times) Initializes the object with the sentences and times arrays. List<String> input(char c) This indicates that the user typed the character c. Returns an empty array [] if c == '#' and stores the inputted sentence in the system. Returns the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than 3 matches, return them all. Example 1: Input ["AutocompleteSystem", "input", "input", "input", "input"] [[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]] Output [null, ["i love you", "island", "i love leetcode"], ["i love you", "i love leetcode"], [], []] Explanation AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]); obj.input("i"); // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored. obj.input(" "); // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ". obj.input("a"); // return []. There are no sentences that have prefix "i a". obj.input("#"); // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search. Constraints: n == sentences.length n == times.length 1 <= n <= 100 1 <= sentences[i].length <= 100 1 <= times[i] <= 50 c is a lowercase English letter, a hash '#', or space ' '. Each tested sentence will be a sequence of characters c that end with the character '#'. Each tested sentence will have a length in the range [1, 200]. The words in each input sentence are separated by single spaces. At most 5000 calls will be made to input.
class AutocompleteSystem: def __init__(self, sentences, times): """ :type sentences: List[str] :type times: List[int] """ self.heap = {} self.cur = "" n = len(sentences) for i in range(0, n): if sentences[i] not in self.heap: self.heap[sentences[i]] = times[i] else: self.heap[sentences[i]] += times[i] self.sortedlist = [] for key, value in self.heap.items(): temp = [key, value] self.sortedlist.append(temp) self.sortedlist = sorted(self.sortedlist, key=self.cmp_to_key(self.compare)) def input(self, c): """ :type c: str :rtype: List[str] """ if c == '#': if self.cur not in self.heap: self.heap[self.cur] = 1 else: self.heap[self.cur] += 1 self.cur = "" self.sortedlist = [] for key, value in self.heap.items(): temp = [key, value] self.sortedlist.append(temp) self.sortedlist = sorted(self.sortedlist, key=self.cmp_to_key(self.compare)) return [] self.cur += c res = [] for x in self.sortedlist: if x[0].startswith(self.cur): res.append(x) self.sortedlist = res if len(res)>=3: return list(map(lambda x: x[0], res[0:3])) return list(map(lambda x: x[0], res)) def cmp_to_key(self, mycmp): 'Convert a cmp= function into a key= function' class K(object): def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K def compare(self, a, b): if a[1] == b[1]: if a[0] == b[0]: return 0 elif a[0] < b[0]: return -1 else: return 1 elif a[1] < b[1]: return 1 else: return -1
584e64
686ac4
There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. Additionally, you are given a 2D integer array trips, where trips[i] = [starti, endi] indicates that you start the ith trip from the node starti and travel to the node endi by any path you like. Before performing your first trip, you can choose some non-adjacent nodes and halve the prices. Return the minimum total price sum to perform all the given trips.   Example 1: Input: n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] Output: 23 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1st trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2nd trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3rd trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. Example 2: Input: n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] Output: 1 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1st trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve.   Constraints: 1 <= n <= 50 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n price[i] is an even integer. 1 <= price[i] <= 1000 1 <= trips.length <= 100 0 <= starti, endi <= n - 1
class Solution: def minimumTotalPrice(self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]]) -> int: path = [[] for _ in range(n)] for u, v in edges: path[u].append(v) path[v].append(u) parent = [-1] * n depth = [0] * n stack = [(-1, 0)] tree = [[] for _ in range(n)] while stack: p, u = stack.pop() for v in path[u]: if v != p: tree[u].append(v) parent[v] = u stack.append((u, v)) depth[v] = depth[u] + 1 weight = [0] * n for u, v in trips: if depth[u] > depth[v]: u, v = v, u while depth[u] != depth[v]: weight[v] += 1 v = parent[v] while u != v: weight[u] += 1 weight[v] += 1 u = parent[u] v = parent[v] weight[u] += 1 def dfs(u): tmp0, tmp1 = 0, weight[u] * price[u] // 2 for v in tree[u]: x0, x1 = dfs(v) tmp0 += max(x0, x1) tmp1 += x0 return tmp0, tmp1 res0, res1 = dfs(0) tot = sum(x * y for x, y in zip(price, weight)) return tot - max(res0, res1)
8152bd
686ac4
There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. Additionally, you are given a 2D integer array trips, where trips[i] = [starti, endi] indicates that you start the ith trip from the node starti and travel to the node endi by any path you like. Before performing your first trip, you can choose some non-adjacent nodes and halve the prices. Return the minimum total price sum to perform all the given trips.   Example 1: Input: n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] Output: 23 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1st trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2nd trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3rd trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. Example 2: Input: n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] Output: 1 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1st trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve.   Constraints: 1 <= n <= 50 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n price[i] is an even integer. 1 <= price[i] <= 1000 1 <= trips.length <= 100 0 <= starti, endi <= n - 1
class Solution(object): def minimumTotalPrice(self, n, edges, price, trips): """ :type n: int :type edges: List[List[int]] :type price: List[int] :type trips: List[List[int]] :rtype: int """ g, v = [[] for _ in range(n)], [0] * n def a(s, p, d): if s == d: v[s] += price[s] return True for o in g[s]: if o != p and a(o, s, d): v[s] += price[s] return True return False def d(s, p): h, w = v[s] / 2, v[s] for o in g[s]: if o != p: a = d(o, s) h, w = h + a[1], w + min(a) return [h, w] for e, f in edges: g[e].append(f) g[f].append(e) for t, u in trips: a(t, -1, u) a, p, q = d(0, -1), v[0] / 2, v[0] for i in range(1, n): q, p = min(q, p) + v[i], q + v[i] / 2 return min(a)
11d1bc
bb4f69
Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.   Example 1: Input: n = 2, s1 = "aa", s2 = "da", evil = "b" Output: 51 Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".  Example 2: Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet" Output: 0 Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string. Example 3: Input: n = 2, s1 = "gx", s2 = "gz", evil = "x" Output: 2   Constraints: s1.length == n s2.length == n s1 <= s2 1 <= n <= 500 1 <= evil.length <= 50 All strings consist of lowercase English letters.
from collections import defaultdict from string import ascii_lowercase class Solution(object): def findGoodStrings(self, n, s1, s2, evil): """ :type n: int :type s1: str :type s2: str :type evil: str :rtype: int """ kmp = [-1]*(len(evil)+1) j = 0 for i in xrange(1, len(evil)): if evil[i] == evil[j]: kmp[i] = kmp[j] else: kmp[i] = j while j >= 0 and evil[i] != evil[j]: j = kmp[j] j += 1 kmp[-1] = j def match(lpm, c): if lpm == len(evil): lpm = kmp[lpm] while lpm >= 0 and evil[lpm] != c: lpm = kmp[lpm] return lpm + 1 M = 10**9 + 7 def ways_below(s): n = len(s) # num chars # whether equal to s # lpm w = defaultdict(int) w[(True, 0)] = 1 for i in xrange(n): ww = defaultdict(int) for (m, lpm), v in w.iteritems(): v %= M for c in ascii_lowercase: if m and c > s[i]: break mm = m and c == s[i] lpmm = match(lpm, c) if lpmm == len(evil): continue ww[(mm, lpmm)] += v w = ww return sum(v for _, v in w.iteritems()) % M r = ways_below(s2) - ways_below(s1) if evil not in s1: r += 1 return r % M
4908c9
bb4f69
Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.   Example 1: Input: n = 2, s1 = "aa", s2 = "da", evil = "b" Output: 51 Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".  Example 2: Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet" Output: 0 Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string. Example 3: Input: n = 2, s1 = "gx", s2 = "gz", evil = "x" Output: 2   Constraints: s1.length == n s2.length == n s1 <= s2 1 <= n <= 500 1 <= evil.length <= 50 All strings consist of lowercase English letters.
import string from functools import lru_cache MOD = 10**9 + 7 class Solution: @lru_cache(maxsize=None) def dp(self, i, oklow, okup, j): if j == len(self.evil): return 0 if i == self.n: return 1 ans = 0 for c in string.ascii_lowercase: if not oklow and ord(c) < ord(self.slow[i]): continue if not okup and ord(c) > ord(self.sup[i]): continue noklow = oklow or ord(c) > ord(self.slow[i]) nokup = okup or ord(c) < ord(self.sup[i]) nj = self.findfail(j, c) ans += self.dp(i+1, noklow, nokup, nj) ans %= MOD return ans % MOD @lru_cache(maxsize=None) def findfail(self, j, c): s = self.evil[:j] + c for i in range(j+1, -1, -1): k = j+1 - i if s[k:] == self.evil[:i]: return i assert False def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int: self.n = n self.slow = s1 self.sup = s2 self.fails = {} self.evil = evil return self.dp(0, False, False, 0)
f10ee0
447aa9
The diameter of a tree is the number of edges in the longest path in that tree. There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree. Return the diameter of the tree. Example 1: Input: edges = [[0,1],[0,2]] Output: 2 Explanation: The longest path of the tree is the path 1 - 0 - 2. Example 2: Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]] Output: 4 Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5. Constraints: n == edges.length + 1 1 <= n <= 10000 0 <= ai, bi < n ai != bi
class Solution(object): def treeDiameter(self, edges): """ :type edges: List[List[int]] :rtype: int """ nei = collections.defaultdict(set) for i, j in edges: nei[i].add(j) nei[j].add(i) memo = {} def dfs(i,j): if (i,j) in memo: return memo[i,j] longest = 0 for k in nei[j]: if k == i: continue longest = max(longest, dfs(j, k)) memo[i,j] = longest + 1 return memo[i,j] for i,j in edges: dfs(i,j) dfs(j,i) return max(memo[i,j] + memo[j,i] - 1 for i,j in edges)
fbbc26
447aa9
The diameter of a tree is the number of edges in the longest path in that tree. There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree. Return the diameter of the tree. Example 1: Input: edges = [[0,1],[0,2]] Output: 2 Explanation: The longest path of the tree is the path 1 - 0 - 2. Example 2: Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]] Output: 4 Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5. Constraints: n == edges.length + 1 1 <= n <= 10000 0 <= ai, bi < n ai != bi
from collections import defaultdict class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: edgesMap = defaultdict(list) for x, y in edges: edgesMap[x].append(y) edgesMap[y].append(x) visited = set() def visit(cur): visited.add(cur) diameter = 0 arr = [] for neighbor in edgesMap[cur]: if neighbor not in visited: d, l = visit(neighbor) diameter = max(diameter, d) arr.append(l) arr.sort() return (max(diameter, 2 + arr[-1] + arr[-2] if len(arr) >= 2 else (1 + arr[-1] if arr else 0)), 1 + max(arr) if arr else 0) return 0 if not edges else visit(edges[0][0])[0]
d6216c
3e1bf1
Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.   Example 1: Input: nums = [1,2,1,2,6,7,5,1], k = 2 Output: [0,3,5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. Example 2: Input: nums = [1,2,1,2,1,2,1,2,1], k = 2 Output: [0,2,4]   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] < 216 1 <= k <= floor(nums.length / 3)
class Solution(object): def maxSumOfThreeSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ N = len(nums) partialSums = [sum(nums[:k])] for i in xrange(1, N-k+1): lastSum = partialSums[-1] nextSum = lastSum - nums[i-1] + nums[i+k-1] partialSums.append(nextSum) maxbegin = [(partialSums[0], 0)] for (i, val) in enumerate(partialSums): if i == 0: continue prevmax, prevind = maxbegin[-1] if val > prevmax: maxbegin.append((val, i)) else: maxbegin.append((prevmax, prevind)) maxend = [(partialSums[-1], len(partialSums)-1)] for i in xrange(len(partialSums)-2, -1, -1): val = partialSums[i] prevmax, prevind = maxend[-1] if val >= prevmax: maxend.append((val, i)) else: maxend.append((prevmax, prevind)) maxend = list(reversed(maxend)) bestvalsofar = -999999999 bestpos = [] for i in xrange(k, len(partialSums)-k): cursum = partialSums[i] + maxbegin[i-k][0] + maxend[i+k][0] if cursum > bestvalsofar: bestvalsofar = cursum bestpos = [maxbegin[i-k][1], i, maxend[i+k][1]] return bestpos
8420fb
3e1bf1
Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.   Example 1: Input: nums = [1,2,1,2,6,7,5,1], k = 2 Output: [0,3,5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. Example 2: Input: nums = [1,2,1,2,1,2,1,2,1], k = 2 Output: [0,2,4]   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] < 216 1 <= k <= floor(nums.length / 3)
class Solution: def maxSumOfThreeSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ ksums = [0 for i in range(len(nums))] ksums[k-1] = (sum(nums[:k]), 0) for i in range(k, len(nums)): ksums[i] = (nums[i] + ksums[i-1][0] - nums[i-k], k - 1 - i) dp1 = [0 for i in range(len(nums))] dp2 = [0 for i in range(len(nums))] dp3 = [0 for i in range(len(nums))] dp1[k-1] = ksums[k-1] for i in range(k, len(nums)): dp1[i] = max(dp1[i-1], ksums[i]) dp2[2*k-1] = (ksums[k-1][0] + ksums[2*k-1][0], 0, -k) for i in range(2*k, len(nums)): pos = dp1[i - k] new_pos = (ksums[i][0] + pos[0], pos[1], k - 1 - i) dp2[i] = max(dp2[i-1], new_pos) dp3[3*k-1] = (ksums[k-1][0] + ksums[2*k-1][0] + ksums[3*k-1][0], 0, -k, -2*k) for i in range(3*k, len(nums)): pos = dp2[i - k] new_pos = (ksums[i][0] + pos[0], pos[1], pos[2], k - 1 - i) dp3[i] = max(dp3[i-1], new_pos) return [-dp3[-1][1], -dp3[-1][2], -dp3[-1][3]]
e018af
15cf4e
Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.   Example 1: Input: nums1 = [2,5], nums2 = [3,4], k = 2 Output: 8 Explanation: The 2 smallest products are: - nums1[0] * nums2[0] = 2 * 3 = 6 - nums1[0] * nums2[1] = 2 * 4 = 8 The 2nd smallest product is 8. Example 2: Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6 Output: 0 Explanation: The 6 smallest products are: - nums1[0] * nums2[1] = (-4) * 4 = -16 - nums1[0] * nums2[0] = (-4) * 2 = -8 - nums1[1] * nums2[1] = (-2) * 4 = -8 - nums1[1] * nums2[0] = (-2) * 2 = -4 - nums1[2] * nums2[0] = 0 * 2 = 0 - nums1[2] * nums2[1] = 0 * 4 = 0 The 6th smallest product is 0. Example 3: Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3 Output: -6 Explanation: The 3 smallest products are: - nums1[0] * nums2[4] = (-2) * 5 = -10 - nums1[0] * nums2[3] = (-2) * 4 = -8 - nums1[4] * nums2[0] = 2 * (-3) = -6 The 3rd smallest product is -6.   Constraints: 1 <= nums1.length, nums2.length <= 5 * 10000 -100000 <= nums1[i], nums2[j] <= 100000 1 <= k <= nums1.length * nums2.length nums1 and nums2 are sorted.
def count_lte(a, b, k, allow_eq): if not a or not b: return 0 j = len(b) - 1 res = 0 for i, x in enumerate(a): while j >= 0 and ((allow_eq and x * b[j] > k) or (not allow_eq and x * b[j] >= k)): j -= 1 if j < 0: break res += j + 1 return res class Solution: def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int: negs1 = [-x for x in nums1 if x < 0] negs1.sort() pos1 = [x for x in nums1 if x >= 0] negs2 = [-x for x in nums2 if x < 0] negs2.sort() pos2 = [x for x in nums2 if x >= 0] lo = int(-1e11) hi = int(1e11) while lo + 1 < hi: mid = (lo + hi) // 2 lte = 0 if mid >= 0: lte += len(negs1) * len(pos2) + len(pos1) * len(negs2) lte += count_lte(negs1, negs2, mid, True) lte += count_lte(pos1, pos2, mid, True) else: lte += len(negs1) * len(pos2) - count_lte(negs1, pos2, -mid, False) lte += len(negs2) * len(pos1) - count_lte(negs2, pos1, -mid, False) # print("There are", lte, "products under", mid) if lte >= k: hi = mid else: lo = mid return hi
5bcd74
15cf4e
Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.   Example 1: Input: nums1 = [2,5], nums2 = [3,4], k = 2 Output: 8 Explanation: The 2 smallest products are: - nums1[0] * nums2[0] = 2 * 3 = 6 - nums1[0] * nums2[1] = 2 * 4 = 8 The 2nd smallest product is 8. Example 2: Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6 Output: 0 Explanation: The 6 smallest products are: - nums1[0] * nums2[1] = (-4) * 4 = -16 - nums1[0] * nums2[0] = (-4) * 2 = -8 - nums1[1] * nums2[1] = (-2) * 4 = -8 - nums1[1] * nums2[0] = (-2) * 2 = -4 - nums1[2] * nums2[0] = 0 * 2 = 0 - nums1[2] * nums2[1] = 0 * 4 = 0 The 6th smallest product is 0. Example 3: Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3 Output: -6 Explanation: The 3 smallest products are: - nums1[0] * nums2[4] = (-2) * 5 = -10 - nums1[0] * nums2[3] = (-2) * 4 = -8 - nums1[4] * nums2[0] = 2 * (-3) = -6 The 3rd smallest product is -6.   Constraints: 1 <= nums1.length, nums2.length <= 5 * 10000 -100000 <= nums1[i], nums2[j] <= 100000 1 <= k <= nums1.length * nums2.length nums1 and nums2 are sorted.
class Solution(object): def kthSmallestProduct(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: int """ if len(nums1) > len(nums2): nums1,nums2 = nums2,nums1 m = len(nums1) n = len(nums2) l = -10**10 -1 l_count = 0 r = -l r_count = m*n while r-l>1: mid = (l+r)//2 count = 0 for i in nums1: if i == 0: count += n if mid >=0 else 0 else: count += bisect.bisect_right(nums2, mid*1.0/i) if i>0 else n-bisect.bisect_left(nums2, mid*1.0/i) if count >= k: r = mid r_count = count else: l= mid l_count = count return r
4d68b3
0c8025
Write an API that generates fancy sequences using the append, addAll, and multAll operations. Implement the Fancy class: Fancy() Initializes the object with an empty sequence. void append(val) Appends an integer val to the end of the sequence. void addAll(inc) Increments all existing values in the sequence by an integer inc. void multAll(m) Multiplies all existing values in the sequence by an integer m. int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7. If the index is greater or equal than the length of the sequence, return -1.   Example 1: Input ["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"] [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]] Output [null, null, null, null, null, 10, null, null, null, 26, 34, 20] Explanation Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: [2] fancy.addAll(3); // fancy sequence: [2+3] -> [5] fancy.append(7); // fancy sequence: [5, 7] fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17] fancy.append(10); // fancy sequence: [13, 17, 10] fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20   Constraints: 1 <= val, inc, m <= 100 0 <= idx <= 100000 At most 100000 calls total will be made to append, addAll, multAll, and getIndex.
class Fancy(object): def __init__(self): self.diff = [] self.step = 0 self.fn = -1 self.factor = 1 def append(self, val): """ :type val: int :rtype: None """ if len(self.diff) == 0: self.fn = val self.diff.append([val - self.fn, self.factor]) def addAll(self, inc): """ :type inc: int :rtype: None """ self.fn += inc def multAll(self, m): """ :type m: int :rtype: None """ self.factor *= m self.fn*=m def getIndex(self, idx): """ :type idx: int :rtype: int """ if idx >= len(self.diff): return -1 return (self.fn + self.diff[idx][0]*self.factor/self.diff[idx][1])%1000000007 # Your Fancy object will be instantiated and called as such: # obj = Fancy() # obj.append(val) # obj.addAll(inc) # obj.multAll(m) # param_4 = obj.getIndex(idx)
4df514
0c8025
Write an API that generates fancy sequences using the append, addAll, and multAll operations. Implement the Fancy class: Fancy() Initializes the object with an empty sequence. void append(val) Appends an integer val to the end of the sequence. void addAll(inc) Increments all existing values in the sequence by an integer inc. void multAll(m) Multiplies all existing values in the sequence by an integer m. int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7. If the index is greater or equal than the length of the sequence, return -1.   Example 1: Input ["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"] [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]] Output [null, null, null, null, null, 10, null, null, null, 26, 34, 20] Explanation Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: [2] fancy.addAll(3); // fancy sequence: [2+3] -> [5] fancy.append(7); // fancy sequence: [5, 7] fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17] fancy.append(10); // fancy sequence: [13, 17, 10] fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20   Constraints: 1 <= val, inc, m <= 100 0 <= idx <= 100000 At most 100000 calls total will be made to append, addAll, multAll, and getIndex.
class Fancy: def __init__(self): self.L=[] self.coef=[1,0] def append(self, val: int) -> None: val=(val-self.coef[1])%(10**9+7) val=(val*pow(self.coef[0], -1, 10**9+7))%(10**9+7) self.L.append(val) def addAll(self, inc: int) -> None: self.coef[1]=(self.coef[1]+inc)%(10**9+7) def multAll(self, m: int) -> None: self.coef[0]=(self.coef[0]*m)%(10**9+7) self.coef[1]=(self.coef[1]*m)%(10**9+7) def getIndex(self, idx: int) -> int: if idx not in range(len(self.L)): return -1 else: return (self.L[idx]*self.coef[0]+self.coef[1])%(10**9+7) # Your Fancy object will be instantiated and called as such: # obj = Fancy() # obj.append(val) # obj.addAll(inc) # obj.multAll(m) # param_4 = obj.getIndex(idx)
1e2b19
a02758
Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. The test cases are generated so that the answer fits in 32-bit integer.   Example 1: Input: nums = [2,4,6,8,10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] Example 2: Input: nums = [7,7,7,7,7] Output: 16 Explanation: Any subsequence of this array is arithmetic.   Constraints: 1  <= nums.length <= 1000 -2^31 <= nums[i] <= 2^31 - 1
class Solution(object): def numberOfArithmeticSlices(self, A): """ :type A: List[int] :rtype: int """ ans=0 dp = [] for i in range(len(A)): a=A[i] dp.append({}) for j in range(i): b=A[j] d=a-b if d in dp[j]: v=1+dp[j][d] else: v=1 if d in dp[i]: dp[i][d]=dp[i][d]+v else: dp[i][d]=v ans += sum([dp[i][x] for x in dp[i]]) - i return ans
bf4f48
16a0ad
You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups.   Example 1: Input: cost = [[15, 96], [36, 2]] Output: 17 Explanation: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. Example 2: Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]] Output: 4 Explanation: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. Example 3: Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]] Output: 10   Constraints: size1 == cost.length size2 == cost[i].length 1 <= size1, size2 <= 12 size1 >= size2 0 <= cost[i][j] <= 100
class Solution: def connectTwoGroups(self, cost: List[List[int]]) -> int: m,n=len(cost),len(cost[0]) @lru_cache(None) def dp(i,mask,pt): # mask is which in group2 alreadyu hit if pt==0: if i==m: return dp(0,mask,1) ret=inf for j in range(n): ret=min(ret,dp(i+1,mask|(1<<j),0)+cost[i][j]) return ret else: if i==n: return 0 if mask&(1<<i): return dp(i+1,mask,1) # have to pick one to connect to mn=inf for j in range(m): mn=min(mn,cost[j][i]) return mn+dp(i+1,mask,1) return dp(0,0,0)
495502
16a0ad
You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups.   Example 1: Input: cost = [[15, 96], [36, 2]] Output: 17 Explanation: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. Example 2: Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]] Output: 4 Explanation: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. Example 3: Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]] Output: 10   Constraints: size1 == cost.length size2 == cost[i].length 1 <= size1, size2 <= 12 size1 >= size2 0 <= cost[i][j] <= 100
class Solution(object): def connectTwoGroups(self, cost): """ :type cost: List[List[int]] :rtype: int """ m,n = len(cost),len(cost[0]) dp = dict() c2 = list(zip(*cost)) # def dfs(arr1,arr2):#在arr1连接和arr2连接下最小cost # if (arr1,arr2) in dp: # return dp[(arr1,arr2)] # if arr1+1==1<<m and arr2+1<<n: # return 0 # for i in range(m): # if arr&1<<i==0: def dfs(index,arr2):#在arr1连接和arr2连接下最小cost if (index,arr2) in dp: return dp[(index,arr2)] if index==m: if 1+arr2 == 1<<n: return 0 else: cur = 0 for j in range(n): if arr2&1<<j==0: cur+=min(c2[j]) dp[(index,arr2)]=cur return cur cur = float('inf') for j in range(n): cur = min(cur,cost[index][j]+dfs(index+1,arr2|1<<j)) dp[(index,arr2)] = cur return cur return dfs(0,0)
8d5f02
3425b9
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. Return the minimum total cost for this robot to return home.   Example 1: Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7] Output: 18 Explanation: One optimal path is that: Starting from (1, 0) -> It goes down to (2, 0). This move costs rowCosts[2] = 3. -> It goes right to (2, 1). This move costs colCosts[1] = 2. -> It goes right to (2, 2). This move costs colCosts[2] = 6. -> It goes right to (2, 3). This move costs colCosts[3] = 7. The total cost is 3 + 2 + 6 + 7 = 18 Example 2: Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26] Output: 0 Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.   Constraints: m == rowCosts.length n == colCosts.length 1 <= m, n <= 100000 0 <= rowCosts[r], colCosts[c] <= 10000 startPos.length == 2 homePos.length == 2 0 <= startrow, homerow < m 0 <= startcol, homecol < n
class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: a, b = startPos ea, eb = homePos to_ret = 0 if eb > b : to_ret += sum(colCosts[b+1:eb+1]) if b > eb : to_ret += sum(colCosts[eb:b]) if ea > a : to_ret += sum(rowCosts[a+1:ea+1]) if a > ea : to_ret += sum(rowCosts[ea:a]) return to_ret
bd6d4b
3425b9
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. Return the minimum total cost for this robot to return home.   Example 1: Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7] Output: 18 Explanation: One optimal path is that: Starting from (1, 0) -> It goes down to (2, 0). This move costs rowCosts[2] = 3. -> It goes right to (2, 1). This move costs colCosts[1] = 2. -> It goes right to (2, 2). This move costs colCosts[2] = 6. -> It goes right to (2, 3). This move costs colCosts[3] = 7. The total cost is 3 + 2 + 6 + 7 = 18 Example 2: Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26] Output: 0 Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.   Constraints: m == rowCosts.length n == colCosts.length 1 <= m, n <= 100000 0 <= rowCosts[r], colCosts[c] <= 10000 startPos.length == 2 homePos.length == 2 0 <= startrow, homerow < m 0 <= startcol, homecol < n
class Solution(object): def minCost(self, startPos, homePos, rowCosts, colCosts): """ :type startPos: List[int] :type homePos: List[int] :type rowCosts: List[int] :type colCosts: List[int] :rtype: int """ ans = 0 r, c = startPos nr, nc = homePos while r != nr: if r < nr: r += 1 else: r -= 1 ans += rowCosts[r] while c != nc: if c < nc: c += 1 else: c -= 1 ans += colCosts[c] return ans
9b17a6
f09023
You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if: It is directly connected to the top of the grid, or At least one other brick in its four adjacent cells is stable. You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.   Example 1: Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]] Output: [2] Explanation: Starting with the grid: [[1,0,0,0], [1,1,1,0]] We erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,1,1,0]] The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is: [[1,0,0,0], [0,0,0,0]] Hence the result is [2]. Example 2: Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]] Output: [0,0] Explanation: Starting with the grid: [[1,0,0,0], [1,1,0,0]] We erase the underlined brick at (1,1), resulting in the grid: [[1,0,0,0], [1,0,0,0]] All remaining bricks are still stable, so no bricks fall. The grid remains the same: [[1,0,0,0], [1,0,0,0]] Next, we erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,0,0,0]] Once again, all remaining bricks are still stable, so no bricks fall. Hence the result is [0,0].   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 200 grid[i][j] is 0 or 1. 1 <= hits.length <= 4 * 10000 hits[i].length == 2 0 <= xi <= m - 1 0 <= yi <= n - 1 All (xi, yi) are unique.
class Solution(object): def hitBricks(self, grid, hits): grid2 = [[[] for _ in row] for row in grid] for i in range(len(grid)): for j in range(len(grid[0])): for i2, j2 in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]: if i2 < 0 or i2 >= len(grid) or j2 < 0 or j2 >= len(grid[0]): continue grid2[i][j].append((i2, j2)) grid3 = [[[] for _ in row] for row in grid] for j in range(len(grid[0])): q = [(0, j)] seen = set(q) while q: i, j = q.pop(0) seen.add((i, j)) if grid[i][j] != 1: continue for child in grid2[i][j]: i2, j2 = child if i2 == 0: continue if child not in seen and (i, j) not in grid3[i2][j2]: q.append(child) grid3[child[0]][child[1]].append((i, j)) ans = [] for i, j in hits: #print("\n".join("".join(str(len(c)) if c else '.' for c in row) for row in grid3)) grid[i][j] = 0 q = [(i, j)] seen = set(q) res = 0 while q: i2, j2 = q.pop(0) seen.add((i2, j2)) for child in grid2[i2][j2]: if child in seen: continue if child[0] == 0: continue i3, j3 = child if grid[i3][j3] == 0: continue if (i2, j2) in grid3[i3][j3]: grid3[child[0]][child[1]].remove((i2, j2)) x, y = i3, j3 while len(grid3[x][y]) == 1: i4, j4 = grid3[x][y][0] if (x, y) in grid3[i4][j4]: grid3[i4][j4].remove((x, y)) if len(grid3[i4][j4]) == 1: x, y = i4, j4 else: break else: break if not grid3[child[0]][child[1]]: grid[i3][j3] = 0 q.append((i3, j3)) res += 1 ans.append(res) return ans
96e36a
841fb1
There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), or (r, c-1). A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations​​​​​. Notes: No two pieces will start in the same square. You may choose the square a piece is already on as its destination. If two pieces are directly adjacent to each other, it is valid for them to move past each other and swap positions in one second.   Example 1: Input: pieces = ["rook"], positions = [[1,1]] Output: 15 Explanation: The image above shows the possible squares the piece can move to. Example 2: Input: pieces = ["queen"], positions = [[1,1]] Output: 22 Explanation: The image above shows the possible squares the piece can move to. Example 3: Input: pieces = ["bishop"], positions = [[4,3]] Output: 12 Explanation: The image above shows the possible squares the piece can move to.   Constraints: n == pieces.length n == positions.length 1 <= n <= 4 pieces only contains the strings "rook", "queen", and "bishop". There will be at most one queen on the chessboard. 1 <= xi, yi <= 8 Each positions[i] is distinct.
class Solution(object): def countCombinations(self, p, pos): res = [] n = len(p) for k in range(n): cur = set() x, y = pos[k] for i in xrange(1, 9): for j in xrange(1, 9): if (i == x or j == y) and p[k][0] in 'rq': cur.add((i, j)) if (i - j == x - y or i + j == x + y) and p[k][0] in 'qb': cur.add((i, j)) res.append(list(cur)) ress = 0 def check(pos2): if len(set(pos2)) < n: return False tt = [] for i in xrange(n): x0, y0 = pos[i] x1, y1 = pos2[i] t = max(abs(x0 - x1), abs(y0 - y1)) tt.append(t) for t in range(max(tt)): cur = [] for i in xrange(n): x0, y0 = pos[i] x1, y1 = pos2[i] if tt[i] == 0: cur.append((x0, y0)) else: x = x0 + (x1 - x0) / tt[i] * t if t < tt[i] else x1 y = y0 + (y1 - y0) / tt[i] * t if t < tt[i] else y1 cur.append((x, y)) if len(set(cur)) < n: # print pos, cur, pos2 return False return True for case in itertools.product(*res): ress += check(case) return ress
823fe4
841fb1
There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), or (r, c-1). A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations​​​​​. Notes: No two pieces will start in the same square. You may choose the square a piece is already on as its destination. If two pieces are directly adjacent to each other, it is valid for them to move past each other and swap positions in one second.   Example 1: Input: pieces = ["rook"], positions = [[1,1]] Output: 15 Explanation: The image above shows the possible squares the piece can move to. Example 2: Input: pieces = ["queen"], positions = [[1,1]] Output: 22 Explanation: The image above shows the possible squares the piece can move to. Example 3: Input: pieces = ["bishop"], positions = [[4,3]] Output: 12 Explanation: The image above shows the possible squares the piece can move to.   Constraints: n == pieces.length n == positions.length 1 <= n <= 4 pieces only contains the strings "rook", "queen", and "bishop". There will be at most one queen on the chessboard. 1 <= xi, yi <= 8 Each positions[i] is distinct.
DIR_STRAIGHT = (1, 0, -1, 0, 1) DIR_DIAGNAL = (1, -1, -1, 1, 1) class Solution: def dfs(self, player: int, buffer: List[List[int]], length: int, valids): # if (player == length): if self.bfs(buffer): self.res += 1 else: for each in valids[player]: buffer.append(each) self.dfs(player + 1, buffer, length, valids) buffer.pop() def bfs(self, combination)-> bool: board = [[0] * 9 for _ in range(9)] q = [] for player in combination: board[player[2]][player[3]] = 1 if player[2] != player[4] or player[3] != player[5]: q.append([*player]) while q: for player in q: # vaccate board[player[2]][player[3]] = 0 q2 = [] for player in q: player[2] += player[0] player[3] += player[1] if board[player[2]][player[3]] == 1: return False board[player[2]][player[3]] = 1 if player[2] != player[4] or player[3] != player[5]: q2.append(player) q = q2 return True def moves(self, dir: tuple, valid: List[tuple], sr: int, sc: int): er, ec = sr, sc while 1: er += dir[0] ec += dir[1] if er == 0 or er == 9 or ec == 0 or ec == 9: break valid.append((dir[0], dir[1], sr, sc, er, ec)) def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int: valids = [] for idx in range(len(pieces)): valid = [] valids.append(valid) valid.append((0, 0, positions[idx][0], positions[idx][1], positions[idx][0], positions[idx][1])) chesser = pieces[idx][0] if 'b' != chesser: for i in range(4): self.moves((DIR_STRAIGHT[i], DIR_STRAIGHT[i+1]), valid, positions[idx][0], positions[idx][1]) if 'r' != chesser: for i in range(4): self.moves((DIR_DIAGNAL[i],DIR_DIAGNAL[i+1]), valid, positions[idx][0], positions[idx][1]) self.res = 0 if len(pieces) == 1: return len(valids[0]) self.dfs(0, [], len(pieces), valids) return self.res
1496cb
911d93
You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2. Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times. Note that a | b denotes the bitwise or between two integers a and b.   Example 1: Input: nums = [12,9], k = 1 Output: 30 Explanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. Example 2: Input: nums = [8,1,2], k = 2 Output: 35 Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 1 <= k <= 15
class Solution: def maximumOr(self, nums: List[int], k: int) -> int: single = 0 double = 0 for v in nums: double |= v & single single |= v poss = 0 for v in nums: res = single & ~(v) res |= double res |= (v << k) poss = max(poss, res) return poss
47ec76
911d93
You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2. Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times. Note that a | b denotes the bitwise or between two integers a and b.   Example 1: Input: nums = [12,9], k = 1 Output: 30 Explanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. Example 2: Input: nums = [8,1,2], k = 2 Output: 35 Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 1 <= k <= 15
class Solution(object): def maximumOr(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() n = len(nums) pre = nums[:] for i in range(n-2, -1, -1): pre[i] = pre[i]|pre[i+1] temp = 0 ans = pre[0] pre += [0] for i in range(n): ans = max(ans, temp|pre[i+1]|(nums[i]*pow(2, k))) temp = temp|nums[i] return (ans)
7a6cf5
ceb2db
You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4. Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Return the XOR sum after the rearrangement.   Example 1: Input: nums1 = [1,2], nums2 = [2,3] Output: 2 Explanation: Rearrange nums2 so that it becomes [3,2]. The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2. Example 2: Input: nums1 = [1,0,3], nums2 = [5,3,4] Output: 8 Explanation: Rearrange nums2 so that it becomes [5,4,3]. The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.   Constraints: n == nums1.length n == nums2.length 1 <= n <= 14 0 <= nums1[i], nums2[i] <= 10^7
class Solution: def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) @cache def ans(x, bitset): if x == len(nums1): return 0 ret = 10**18 for i in range(n): if bitset&(1<<i): ret = min(ret, (nums1[x]^nums2[i]) + ans(x+1, bitset^(1<<i))) return ret return ans(0, (1<<n)-1)
00cae5
ceb2db
You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4. Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Return the XOR sum after the rearrangement.   Example 1: Input: nums1 = [1,2], nums2 = [2,3] Output: 2 Explanation: Rearrange nums2 so that it becomes [3,2]. The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2. Example 2: Input: nums1 = [1,0,3], nums2 = [5,3,4] Output: 8 Explanation: Rearrange nums2 so that it becomes [5,4,3]. The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.   Constraints: n == nums1.length n == nums2.length 1 <= n <= 14 0 <= nums1[i], nums2[i] <= 10^7
class Solution(object): def minimumXORSum(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ m={} def conv(arr): arr.sort() s="" for i in arr: s+=str(i)+'$' return s def func(k,brr): if k==len(nums1): return 0 s=conv(brr) if m.get(s,10**18)!=10**18: return m[s] val=10**18 brr.sort() for i in range(len(brr)): ans=nums2[brr[i]]^nums1[k] crr=brr[:] crr.pop(i) ans+=func(k+1,crr) val=min(val,ans) m[s]=val return val val=func(0,[i for i in range(len(nums1))]) return val
04abf8
2b2fd4
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.   Example 1: Input: n = 5 Output: 2 Explanation: Because the 3rd row is incomplete, we return 2. Example 2: Input: n = 8 Output: 3 Explanation: Because the 4th row is incomplete, we return 3.   Constraints: 1 <= n <= 2^31 - 1
class Solution(object): def arrangeCoins(self, n): if n<=0: return 0 i = 0 j = n m = 0 n = n*2 while i <=j: m = (i+j)/2 r = m*(1+m) if r > n: j = m-1 elif r < n: i = m+1 else: return m r = m*(1+m) if r > n: return m-1 else: return m
28c113
34877f
We define the lcp matrix of any 0-indexed string word of n lowercase English letters as an n x n grid such that: lcp[i][j] is equal to the length of the longest common prefix between the substrings word[i,n-1] and word[j,n-1]. Given an n x n matrix lcp, return the alphabetically smallest string word that corresponds to lcp. If there is no such string, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "aabd" is lexicographically smaller than "aaca" because the first position they differ is at the third letter, and 'b' comes before 'c'.   Example 1: Input: lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] Output: "abab" Explanation: lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab". Example 2: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] Output: "aaaa" Explanation: lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa". Example 3: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] Output: "" Explanation: lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists.   Constraints: 1 <= n == lcp.length == lcp[i].length <= 1000 0 <= lcp[i][j] <= n
class Solution(object): def findTheString(self, lcp): """ :type lcp: List[List[int]] :rtype: str """ n = len(lcp) adj = [[] for _ in xrange(n)] for i in xrange(n): for j in xrange(i, n): if lcp[i][j] > 0: adj[i].append(j) adj[j].append(i) c = 0 r = [None] * n for i in xrange(n): if r[i] is not None: continue if c >= 26: return '' r[i] = chr(c + ord('a')) c += 1 q = [i] while q: u = q.pop() for v in adj[u]: if r[v] is not None: continue r[v] = r[i] s = ''.join(r) for i in xrange(n): for j in xrange(n): if s[i] != s[j]: c = 0 elif i+1<n and j+1<n: c = 1 + lcp[i+1][j+1] else: c = 1 if lcp[i][j] != c: return '' return ''.join(r)
ae72aa
34877f
We define the lcp matrix of any 0-indexed string word of n lowercase English letters as an n x n grid such that: lcp[i][j] is equal to the length of the longest common prefix between the substrings word[i,n-1] and word[j,n-1]. Given an n x n matrix lcp, return the alphabetically smallest string word that corresponds to lcp. If there is no such string, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "aabd" is lexicographically smaller than "aaca" because the first position they differ is at the third letter, and 'b' comes before 'c'.   Example 1: Input: lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] Output: "abab" Explanation: lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab". Example 2: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] Output: "aaaa" Explanation: lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa". Example 3: Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] Output: "" Explanation: lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists.   Constraints: 1 <= n == lcp.length == lcp[i].length <= 1000 0 <= lcp[i][j] <= n
class Solution: def findTheString(self, lcp: List[List[int]]) -> str: n = len(lcp) cc = [-1 for _ in range(n)] step = 0 for i in range(n): if cc[i] == -1: cc[i] = step for j in range(i+1, n): if lcp[i][j] != 0: if cc[j] != -1: return '' cc[j] = step step += 1 step %= 26 for i in range(n): for j in range(n): if cc[i] == cc[j]: prev = 0 if i < n-1 and j < n-1: prev = lcp[i+1][j+1] if lcp[i][j] != 1 + prev: return '' else: if lcp[i][j] != 0: return '' return ''.join([chr(97+x) for x in cc])
df6d6a
0171d0
Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing.   Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,2,2,2,2] Output: 5 Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.   Constraints: 1 <= nums.length <= 2000 -1000000 <= nums[i] <= 1000000
class Solution(object): def findNumberOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return 0 maxl = 1 dp = [] cnt = [] for i in range(n): dp.append(1) cnt.append(1) for i in range(n): for j in range(i): if nums[j] < nums[i]: if dp[j] + 1 > dp[i]: dp[i] = dp[j] + 1 cnt[i] = cnt[j] elif dp[j] + 1 == dp[i]: cnt[i] += cnt[j] maxl = max(maxl, dp[i]) #print i, dp[i], cnt[i] ans = 0 for i in range(n): if dp[i] == maxl: ans += cnt[i] return ans
3515b9
0171d0
Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing.   Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,2,2,2,2] Output: 5 Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.   Constraints: 1 <= nums.length <= 2000 -1000000 <= nums[i] <= 1000000
class Solution: def findNumberOfLIS(self, a): n = len(a) dp = [0]*n cs = [0]*n r, s = 0, 0 for i in range(n): v, c = 1, 1 for j in range(i): if a[j] < a[i]: if dp[j] >= v: v = dp[j]+1 c = cs[j] elif dp[j]+1 == v: c += cs[j] dp[i] = v cs[i] = c r = max(r, dp[i]) for i in range(n): if dp[i] == r: s += cs[i] return s
b42950
749bf4
Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands.   Example 1: Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] Output: 1 Example 3: Input: grid = [[1,1,1,1,1,1,1],   [1,0,0,0,0,0,1],   [1,0,1,1,1,0,1],   [1,0,1,0,1,0,1],   [1,0,1,1,1,0,1],   [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] Output: 2   Constraints: 1 <= grid.length, grid[0].length <= 100 0 <= grid[i][j] <=1
class Solution(object): def closedIsland(self, A): R, C = len(A), len(A[0]) def neighbors(r, c): for nr, nc in ((r-1, c), (r, c-1), (r+1, c),(r, c+1)): yield nr, nc def dfs(r, c): for nr, nc in neighbors(r, c): if not( 0 <= nr < R and 0 <= nc < C): self.bns = 0 else: if (nr, nc) not in seen and A[nr][nc] == 0: seen.add((nr, nc)) dfs(nr, nc) seen = set() ans = 0 for r, row in enumerate(A): for c, val in enumerate(row): if (r, c) not in seen and val == 0: self.bns = 1 seen.add((r, c)) dfs(r, c) ans += self.bns return ans
32b7e3
749bf4
Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands.   Example 1: Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] Output: 1 Example 3: Input: grid = [[1,1,1,1,1,1,1],   [1,0,0,0,0,0,1],   [1,0,1,1,1,0,1],   [1,0,1,0,1,0,1],   [1,0,1,1,1,0,1],   [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] Output: 2   Constraints: 1 <= grid.length, grid[0].length <= 100 0 <= grid[i][j] <=1
class Solution: def closedIsland(self, grid: List[List[int]]) -> int: s=0 n=len(grid) m=len(grid[0]) d=[[-1,0],[1,0],[0,-1],[0,1]] for i in range(n): for j in range(m): if grid[i][j]==0: flag=True arr=[(i,j)] grid[i][j]=2 start=0 end=1 while(start<end): x=arr[start][0] y=arr[start][1] start=start+1 for dd in d: dx=x+dd[0] dy=y+dd[1] if dx<0 or dx>=n or dy<0 or dy>=m: flag=False elif grid[dx][dy]==0: grid[dx][dy]=2 arr.append((dx,dy)) end=end+1 if flag==True: s=s+1 return s
95184c
30e42c
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A good path is a simple path that satisfies the following conditions: The starting node and the ending node have the same value. All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path). Return the number of distinct good paths. Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.   Example 1: Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]] Output: 6 Explanation: There are 5 good paths consisting of a single node. There is 1 additional good path: 1 -> 0 -> 2 -> 4. (The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.) Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0]. Example 2: Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]] Output: 7 Explanation: There are 5 good paths consisting of a single node. There are 2 additional good paths: 0 -> 1 and 2 -> 3. Example 3: Input: vals = [1], edges = [] Output: 1 Explanation: The tree consists of only one node, so there is one good path.   Constraints: n == vals.length 1 <= n <= 3 * 10000 0 <= vals[i] <= 100000 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree.
class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: n = len(vals) parent = [i for i in range(n)] sz = [1 for i in range(n)] def root(x): if x == parent[x]: return x parent[x] = root(parent[x]) return parent[x] def join(x, y): x, y = root(x), root(y) if x == y: return if sz[x] > sz[y]: x, y = y, x parent[x] = y sz[y] += sz[x] d = defaultdict(list) for i in range(n): d[vals[i]].append(i) adj = [[] for i in range(n)] for i, j in edges: adj[i].append(j) adj[j].append(i) added = [False]*n res = 0 for _ in sorted(d): v = d[_] for i in v: added[i] = True for j in adj[i]: if added[j]: join(i, j) c = Counter() for i in v: c[root(i)] += 1 for i in c.values(): res += i*(i+1) // 2 return res
5fdb19
30e42c
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A good path is a simple path that satisfies the following conditions: The starting node and the ending node have the same value. All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path). Return the number of distinct good paths. Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.   Example 1: Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]] Output: 6 Explanation: There are 5 good paths consisting of a single node. There is 1 additional good path: 1 -> 0 -> 2 -> 4. (The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.) Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0]. Example 2: Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]] Output: 7 Explanation: There are 5 good paths consisting of a single node. There are 2 additional good paths: 0 -> 1 and 2 -> 3. Example 3: Input: vals = [1], edges = [] Output: 1 Explanation: The tree consists of only one node, so there is one good path.   Constraints: n == vals.length 1 <= n <= 3 * 10000 0 <= vals[i] <= 100000 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree.
class Solution(object): def numberOfGoodPaths(self, vals, edges): """ :type vals: List[int] :type edges: List[List[int]] :rtype: int """ f, g, h, i, j = [], [0] * len(vals), [0] * len(vals), [1] * len(vals), [1] * len(vals) def l(n): if g[n] == n: return n o = l(g[n]) g[n], h[n], i[n], j[n] = o, h[o], i[o], j[o] return o def m(n, o): p, q = l(n), l(o) g[q], j[p], i[p], h[p] = g[q] if p == q else p, j[p] if p == q else j[p] + j[q] + (i[p] * i[q] if h[p] == h[q] else 0), i[p] if p == q else i[p] + i[q] if h[p] == h[q] else i[q] if h[p] < h[q] else i[p], max(h[p], h[q]) for k in range(len(vals) - 1): edges[k][0], edges[k][1] = edges[k][1] if vals[edges[k][0]] < vals[edges[k][1]] else edges[k][0], edges[k][0] if vals[edges[k][0]] < vals[edges[k][1]] else edges[k][1] for k in range(len(vals) - 1): f.append([max(vals[edges[k][0]], vals[edges[k][1]]), edges[k][0], edges[k][1]]) f.sort() for k in range(len(vals)): g[k], h[k] = k, vals[k] for k in range(len(vals) - 1): m(f[k][1], f[k][2]) return j[l(0)]
92b68a
70508e
There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations: Serve 100 ml of soup A and 0 ml of soup B, Serve 75 ml of soup A and 25 ml of soup B, Serve 50 ml of soup A and 50 ml of soup B, and Serve 25 ml of soup A and 75 ml of soup B. When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: n = 50 Output: 0.62500 Explanation: If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. Example 2: Input: n = 100 Output: 0.71875   Constraints: 0 <= n <= 10^9
from functools import wraps def memo(f): cache = {} @wraps(f) def wrap(*args): if args not in cache: cache[args]=f(*args) return cache[args] return wrap class Solution(object): def soupServings(self, N): if N>=5000: return 1 @memo def helper(k,l): if k<=0 and l<=0: return 0.5 if k<=0: return 1 if l<=0: return 0 return 0.25*(helper(k-4,l)+helper(k-3,l-1)+helper(k-2,l-2)+helper(k-1,l-3)) if N%25!=0: k=N//25+1 else: k=N//25 return helper(k,k) """ :type N: int :rtype: float """
1a9b51
70508e
There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations: Serve 100 ml of soup A and 0 ml of soup B, Serve 75 ml of soup A and 25 ml of soup B, Serve 50 ml of soup A and 50 ml of soup B, and Serve 25 ml of soup A and 75 ml of soup B. When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: n = 50 Output: 0.62500 Explanation: If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. Example 2: Input: n = 100 Output: 0.71875   Constraints: 0 <= n <= 10^9
class Solution(object): def soupServings(self, N): """ :type N: int :rtype: float """ if N > 6000: return 0.9999999 resa = 0 resab = 0 dic = {(N, N): 1} op = [(-100, 0), (-75, -25), (-50, -50), (-25, -75)] keys = [(N, N)] while True: if len(keys) == 0 or len(dic) == 0 or keys[0] not in dic: break cur = keys[0] poss = 0.25 * dic[cur] del dic[cur] keys.pop(0) for o in op: nx = max(cur[0] + o[0], 0) ny = max(cur[1] + o[1], 0) if nx == 0 and ny == 0: resab += poss elif nx == 0: resa += poss if nx != 0 and ny != 0: if (nx, ny) in dic: dic[(nx, ny)] += poss else: dic[(nx, ny)] = poss keys.append((nx, ny)) return resa + 0.5 * resab
2eb86e
3a10e6
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp. Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded. Finds the maximum price the stock has been based on the current records. Finds the minimum price the stock has been based on the current records. Implement the StockPrice class: StockPrice() Initializes the object with no price records. void update(int timestamp, int price) Updates the price of the stock at the given timestamp. int current() Returns the latest price of the stock. int maximum() Returns the maximum price of the stock. int minimum() Returns the minimum price of the stock.   Example 1: Input ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] Output [null, null, null, 5, 10, null, 5, null, 2] Explanation StockPrice stockPrice = new StockPrice(); stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10]. stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5]. stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5. stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1. stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3. // Timestamps are [1,2] with corresponding prices [3,5]. stockPrice.maximum(); // return 5, the maximum price is 5 after the correction. stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2]. stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.   Constraints: 1 <= timestamp, price <= 10^9 At most 100000 calls will be made in total to update, current, maximum, and minimum. current, maximum, and minimum will be called only after update has been called at least once.
class StockPrice: def __init__(self): self.tp=defaultdict(int) self.mx=[] self.mn=[] self.now=-1 self.cur=0 def update(self, timestamp: int, price: int) -> None: if timestamp>=self.now: self.now=timestamp self.cur=price self.tp[timestamp]=price heappush(self.mx,(-price,timestamp)) heappush(self.mn,(price,timestamp)) def current(self) -> int: return self.cur def maximum(self) -> int: while 1: p,t=self.mx[0] p=-p if self.tp[t]==p: return p heappop(self.mx) def minimum(self) -> int: while 1: p,t=self.mn[0] if self.tp[t]==p: return p heappop(self.mn) # Your StockPrice object will be instantiated and called as such: # obj = StockPrice() # obj.update(timestamp,price) # param_2 = obj.current() # param_3 = obj.maximum() # param_4 = obj.minimum()
1f854c
3a10e6
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp. Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded. Finds the maximum price the stock has been based on the current records. Finds the minimum price the stock has been based on the current records. Implement the StockPrice class: StockPrice() Initializes the object with no price records. void update(int timestamp, int price) Updates the price of the stock at the given timestamp. int current() Returns the latest price of the stock. int maximum() Returns the maximum price of the stock. int minimum() Returns the minimum price of the stock.   Example 1: Input ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] Output [null, null, null, 5, 10, null, 5, null, 2] Explanation StockPrice stockPrice = new StockPrice(); stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10]. stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5]. stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5. stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1. stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3. // Timestamps are [1,2] with corresponding prices [3,5]. stockPrice.maximum(); // return 5, the maximum price is 5 after the correction. stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2]. stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.   Constraints: 1 <= timestamp, price <= 10^9 At most 100000 calls will be made in total to update, current, maximum, and minimum. current, maximum, and minimum will be called only after update has been called at least once.
from heapq import heappush, heappop class Heap: def __init__(self): self._h = [] def remove(self, val): heappush(self._h, (val, -1)) def add(self, val): heappush(self._h, (val, 1)) def top(self): self._bal() return self._h[0][0] def _bal(self): s = 0 while s < 0 or (self._h and self._h[0][1] < 0): s += heappop(self._h)[1] class StockPrice(object): def __init__(self): self._d = {} self._lo = Heap() self._hi = Heap() self._ts = float('-inf') self._cur = None def update(self, timestamp, price): """ :type timestamp: int :type price: int :rtype: None """ if timestamp in self._d: oldprice = self._d[timestamp] self._lo.remove((oldprice, timestamp)) self._hi.remove((-oldprice, timestamp)) self._d[timestamp] = price self._lo.add((price, timestamp)) self._hi.add((-price, timestamp)) if timestamp >= self._ts: self._ts = timestamp self._cur = price def current(self): """ :rtype: int """ return self._cur def maximum(self): """ :rtype: int """ return -self._hi.top()[0] def minimum(self): """ :rtype: int """ return self._lo.top()[0] # Your StockPrice object will be instantiated and called as such: # obj = StockPrice() # obj.update(timestamp,price) # param_2 = obj.current() # param_3 = obj.maximum() # param_4 = obj.minimum()
dc5dcd
0aad4a
There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A node sequence is valid if it meets the following conditions: There is an edge connecting every pair of adjacent nodes in the sequence. No node appears more than once in the sequence. The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.   Example 1: Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 24 Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3]. The score of the node sequence is 5 + 2 + 9 + 8 = 24. It can be shown that no other node sequence has a score of more than 24. Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24. The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3. Example 2: Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]] Output: -1 Explanation: The figure above shows the graph. There are no valid node sequences of length 4, so we return -1.   Constraints: n == scores.length 4 <= n <= 5 * 10000 1 <= scores[i] <= 10^8 0 <= edges.length <= 5 * 10000 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate edges.
class Solution: def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: adj = defaultdict(list) for i, j in edges: adj[i].append(j) adj[j].append(i) for i in adj: adj[i].sort(key=lambda x: scores[x], reverse=True) adj[i] = adj[i][:4] ans = -1 for i, j in edges: for k in adj[i]: for l in adj[j]: if len(set((i, j, k, l))) == 4: ans = max(ans, scores[i] + scores[j] + scores[k] + scores[l]) return ans
e1f163
0aad4a
There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A node sequence is valid if it meets the following conditions: There is an edge connecting every pair of adjacent nodes in the sequence. No node appears more than once in the sequence. The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.   Example 1: Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 24 Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3]. The score of the node sequence is 5 + 2 + 9 + 8 = 24. It can be shown that no other node sequence has a score of more than 24. Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24. The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3. Example 2: Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]] Output: -1 Explanation: The figure above shows the graph. There are no valid node sequences of length 4, so we return -1.   Constraints: n == scores.length 4 <= n <= 5 * 10000 1 <= scores[i] <= 10^8 0 <= edges.length <= 5 * 10000 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate edges.
class Solution(object): def maximumScore(self, scores, edges): """ :type scores: List[int] :type edges: List[List[int]] :rtype: int """ n = len(scores) rs = [[(-1,-1),(-1,-1),(-1,-1)] for _ in range(n)] for a, b in edges: v, i = scores[b], b if v>rs[a][0][0]: rs[a][2], rs[a][1] = rs[a][1], rs[a][0] rs[a][0]=(v, i) elif v>rs[a][1][0]: rs[a][2]=rs[a][1] rs[a][1] = (v,i) elif v>rs[a][2][0]: rs[a][2]=(v, i) v, i = scores[a], a if v>rs[b][0][0]: rs[b][2], rs[b][1] = rs[b][1], rs[b][0] rs[b][0]=(v, i) elif v>rs[b][1][0]: rs[b][2]=rs[b][1] rs[b][1] = (v,i) elif v>rs[b][2][0]: rs[b][2]=(v, i) rc=-1 for a, b in edges: v=scores[a]+scores[b] for k1 in range(3): v1, i1 = rs[a][k1] if v1==-1: break if i1==b: continue for k2 in range(3): v2, i2 = rs[b][k2] if v2==-1: break if i2==a: continue if i1==i2: continue vv=v1+v2+v if rc<vv: rc=vv return rc
696703
e9b056
You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm: The ith (0-indexed) request arrives. If all servers are busy, the request is dropped (not handled at all). If the (i % k)th server is available, assign the request to that server. Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on. You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.   Example 1: Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] Output: [1] Explanation: All of the servers start out available. The first 3 requests are handled by the first 3 servers in order. Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1. Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped. Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server. Example 2: Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2] Output: [0] Explanation: The first 3 requests are handled by first 3 servers. Request 3 comes in. It is handled by server 0 since the server is available. Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. Example 3: Input: k = 3, arrival = [1,2,3], load = [10,12,11] Output: [0,1,2] Explanation: Each server handles a single request, so they are all considered the busiest.   Constraints: 1 <= k <= 100000 1 <= arrival.length, load.length <= 100000 arrival.length == load.length 1 <= arrival[i], load[i] <= 10^9 arrival is strictly increasing.
from sortedcontainers import SortedList class Solution: def busiestServers(self, K: int, arrival: List[int], load: List[int]) -> List[int]: heap = [] s = SortedList() counts = [0] * K for x in range(K): s.add(x) for i, (a, l) in enumerate(zip(arrival, load)): while len(heap) > 0: t, index = heap[0] if t <= a: heapq.heappop(heap) s.add(index) else: break k = s.bisect_left(i%K) if k >= len(s): k = s.bisect_left(0) if k < len(s): counts[s[k]] += 1 heapq.heappush(heap, (a + l, s[k])) #print(i,a, l, s[k]) s.discard(s[k]) #print(counts) results = [] target = max(counts) for x in range(K): if counts[x] == target: results.append(x) return results
e859dd
e9b056
You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm: The ith (0-indexed) request arrives. If all servers are busy, the request is dropped (not handled at all). If the (i % k)th server is available, assign the request to that server. Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on. You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.   Example 1: Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] Output: [1] Explanation: All of the servers start out available. The first 3 requests are handled by the first 3 servers in order. Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1. Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped. Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server. Example 2: Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2] Output: [0] Explanation: The first 3 requests are handled by first 3 servers. Request 3 comes in. It is handled by server 0 since the server is available. Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. Example 3: Input: k = 3, arrival = [1,2,3], load = [10,12,11] Output: [0,1,2] Explanation: Each server handles a single request, so they are all considered the busiest.   Constraints: 1 <= k <= 100000 1 <= arrival.length, load.length <= 100000 arrival.length == load.length 1 <= arrival[i], load[i] <= 10^9 arrival is strictly increasing.
class Solution(object): def busiestServers(self, k, arrival, load): """ :type k: int :type arrival: List[int] :type load: List[int] :rtype: List[int] """ reqs = collections.Counter() avails = range(k) frees = [] for i, (t, l) in enumerate(zip(arrival, load)): while frees and frees[0][0] <= t: _, s = heapq.heappop(frees) bisect.insort(avails, s) # print i, frees, avails, reqs if not avails: continue idx = bisect.bisect_left(avails, i % k) if idx >= len(avails): idx = 0 reqs[avails[idx]] += 1 heapq.heappush(frees, (t + l, avails[idx])) del avails[idx] mx = max(reqs.values()) return [k for k, v in reqs.items() if v == mx]
0c0b4e
a59a5f
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.   Constraints: 1 <= stoneValue.length <= 5 * 10000 -1000 <= stoneValue[i] <= 1000
class Solution(object): def stoneGameIII(self, A): N = len(A) WA = "Alice" WB = "Bob" WT = "Tie" S = sum(A) dp = [float('-inf')] * (N+1) dp[N] = 0 # dp[i] : with A[i:] left, and its alice's turn, what is score of game? for i in xrange(N-1, -1, -1): for j in xrange(3): if i + j >= N: continue # take 1, then eg. took A[i] dp[i] = max(dp[i], sum(A[i+k] for k in xrange(j+1)) - dp[i+j +1]) ans = dp[0] if ans > 0: return WA if ans < 0: return WB return WT
f85999
a59a5f
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.   Constraints: 1 <= stoneValue.length <= 5 * 10000 -1000 <= stoneValue[i] <= 1000
from functools import * class Solution: def stoneGameIII(self, sv: List[int]) -> str: n=len(sv) @lru_cache(maxsize=None) def dp(i): if i>=n: return 0 if i==n-1: return sv[-1] end=min(i+3,n) ans=float("-inf") acc=0 for j in range(i,end): acc+=sv[j] ans=max(ans,acc-dp(j+1)) return ans ans=dp(0) if ans>0: return "Alice" elif ans<0: return "Bob" else: return "Tie"