sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
cd0ce3
37ab89
You are given two numeric strings num1 and num2 and two integers max_sum and min_sum. We denote an integer x to be good if: num1 <= x <= num2 min_sum <= digit_sum(x) <= max_sum. Return the number of good integers. Since the answer may be large, return it modulo 109 + 7. Note that digit_sum(x) denotes the sum of the digits of x.   Example 1: Input: num1 = "1", num2 = "12", min_sum = 1, max_sum = 8 Output: 11 Explanation: There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. Example 2: Input: num1 = "1", num2 = "5", min_sum = 1, max_sum = 5 Output: 5 Explanation: The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.   Constraints: 1 <= num1 <= num2 <= 1022 1 <= min_sum <= max_sum <= 400
class Solution(object): def count(self, num1, num2, min_sum, max_sum): """ :type num1: str :type num2: str :type min_sum: int :type max_sum: int :rtype: int """ M = 10**9 + 7 def getnext(index,rest,flag,num,dic): if (index,rest,flag) in dic: return dic[(index,rest,flag)] if index==len(num): return 1 output = 0 for d in range(10): if flag and d > int(num[index]): break if d > rest: break if str(d)==num[index]: output += getnext(index+1,rest-d,flag,num,dic) else: output += getnext(index+1,rest-d,False,num,dic) output %= M dic[(index,rest,flag)] = output return output def calculate(num,dsum): dic = {} output = getnext(0,dsum,True,num,dic) return output num1 = str(int(num1)-1) ans = calculate(num2,max_sum) + calculate(num1,min_sum - 1) - calculate(num2,min_sum - 1) - calculate(num1,max_sum) ans %= M return ans
33c8a6
a64afd
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: 0 <= i < j < nums.length nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) Return the number of nice pairs of indices. Since that number can be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [42,11,1,97] Output: 2 Explanation: The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. Example 2: Input: nums = [13,10,35,24,76] Output: 4   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9
class Solution(object): def countNicePairs(self, nums): """ :type nums: List[int] :rtype: int """ cs = {} for v in nums: v2 = int(str(v)[::-1]) # print v, v2 v2 -= v if v2 not in cs: cs[v2]=0 cs[v2]+=1 r = 0 for k in cs: c = cs[k] r += c*(c-1)/2 r %= 1000000007 return r
10502d
a64afd
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: 0 <= i < j < nums.length nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) Return the number of nice pairs of indices. Since that number can be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [42,11,1,97] Output: 2 Explanation: The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. Example 2: Input: nums = [13,10,35,24,76] Output: 4   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9
class Solution: def countNicePairs(self, nums: List[int]) -> int: def rev(x): return int(str(x)[::-1]) diffs = [n - rev(n) for n in nums] count = 0 counts = collections.Counter() for d in diffs: count += counts[d] counts[d] += 1 return count % (10 ** 9 + 7)
3e9f28
9e7008
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.   Example 1: Input: s1 = "ab", s2 = "ba" Output: 1 Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba". Example 2: Input: s1 = "abc", s2 = "bca" Output: 2 Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".   Constraints: 1 <= s1.length <= 20 s2.length == s1.length s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}. s2 is an anagram of s1.
class Solution: def dfs(self, x, cnt): if self.ans is not None and cnt >= self.ans: return if x == self.n: self.ans = cnt return if self.a[x] == self.b[x]: self.dfs(x + 1, cnt) else: for i in range(x + 1, self.n): if self.b[i] == self.a[x]: self.b[x], self.b[i] = self.b[i], self.b[x] self.dfs(x + 1, cnt + 1) self.b[x], self.b[i] = self.b[i], self.b[x] def kSimilarity(self, A, B): """ :type A: str :type B: str :rtype: int """ data = [[p, q] for (p, q) in zip(A, B) if p != q] self.a = [e[0] for e in data] self.b = [e[1] for e in data] self.n = len(self.a) self.ans = None self.dfs(0, 0) return self.ans
fead1b
9e7008
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.   Example 1: Input: s1 = "ab", s2 = "ba" Output: 1 Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba". Example 2: Input: s1 = "abc", s2 = "bca" Output: 2 Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".   Constraints: 1 <= s1.length <= 20 s2.length == s1.length s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}. s2 is an anagram of s1.
class Solution(object): def kSimilarity(self, A, B, dic = {}): """ :type A: str :type B: str :rtype: int """ if A == B: return 0 if (A, B) in dic: return dic[(A, B)] if A[0] == B[0]: ans = self.kSimilarity(A[1:], B[1:]) dic[(A, B)] = ans return ans else: ans = 0xffffffff for i in range(1, len(A)): if A[i] == B[0]: ta = A[1:] new = list(ta) new[i - 1] = A[0] ta = ''.join(new) ans = min(ans, 1 + self.kSimilarity(ta, B[1:])) dic[(A, B)] = ans return ans #121 #211
7db375
f7cc52
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1). In one move the snake can: Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c). Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1). Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1.   Example 1: Input: grid = [[0,0,0,0,0,1], [1,1,0,0,1,0],   [0,0,0,0,1,1],   [0,0,1,0,1,0],   [0,1,1,0,0,0],   [0,1,1,0,0,0]] Output: 11 Explanation: One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down]. Example 2: Input: grid = [[0,0,1,1,1,1],   [0,0,0,0,1,1],   [1,1,0,0,0,1],   [1,1,1,0,0,1],   [1,1,1,0,0,1],   [1,1,1,0,0,0]] Output: 9   Constraints: 2 <= n <= 100 0 <= grid[i][j] <= 1 It is guaranteed that the snake starts at empty cells.
class Solution(object): def minimumMoves(self, A): N = len(A) # N>= 2 R=C=N def neighbors(r, c, dire): # movement: if dire == RIGHT: # occing r,c and r,c+1 #slide right if c+2 < N and A[r][c+2] == 0: yield r, c+1, dire #slide down if r+1 < N and A[r+1][c] == 0 and A[r+1][c+1] == 0: yield r+1, c, dire # turn down if r+1 < N and A[r+1][c] == A[r+1][c+1] == 0: yield r, c, dire ^ 1 else: # down - occing r,c and r+1, c # slide right if c+1 < N and A[r][c+1] == A[r+1][c+1] == 0: yield r, c+1, dire # slide down if r+2 < N and A[r+2][c] == 0: yield r+1, c, dire # turn up if c+1 < N and A[r][c+1] == A[r+1][c+1] == 0: yield r, c, dire ^ 1 RIGHT, DOWN = 0, 1 Q = collections.deque([(0,0, RIGHT, 0)]) seen = {(0,0,RIGHT)} while Q: r,c,dire,d = Q.popleft() if r==N-1 and c==N-2 and dire==RIGHT: return d if r==N-2 and C==N-1 and dire==DOWN: return d for nei in neighbors(r, c, dire): if nei not in seen: seen.add(nei) Q.append(nei + (d+1,)) return -1
087e82
f7cc52
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1). In one move the snake can: Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c). Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1). Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1.   Example 1: Input: grid = [[0,0,0,0,0,1], [1,1,0,0,1,0],   [0,0,0,0,1,1],   [0,0,1,0,1,0],   [0,1,1,0,0,0],   [0,1,1,0,0,0]] Output: 11 Explanation: One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down]. Example 2: Input: grid = [[0,0,1,1,1,1],   [0,0,0,0,1,1],   [1,1,0,0,0,1],   [1,1,1,0,0,1],   [1,1,1,0,0,1],   [1,1,1,0,0,0]] Output: 9   Constraints: 2 <= n <= 100 0 <= grid[i][j] <= 1 It is guaranteed that the snake starts at empty cells.
from collections import deque class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: N = len(grid) que = deque([(0, 0, 0)]) used = [[[-1]*N for i in range(N)] for j in range(2)] used[0][0][0] = 0 while que: p, c, r = que.popleft() d = used[p][c][r] + 1 if p == 0: if r+2 < N and grid[c][r+2] == 0 and used[0][c][r+1] == -1: used[0][c][r+1] = d que.append((0, c, r+1)) if c+1 < N and grid[c+1][r] == grid[c+1][r+1] == 0 and used[0][c+1][r] == -1: used[0][c+1][r] = d que.append((0, c+1, r)) if c+1 < N and grid[c+1][r] == grid[c+1][r+1] == 0 and used[1][c][r] == -1: used[1][c][r] = d que.append((1, c, r)) else: if r+1 < N and grid[c][r+1] == grid[c+1][r+1] == 0 and used[1][c][r+1] == -1: used[1][c][r+1] = d que.append((1, c, r+1)) if c+2 < N and grid[c+2][r] == 0 and used[1][c+1][r] == -1: used[1][c+1][r] = d que.append((1, c+1, r)) if r+1 < N and grid[c][r+1] == grid[c+1][r+1] == 0 and used[0][c][r] == -1: used[0][c][r] = d que.append((0, c, r)) return used[0][N-1][N-2]
a61000
51f7d7
You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker. You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules: You will run k sessions and hire exactly one worker in each session. In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index. For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2]. In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process. If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index. A worker can only be chosen once. Return the total cost to hire exactly k workers.   Example 1: Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4 Output: 11 Explanation: We hire 3 workers in total. The total cost is initially 0. - In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2. - In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4. - In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers. The total hiring cost is 11. Example 2: Input: costs = [1,2,4,1], k = 3, candidates = 3 Output: 4 Explanation: We hire 3 workers in total. The total cost is initially 0. - In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers. - In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2. - In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4. The total hiring cost is 4.   Constraints: 1 <= costs.length <= 100000 1 <= costs[i] <= 100000 1 <= k, candidates <= costs.length
class Solution: def totalCost(self, costs: List[int], k: int, candidates: int) -> int: heap = [] hs = 0 he = len(costs) - 1 for i in range(candidates) : if he < hs : break heapq.heappush(heap, [costs[hs], hs]) hs += 1 if he < hs : break heapq.heappush(heap, [costs[he], he]) he -= 1 to_ret = 0 for _ in range(k) : v, pv = heapq.heappop(heap) to_ret += v if he < hs : continue elif pv < hs : heapq.heappush(heap, [costs[hs], hs]) hs += 1 else : assert pv > he heapq.heappush(heap, [costs[he], he]) he -= 1 return to_ret
098ae4
51f7d7
You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker. You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules: You will run k sessions and hire exactly one worker in each session. In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index. For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2]. In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process. If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index. A worker can only be chosen once. Return the total cost to hire exactly k workers.   Example 1: Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4 Output: 11 Explanation: We hire 3 workers in total. The total cost is initially 0. - In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2. - In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4. - In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers. The total hiring cost is 11. Example 2: Input: costs = [1,2,4,1], k = 3, candidates = 3 Output: 4 Explanation: We hire 3 workers in total. The total cost is initially 0. - In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers. - In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2. - In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4. The total hiring cost is 4.   Constraints: 1 <= costs.length <= 100000 1 <= costs[i] <= 100000 1 <= k, candidates <= costs.length
class Solution(object): def totalCost(self, costs, k, candidates): """ :type costs: List[int] :type k: int :type candidates: int :rtype: int """ l, r, q, t = 0, len(costs) - 1, [], 0 while l < candidates: heapq.heappush(q, [costs[l], l]) l += 1 while r >= len(costs) - candidates and r >= l: heapq.heappush(q, [costs[r], r]) r -= 1 while k > 0: k, t, c = k - 1, t + q[0][0], heapq.heappop(q)[1] if c < l and l <= r: heapq.heappush(q, [costs[l], l]) elif c > r and r >= l: heapq.heappush(q, [costs[r], r]) l, r = l + 1 if c < l and l <= r else l, r - 1 if c > r and r >= l else r return t
fa30b0
fd4f1b
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.   Example 1: Input: nums = [1,2,0,3,0], k = 1 Output: 3 Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0]. Example 2: Input: nums = [3,4,5,2,1,7,3,4,7], k = 3 Output: 3 Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7]. Example 3: Input: nums = [1,2,4,1,2,5,1,2,6], k = 3 Output: 3 Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].   Constraints: 1 <= k <= nums.length <= 2000 ​​​​​​0 <= nums[i] < 210
class Solution(object): def minChanges(self, A, k): n = len(A) s = [None] * k for i in range(k): s[i] = defaultdict(lambda: 0) for j in range(i, n, k): s[i][A[j]] += 1 def cost(i, e): return ceil((n - i) / k) - s[i][e] def mc(i): return min([cost(i, e) for e in s[i]]) total_min_cost = sum([mc(i) for i in range(k)]) u = total_min_cost + min([ceil((n - i) / k) - mc(i) for i in range(k)]) dp = {0: 0} for i in range(k): nd = defaultdict(lambda: float('inf')) for e in s[i]: for xor_pfx in dp: nc = cost(i, e) + dp[xor_pfx] if nc < u: new_pfx = xor_pfx ^ e nd[new_pfx] = min(nd[new_pfx], nc) dp = nd return dp[0] if 0 in dp else u
600f86
fd4f1b
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.   Example 1: Input: nums = [1,2,0,3,0], k = 1 Output: 3 Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0]. Example 2: Input: nums = [3,4,5,2,1,7,3,4,7], k = 3 Output: 3 Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7]. Example 3: Input: nums = [1,2,4,1,2,5,1,2,6], k = 3 Output: 3 Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].   Constraints: 1 <= k <= nums.length <= 2000 ​​​​​​0 <= nums[i] < 210
class Solution(object): def minChanges(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k == 1: return sum(min(1, x) for x in nums) c = [Counter() for _ in xrange(k)] for i, v in enumerate(nums): c[i%k][v] += 1 m = 1 << max(nums).bit_length() f = [float('-inf')] * m f[0] = 0 for i in xrange(k): ff = f[:] for x in xrange(m): for y, v in c[i].iteritems(): ff[x^y] = max(ff[x^y], f[x]+v) lb = max(f) for i in xrange(m): f[i] = max(ff[i], lb) return len(nums) - f[0]
34098c
5a20cd
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.   Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13 Output: 0 Explanation: One possible choice is to: - Choose 1 from the first row. - Choose 5 from the second row. - Choose 7 from the third row. The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. Example 2: Input: mat = [[1],[2],[3]], target = 100 Output: 94 Explanation: The best possible choice is to: - Choose 1 from the first row. - Choose 2 from the second row. - Choose 3 from the third row. The sum of the chosen elements is 6, and the absolute difference is 94. Example 3: Input: mat = [[1,2,9,8,7]], target = 6 Output: 1 Explanation: The best choice is to choose 7 from the first row. The absolute difference is 1.   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 70 1 <= mat[i][j] <= 70 1 <= target <= 800
class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: v = set([0]) for line in mat : vn = set() for n in line : for vt in v : vn.add(vt+n) v = vn mint = 1e99 for t in v : mint = min(mint, abs(t-target)) return mint
214e13
5a20cd
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.   Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13 Output: 0 Explanation: One possible choice is to: - Choose 1 from the first row. - Choose 5 from the second row. - Choose 7 from the third row. The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. Example 2: Input: mat = [[1],[2],[3]], target = 100 Output: 94 Explanation: The best possible choice is to: - Choose 1 from the first row. - Choose 2 from the second row. - Choose 3 from the third row. The sum of the chosen elements is 6, and the absolute difference is 94. Example 3: Input: mat = [[1,2,9,8,7]], target = 6 Output: 1 Explanation: The best choice is to choose 7 from the first row. The absolute difference is 1.   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 70 1 <= mat[i][j] <= 70 1 <= target <= 800
class Solution(object): def minimizeTheDifference(self, mat, target): """ :type mat: List[List[int]] :type target: int :rtype: int """ l, a, b = [False] * 5000, -10000, 10000 l[0] = True for row in mat: n = [False] * 5000 for i in range(0, 5000): if l[i]: for val in row: n[i + val] = True if i >= target: break l = n for i in range(target, 0, -1): if l[i]: a = i break for i in range(target, 5000): if l[i]: b = i break return min(target - a, b - target)
e00c06
e928fb
Given a positive integer num, return the smallest positive integer x whose multiplication of each digit equals num. If there is no answer or the answer is not fit in 32-bit signed integer, return 0. Example 1: Input: num = 48 Output: 68 Example 2: Input: num = 15 Output: 35 Constraints: 1 <= num <= 2^31 - 1
class Solution: def smallestFactorization(self, a): """ :type a: int :rtype: int """ if a == 1: return 1 x = "" MAX_INT = 2147483647 t = 9 while t > 1: if a%t == 0: x = str(t) + x a /= t else: t -= 1 if len(x) > 10: return 0 if a > 1: return 0 b = int(x) if b > MAX_INT: return 0 else: return b
5cf08a
e928fb
Given a positive integer num, return the smallest positive integer x whose multiplication of each digit equals num. If there is no answer or the answer is not fit in 32-bit signed integer, return 0. Example 1: Input: num = 48 Output: 68 Example 2: Input: num = 15 Output: 35 Constraints: 1 <= num <= 2^31 - 1
class Solution(object): def smallestFactorization(self, a): """ :type a: int :rtype: int """ if a == 0: return 0 lst = [] while a >= 10: flag = False for i in range(9, 1, -1): if a % i == 0: flag = True lst.append(str(i)) a /= i break if not flag: return 0 lst.append(str(a)) res = int(''.join(reversed(lst))) if res > 2 ** 31 - 1: return 0 else: return res
68d441
a9376e
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.   Example 1: Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -> Pacific Ocean   [0,4] -> Atlantic Ocean [1,3]: [1,3] -> [0,3] -> Pacific Ocean   [1,3] -> [1,4] -> Atlantic Ocean [1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean   [1,4] -> Atlantic Ocean [2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean   [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean [3,0]: [3,0] -> Pacific Ocean   [3,0] -> [4,0] -> Atlantic Ocean [3,1]: [3,1] -> [3,0] -> Pacific Ocean   [3,1] -> [4,1] -> Atlantic Ocean [4,0]: [4,0] -> Pacific Ocean [4,0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. Example 2: Input: heights = [[1]] Output: [[0,0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.   Constraints: m == heights.length n == heights[r].length 1 <= m, n <= 200 0 <= heights[r][c] <= 100000
class Solution(object): def walk(self,x,y,z,m,h,w,q,r): if x>=h or x < 0 or y>=w or y < 0: return if r[x][y]: return if m[x][y]<z: return r[x][y]=True q.append((x,y)) def bfs(self, m, h, w, q): r=[[False for a in range(w)] for b in range(h)] for a in q: r[a[0]][a[1]]=True a=0 while a < len(q): q0=q[a] a+=1 z=m[q0[0]][q0[1]] self.walk(q0[0]+1,q0[1],z,m,h,w,q,r) self.walk(q0[0]-1,q0[1],z,m,h,w,q,r) self.walk(q0[0],q0[1]+1,z,m,h,w,q,r) self.walk(q0[0],q0[1]-1,z,m,h,w,q,r) return r def pacificAtlantic(self, m): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ h=len(m) if h == 0: return [] w=len(m[0]) if w == 0: return [] q=[] for a in range(h): q.append([a,0]) for a in range(1,w): q.append([0,a]) m1=self.bfs(m,h,w,q) q=[] for a in range(h): q.append([a,w-1]) for a in range(0,w-1): q.append([h-1,a]) m2=self.bfs(m,h,w,q) ans=[] for a in range(h): for b in range(w): if m1[a][b] and m2[a][b]: ans.append([a,b]) return ans
d87db9
15a546
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.   Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3] Example 2: Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3]   Constraints: n == graph.length 1 <= n <= 12 0 <= graph[i].length < n graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. The input graph is always connected.
class Solution: def shortestPathLength(self, g): """ :type graph: List[List[int]] :rtype: int """ self.g = g self.n = len(g) # init self.d = [ [None] * self.n for _ in range(2 ** self.n) ] self.q = [] # source for x in range(self.n): self.push(1 << x, x, 0) head = 0 while head < len(self.q): bit, x, cur = self.q[head] head += 1 for y in self.g[x]: self.push(bit | (1 << y), y, cur + 1) ans = min( [self.d[(1 << self.n) - 1][x] for x in range(self.n)] ) return ans def push(self, bit, x, d): if self.d[bit][x] is None: self.d[bit][x] =d self.q.append( (bit, x, d) )
453f38
15a546
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.   Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3] Example 2: Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3]   Constraints: n == graph.length 1 <= n <= 12 0 <= graph[i].length < n graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. The input graph is always connected.
from itertools import combinations class Solution(object): def shortestPathLength(self, graph): """ :type graph: List[List[int]] :rtype: int """ n = len(graph) if n < 2: return 0 dsts = [[1e9 for i in xrange(n)] for j in xrange(n)] for i in xrange(n): dsts[i][i] = 0 for j in graph[i]: dsts[i][j] = 1 for k in xrange(n): for i in xrange(n): for j in xrange(n): dsts[i][j] = min(dsts[i][j], dsts[i][k] + dsts[k][j]) D = {} for i in xrange(n): D[(1<<i, i)] = 0 best_path = 1e9 for ss_size in xrange(2, n+1): for ss in combinations(range(n), ss_size): bitset = 0 for v in ss: bitset |= 1<<v for v in ss: bitset_1 = bitset ^ (1<<v) D[(bitset, v)] = min([D[(bitset_1, v1)] + dsts[v1][v] for v1 in ss if v1 != v]) if ss_size == n: best_path = min(best_path, D[(bitset, v)]) return best_path
bbd6b0
d12e86
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. 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 is palindromic if it reads the same forward and backward.   Example 1: Input: s = "leetcodecom" Output: 9 Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence. The product of their lengths is: 3 * 3 = 9. Example 2: Input: s = "bb" Output: 1 Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence. The product of their lengths is: 1 * 1 = 1. Example 3: Input: s = "accbcaxxcxx" Output: 25 Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence. The product of their lengths is: 5 * 5 = 25.   Constraints: 2 <= s.length <= 12 s consists of lowercase English letters only.
class Solution(object): def maxProduct(self, s): """ :type s: str :rtype: int """ n = len(s) palin = [False] * (1<<n) pc = [0] * (1<<n) for msk in xrange(1, 1<<n): pc[msk] = pc[msk&(msk-1)] + 1 t = ''.join(ch for i, ch in enumerate(s) if msk&(1<<i)) palin[msk] = t == t[::-1] def _dfs(pos, msk1, msk2): if pos == n: return pc[msk1]*pc[msk2] if palin[msk1] and palin[msk2] else 0 r = _dfs(pos+1, msk1, msk2) r = max(r, _dfs(pos+1, msk1^(1<<pos), msk2)) if msk1: r = max(r, _dfs(pos+1, msk1, msk2^(1<<pos))) return r return _dfs(0, 0, 0)
0de536
d12e86
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. 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 is palindromic if it reads the same forward and backward.   Example 1: Input: s = "leetcodecom" Output: 9 Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence. The product of their lengths is: 3 * 3 = 9. Example 2: Input: s = "bb" Output: 1 Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence. The product of their lengths is: 1 * 1 = 1. Example 3: Input: s = "accbcaxxcxx" Output: 25 Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence. The product of their lengths is: 5 * 5 = 25.   Constraints: 2 <= s.length <= 12 s consists of lowercase English letters only.
class Solution: def maxProduct(self, s: str) -> int: @cache def longestPalindromeSubseq(s): n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): dp[i][i] = 1 for j in range(i + 1, n): if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][n - 1] l = len(s) res = 0 for status in range(1, (1 << (l-1))): r1 = [] r2 = [] for i in range(l): if (status >> i) & 1: r1.append(s[i]) else: r2.append(s[i]) if status == 0: break res = max(res, longestPalindromeSubseq("".join(r1))* longestPalindromeSubseq("".join(r2))) return res
f18cb4
41a925
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k. In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking. Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.   Example 1: Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2 Output: 3 Explanation: The figure above represents the given graph. In the first semester, you can take courses 2 and 3. In the second semester, you can take course 1. In the third semester, you can take course 4. Example 2: Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2 Output: 4 Explanation: The figure above represents the given graph. In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester. In the second semester, you can take course 4. In the third semester, you can take course 1. In the fourth semester, you can take course 5.   Constraints: 1 <= n <= 15 1 <= k <= n 0 <= relations.length <= n * (n-1) / 2 relations[i].length == 2 1 <= prevCoursei, nextCoursei <= n prevCoursei != nextCoursei All the pairs [prevCoursei, nextCoursei] are unique. The given graph is a directed acyclic graph.
class Solution(object): def minNumberOfSemesters(self, n, dependencies, k): """ :type n: int :type dependencies: List[List[int]] :type k: int :rtype: int """ def length(c): if c in lens: return lens[c] if c not in deps: return lens.setdefault(c, 1) return lens.setdefault(c, max(length(dc) for dc in deps[c]) + 1) lens = collections.defaultdict(int) pres = collections.defaultdict(set) deps = collections.defaultdict(set) for c1, c2 in dependencies: pres[c2].add(c1) deps[c1].add(c2) canSelect = [(-length(c), c) for c in xrange(1, n + 1) if c not in pres] heapq.heapify(canSelect) ans = 0 while canSelect: ans += 1 select = [] for i in xrange(k): if canSelect: select.append(heapq.heappop(canSelect)[1]) for c in select: for dc in deps[c]: pres[dc].remove(c) if not pres[dc]: heapq.heappush(canSelect, (-length(dc), dc)) return ans
9b8c07
41a925
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k. In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking. Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.   Example 1: Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2 Output: 3 Explanation: The figure above represents the given graph. In the first semester, you can take courses 2 and 3. In the second semester, you can take course 1. In the third semester, you can take course 4. Example 2: Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2 Output: 4 Explanation: The figure above represents the given graph. In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester. In the second semester, you can take course 4. In the third semester, you can take course 1. In the fourth semester, you can take course 5.   Constraints: 1 <= n <= 15 1 <= k <= n 0 <= relations.length <= n * (n-1) / 2 relations[i].length == 2 1 <= prevCoursei, nextCoursei <= n prevCoursei != nextCoursei All the pairs [prevCoursei, nextCoursei] are unique. The given graph is a directed acyclic graph.
from functools import lru_cache memo = lru_cache(None) class Solution: def minNumberOfSemesters(self, N, edges, K): for i in range(len(edges)): edges[i][0] -= 1 edges[i][1] -= 1 indeg = [0] * (N) reqs = [0 for _ in range(N)] for u, v in edges: indeg[v] += 1 reqs[v] += 1 << u starts = [u for u in range(N) if indeg[u] == 0] TARGET = (1 << N) - 1 @memo def dp(mask): if mask == TARGET: return 0 cands = [] for u in range(N): bit = 1 << u if mask & bit == 0: if mask & reqs[u] == reqs[u]: cands.append(u) if len(cands) <= K: mask2 = mask for u in cands: mask2 |= 1 << u return 1 + dp(mask2) else: ans = 10000 for choice in itertools.combinations(cands, K): mask2 = mask for u in choice: mask2 |= 1 << u bns = 1 + dp(mask2) if bns<ans:ans= bns return ans return dp(0)
fccb31
0b66f1
There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots. The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially. All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving. At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots. Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired. Note that All robots move at the same speed. If two robots move in the same direction, they will never collide. If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other. If a robot passes by a factory that reached its limits, it crosses it as if it does not exist. If the robot moved from a position x to a position y, the distance it moved is |y - x|.   Example 1: Input: robot = [0,4,6], factory = [[2,2],[6,2]] Output: 4 Explanation: As shown in the figure: - The first robot at position 0 moves in the positive direction. It will be repaired at the first factory. - The second robot at position 4 moves in the negative direction. It will be repaired at the first factory. - The third robot at position 6 will be repaired at the second factory. It does not need to move. The limit of the first factory is 2, and it fixed 2 robots. The limit of the second factory is 2, and it fixed 1 robot. The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4. Example 2: Input: robot = [1,-1], factory = [[-2,1],[2,1]] Output: 2 Explanation: As shown in the figure: - The first robot at position 1 moves in the positive direction. It will be repaired at the second factory. - The second robot at position -1 moves in the negative direction. It will be repaired at the first factory. The limit of the first factory is 1, and it fixed 1 robot. The limit of the second factory is 1, and it fixed 1 robot. The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.   Constraints: 1 <= robot.length, factory.length <= 100 factory[j].length == 2 -10^9 <= robot[i], positionj <= 10^9 0 <= limitj <= robot.length The input will be generated such that it is always possible to repair every robot.
class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: robot = sorted(robot) factory = sorted(factory) @functools.lru_cache(None) def solve(pr = 0, pf = 0, tf = 0) : if pr == len(robot) : return 0 if pf == len(factory) : return 1e99 if tf == factory[pf][1] : return solve(pr, pf+1, 0) to_ret = abs(robot[pr]-factory[pf][0]) + solve(pr+1, pf, tf+1) to_ret = min(to_ret, solve(pr, pf+1, 0)) return to_ret return solve()
18189d
0b66f1
There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots. The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially. All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving. At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots. Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired. Note that All robots move at the same speed. If two robots move in the same direction, they will never collide. If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other. If a robot passes by a factory that reached its limits, it crosses it as if it does not exist. If the robot moved from a position x to a position y, the distance it moved is |y - x|.   Example 1: Input: robot = [0,4,6], factory = [[2,2],[6,2]] Output: 4 Explanation: As shown in the figure: - The first robot at position 0 moves in the positive direction. It will be repaired at the first factory. - The second robot at position 4 moves in the negative direction. It will be repaired at the first factory. - The third robot at position 6 will be repaired at the second factory. It does not need to move. The limit of the first factory is 2, and it fixed 2 robots. The limit of the second factory is 2, and it fixed 1 robot. The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4. Example 2: Input: robot = [1,-1], factory = [[-2,1],[2,1]] Output: 2 Explanation: As shown in the figure: - The first robot at position 1 moves in the positive direction. It will be repaired at the second factory. - The second robot at position -1 moves in the negative direction. It will be repaired at the first factory. The limit of the first factory is 1, and it fixed 1 robot. The limit of the second factory is 1, and it fixed 1 robot. The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.   Constraints: 1 <= robot.length, factory.length <= 100 factory[j].length == 2 -10^9 <= robot[i], positionj <= 10^9 0 <= limitj <= robot.length The input will be generated such that it is always possible to repair every robot.
class Solution(object): def minimumTotalDistance(self, robot, factory): """ :type robot: List[int] :type factory: List[List[int]] :rtype: int """ a, p, s, m, f, n, t = [float('inf')], [0] * len(factory), 0, [0] * len(factory), [[0] * len(robot) for _ in factory], [[None] * len(factory) for _ in robot], 0 def u(v, f): if v == len(robot): return 0 elif f == len(factory) or m[f] < len(robot) - v: return a[0] elif n[v][f] != None: return n[v][f] l, r = 0, min(len(robot) - v, factory[f][1]) while r - l > 1: r = (l + r) / 2 if g(v, f, (l + r) / 2) < g(v, f, (l + r) / 2 + 1) else r l = l if g(v, f, (l + r) / 2) < g(v, f, (l + r) / 2 + 1) else (l + r) / 2 n[v][f] = min(g(v, f, l), g(v, f, r)) return n[v][f] def g(r, g, v): return a[0] if u(r + v, g + 1) == a[0] else (f[g][r + v - 1] if r + v else 0) - (f[g][r - 1] if r else 0) + u(r + v, g + 1) robot.sort() factory.sort() for i in range(len(factory) - 1, -1, -1): s, m[i] = s + factory[i][1], s + factory[i][1] for i in range(len(factory)): s = 0 for j in range(len(robot)): s, f[i][j] = s + abs(robot[j] - factory[i][0]), s + abs(robot[j] - factory[i][0]) for i in range(len(p)): t, p[i] = t + factory[i][1], t + factory[i][1] return u(0, 0)
a7ab03
db039b
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1. The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.   Example 1: Input: grid = [[1,0,1],[0,0,0],[1,0,1]] Output: 2 Explanation: The cell (1, 1) is as far as possible from all the land with distance 2. Example 2: Input: grid = [[1,0,0],[0,0,0],[0,0,0]] Output: 4 Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.   Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
class Solution: def maxDistance(self, grid: List[List[int]]) -> int: r, c = len(grid), len(grid[0]) rot = list() for i in range(r): for j in range(c): if grid[i][j] == 1: rot.append((i, j, 0)) d = [(0,1), (0,-1), (1,0), (-1,0)] res = 0 while rot: i, j, res = rot.pop(0) for xd, yd in d: x = i + xd y = j + yd if 0 <= x < r and 0 <= y < c and grid[x][y] == 0: grid[x][y] = grid[xd][yd] + 1 rot.append((x, y, res+1)) return res if res != 0 else -1
4b7126
db039b
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1. The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.   Example 1: Input: grid = [[1,0,1],[0,0,0],[1,0,1]] Output: 2 Explanation: The cell (1, 1) is as far as possible from all the land with distance 2. Example 2: Input: grid = [[1,0,0],[0,0,0],[0,0,0]] Output: 4 Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.   Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
from collections import deque class Solution(object): def maxDistance(self, matrix): """ :type grid: List[List[int]] :rtype: int """ queue = deque() v = [] ans = [] for i in range(len(matrix)): tmp = [] tmp2 = [] for j in range(len(matrix[0])): tmp.append(True) tmp2.append(0) v.append(tmp) ans.append(tmp2) flag = True fflag = True for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1: flag = False queue.append([i,j]) v[i][j] = False else: fflag = False if flag or fflag: return -1 directions = [[0,1],[0,-1],[1,0],[-1,0]] while queue: tmp = queue.popleft() #print tmp x = tmp[0] y = tmp[1] for d in directions: tx = x+d[0] ty = y+d[1] if tx<0 or ty<0 or tx>=len(matrix) or ty>=len(matrix[0]) or not v[tx][ty]: continue ans[tx][ty] = ans[x][y] + 1 queue.append([tx,ty]) v[tx][ty] = False res = 0 for r in ans: for n in r: res = max(n, res) return res
667145
974a29
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import math def dijkstra(source, getNbr, isDest=None): dest = None dist = {} queue = [] heappush(queue, (0, source)) while queue: # Grab current shortest that isn't finalized yet minDist, minNode = heappop(queue) if minNode in dist: # Finalized with something shorter before, continue assert dist[minNode] <= minDist continue # Finalize the current shortest dist[minNode] = minDist # Check if it's already at the destination if isDest and isDest(minNode): dest = minNode break # Add all neighbors that still needs to be processed for nbr, weight in getNbr(minNode): if nbr not in dist: heappush(queue, (minDist + weight, nbr)) else: assert minDist + weight >= dist[nbr] return dist, dest class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: g = defaultdict(lambda: defaultdict(float)) for (u, v), w in zip(edges, succProb): g[u][v] = -math.log(w) g[v][u] = -math.log(w) def getNbr(u): ret = [] for v, w in g[u].items(): ret.append((v, w)) #print('nbr of u', u, ret) return ret def isDest(u): return u == end dist, dest = dijkstra(start, getNbr, isDest) if dest not in dist: return 0.0 return math.e ** -dist[dest]
c48ef0
974a29
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict from heapq import heappush, heappop from math import exp, log class Solution(object): def maxProbability(self, n, edges, succProb, start, end): """ :type n: int :type edges: List[List[int]] :type succProb: List[float] :type start: int :type end: int :rtype: float """ adj = defaultdict(list) for i in xrange(len(edges)): if succProb[i] == 0: continue u, v = edges[i] w = -log(succProb[i]) adj[u].append((v, w)) adj[v].append((u, w)) dst = [float('inf')]*n q = [] def consider(du, u): if du >= dst[u]: return dst[u] = du heappush(q, (du, u)) consider(0, start) seen = set() while q: du, u = heappop(q) if u in seen: continue seen.add(u) for v, w in adj[u]: consider(du+w, v) return exp(-dst[end])
b7a102
326f34
You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, a: List[int], target: int) -> int: n = len(a) a = [0] + a s = {} cs = 0 inf = 10**9 b = [inf] * (n + 1) res = inf for i in range(n + 1): cs += a[i] if i: b[i] = min(b[i-1], b[i]) j = s.get(cs - target, None) if j is not None: b[i] = min(b[i], i - j) res = min(res, i - j + b[j]) s[cs] = i return res if res != inf else -1
825fb5
326f34
You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution(object): def minSumOfLengths(self, A, T): """ :type arr: List[int] :type target: int :rtype: int """ P = [0] for x in A: P.append(P[-1] + x) intervals = [] seen = {} INF = float('inf') lengths = [INF] * (len(P) + 1) lengths2 = [INF] * (len(P) + 1) for j, p in enumerate(P): if p - T in seen: i = seen[p - T] length = j - i lengths[j] = length lengths2[i] = length seen[p] = j #print("!", lengths) prefix = [INF] * (len(P) + 1) m = INF for i in xrange(len(P) + 1): l = lengths[i] if l < m: m = l prefix[i] = m suffix = [INF] * (len(P) + 1) m = INF for i in xrange(len(P), -1, -1): l = lengths2[i] if l < m: m = l suffix[i] = m ans = INF for i in range(len(P)): ans = min(ans, prefix[i] + suffix[i]) if ans == INF: return -1 return ans
e73fb2
2ef436
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array.   Example 1: Input: nums = [7,2,5,10,8], k = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1,2,3,4,5], k = 2 Output: 9 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000000 1 <= k <= min(50, nums.length)
class Solution(object): def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ l = 0 r = sum(nums) while l <= r: mid = (l + r) / 2 if self.check(nums, m, mid): r = mid - 1 else: l = mid + 1 return l def check(self, nums, m, most): s = 0 for n in nums: if n > most: return False s += n if s > most: m -= 1 s = n return m > 0
facb5b
db4480
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.   Example 1: Input: expression = "{a,b}{c,{d,e}}" Output: ["ac","ad","ae","bc","bd","be"] Example 2: Input: expression = "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer.   Constraints: 1 <= expression.length <= 60 expression[i] consists of '{', '}', ','or lowercase English letters. The given expression represents a set of words based on the grammar given in the description.
from itertools import product class Solution(object): def braceExpansionII(self, expression): """ :type expression: str :rtype: List[str] """ n = len(expression) s = [] m = {} for i, c in enumerate(expression): if c == '{': s.append(i) elif c == '}': m[s.pop()] = i def poss(a, b): if a + 1 == b: return expression[a] r = set() curr = [] while a < b: if expression[a] == '{': curr.append(poss(a+1, m[a])) a = m[a]+1 continue if expression[a] == ',': r.update(''.join(t) for t in product(*curr)) curr = [] a += 1 continue curr.append(expression[a]) a += 1 r.update(''.join(t) for t in product(*curr)) return r return sorted(poss(0, n))
2bbf3a
db4480
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.   Example 1: Input: expression = "{a,b}{c,{d,e}}" Output: ["ac","ad","ae","bc","bd","be"] Example 2: Input: expression = "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer.   Constraints: 1 <= expression.length <= 60 expression[i] consists of '{', '}', ','or lowercase English letters. The given expression represents a set of words based on the grammar given in the description.
def gen (gram): if ',' in gram: choices = [[]] for elem in gram: if elem == ',': choices.append ([]) else: choices[-1].append (gen (elem)) return ['_choice', choices] elif type (gram) is list: return [gen (elem) for elem in gram] else: return gram def walk (code): if type (code) is str: yield code elif type (code) is list and len (code) > 0 and code[0] == '_choice': for choice in code[1]: for answer in walk (choice): yield answer else: if len (code) == 0: yield '' elif len (code) == 1: for _ in walk (code[0]): yield _ else: head = code[0] tail = code[1:] for part1 in walk (head): for part2 in walk (tail): yield part1 + part2 class Solution: def braceExpansionII(self, expression): gram = [[]] for char in expression: if char == ',': gram[-1].append (',') elif char == '{': gram.append ([]) elif char == '}': gram[-2].append (gram[-1]) gram.pop () else: gram[-1].append (char) code = gen (gram) ans = set () for string in walk (code): ans.add (string) ans = list (ans) ans.sort () return ans
273118
331ba9
You are given an integer array nums of length n where nums is a permutation of the integers in the range [1, n]. You are also given a 2D integer array sequences where sequences[i] is a subsequence of nums. Check if nums is the shortest possible and the only supersequence. The shortest supersequence is a sequence with the shortest length and has all sequences[i] as subsequences. There could be multiple valid supersequences for the given array sequences. For example, for sequences = [[1,2],[1,3]], there are two shortest supersequences, [1,2,3] and [1,3,2]. While for sequences = [[1,2],[1,3],[1,2,3]], the only shortest supersequence possible is [1,2,3]. [1,2,3,4] is a possible supersequence but not the shortest. Return true if nums is the only shortest supersequence for sequences, or false otherwise. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [1,2,3], sequences = [[1,2],[1,3]] Output: false Explanation: There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [1,2,3] and [1,3,2]. The sequence [1,3] is a subsequence of both: [1,2,3] and [1,3,2]. Since nums is not the only shortest supersequence, we return false. Example 2: Input: nums = [1,2,3], sequences = [[1,2]] Output: false Explanation: The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [1,2]. Since nums is not the shortest supersequence, we return false. Example 3: Input: nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] Output: true Explanation: The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [1,2,3]. The sequence [1,3] is a subsequence of it: [1,2,3]. The sequence [2,3] is a subsequence of it: [1,2,3]. Since nums is the only shortest supersequence, we return true. Constraints: n == nums.length 1 <= n <= 10000 nums is a permutation of all the integers in the range [1, n]. 1 <= sequences.length <= 10000 1 <= sequences[i].length <= 10000 1 <= sum(sequences[i].length) <= 100000 1 <= sequences[i][j] <= n All the arrays of sequences are unique. sequences[i] is a subsequence of nums.
class Solution(object): def sequenceReconstruction(self, org, seqs): n = len(org) r = [0 for i in range(n)] for i in range(n): r[org[i]-1] = i #print r for i in seqs: for j in range(len(i)): if i[j] > n or i[j] < 1: return False i[j] = r[i[j]-1] for i in range(n): r[i] = 0 for s in seqs: ns = len(s) for i in range(ns): if i < ns - 1: if s[i] >= s[i+1]: return False if s[i]+1 == s[i+1]: r[s[i]] = 2 if r[s[i]] == 0: r[s[i]] = 1 for i in range(n): if i < n-1: if r[i] != 2: return False else: if r[i] != 1: return False return True
42cd61
9f67a6
You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times: Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query. Remove the last element from the current array nums. Return an array answer, where answer[i] is the answer to the ith query.   Example 1: Input: nums = [0,1,1,3], maximumBit = 2 Output: [0,3,2,3] Explanation: The queries are answered as follows: 1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = [0], k = 3 since 0 XOR 3 = 3. Example 2: Input: nums = [2,3,4,7], maximumBit = 3 Output: [5,2,6,5] Explanation: The queries are answered as follows: 1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = [2], k = 5 since 2 XOR 5 = 7. Example 3: Input: nums = [0,1,2,2,5,7], maximumBit = 3 Output: [4,3,6,4,6,7]   Constraints: nums.length == n 1 <= n <= 100000 1 <= maximumBit <= 20 0 <= nums[i] < 2maximumBit nums​​​ is sorted in ascending order.
class Solution: def getMaximumXor(self, nums: List[int], ma: int) -> List[int]: n=len(nums) for i in range(1,n): nums[i]^=nums[i-1] ans=[] for i in range(n-1,-1,-1): cur=nums[i] t=0 for i in range(ma-1,-1,-1): if not cur&1<<i: t^=1<<i ans.append(t) return ans
113909
9f67a6
You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times: Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query. Remove the last element from the current array nums. Return an array answer, where answer[i] is the answer to the ith query.   Example 1: Input: nums = [0,1,1,3], maximumBit = 2 Output: [0,3,2,3] Explanation: The queries are answered as follows: 1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = [0], k = 3 since 0 XOR 3 = 3. Example 2: Input: nums = [2,3,4,7], maximumBit = 3 Output: [5,2,6,5] Explanation: The queries are answered as follows: 1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = [2], k = 5 since 2 XOR 5 = 7. Example 3: Input: nums = [0,1,2,2,5,7], maximumBit = 3 Output: [4,3,6,4,6,7]   Constraints: nums.length == n 1 <= n <= 100000 1 <= maximumBit <= 20 0 <= nums[i] < 2maximumBit nums​​​ is sorted in ascending order.
class Solution(object): def getMaximumXor(self, nums, maximumBit): n = len(nums) tot = (1<<maximumBit) - 1 res = [] for i in nums: tot ^= i i = n-1 while i>=0: res.append(tot) tot ^= nums[i] i-=1 return res
08813c
908843
The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0.   Example 1: Input: candidates = [16,17,71,62,12,24,14] Output: 4 Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0. The size of the combination is 4. It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. Note that more than one combination may have the largest size. For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0. Example 2: Input: candidates = [8,8] Output: 2 Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0. The size of the combination is 2, so we return 2.   Constraints: 1 <= candidates.length <= 100000 1 <= candidates[i] <= 10^7
class Solution(object): def largestCombination(self, candidates): """ :type candidates: List[int] :rtype: int """ a, r = [0] * 30, 0 for n in candidates: v, i = 1, 0 while i < 30 and v <= n: a[i], r, v, i = a[i] + (1 if v & n else 0), max(r, a[i] + (1 if v & n else 0)) if v & n else r, v << 1, i + 1 return r
931fe9
908843
The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0.   Example 1: Input: candidates = [16,17,71,62,12,24,14] Output: 4 Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0. The size of the combination is 4. It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. Note that more than one combination may have the largest size. For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0. Example 2: Input: candidates = [8,8] Output: 2 Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0. The size of the combination is 2, so we return 2.   Constraints: 1 <= candidates.length <= 100000 1 <= candidates[i] <= 10^7
class Solution: def largestCombination(self, candidates: List[int]) -> int: ans = 0 for i in range(30): ans = max(ans, len([c for c in candidates if (c & (1 << i)) > 0])) return ans
96d5b6
fdcf46
You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.   Example 1: Input: nums = [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5. Example 2: Input: nums = [3,1] Output: false   Constraints: 1 <= nums.length <= 30 0 <= nums[i] <= 10000
class Solution(object): def splitArraySameAverage(self, A): """ :type A: List[int] :rtype: bool """ if len(A) < 2: return False A.sort() total = sum(A) for l1 in range(1, len(A) / 2 + 1): l2 = len(A) - l1 if (l1 * total) % (l1 + l2) != 0: continue s1 = (l1 * total) / (l1 + l2) if self.dfs(A, s1, l1, 0, 0, 0): return True return False def dfs(self, A, s1, l1, p, curl, curs): if curl == l1: if curs == s1: return True else: return False if curs > s1: return False if len(A) - p < l1 - curl: return False if self.dfs(A, s1, l1, p + 1, curl + 1, curs + A[p]): return True if self.dfs(A, s1, l1, p + 1, curl, curs): return True return False
92920c
fdcf46
You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.   Example 1: Input: nums = [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5. Example 2: Input: nums = [3,1] Output: false   Constraints: 1 <= nums.length <= 30 0 <= nums[i] <= 10000
class Solution: def splitArraySameAverage(self, A): """ :type A: List[int] :rtype: bool """ p=[2,3,5,7,11,13,17,19,23,29] A.sort() n=len(A) s=sum(A) if n in p and s%n!=0: return False avg=s/n def find(cnt,tot,start): if tot<0: return False if cnt==0: return tot==0 for i in range(start,n): if tot>=A[i] and find(cnt-1,tot-A[i],i+1): return True return False for i in range(1,n): if (s*i)%n==0: if find(i,s*i/n,0): return True return False
0bf46a
e36f5a
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".   Example 1: Input: senate = "RD" Output: "Radiant" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. Example 2: Input: senate = "RDD" Output: "Dire" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.   Constraints: n == senate.length 1 <= n <= 10000 senate[i] is either 'R' or 'D'.
class Solution(object): def predictPartyVictory(self, senate): """ :type senate: str :rtype: str """ senate = list(senate) stack = [] while len(senate)>1 and len(set(senate))>1: i = 0 while i<len(senate): if len(stack) == 0: stack.append(senate[i]) i += 1 else: if senate[i] == stack[-1]: stack.append(senate[i]) i += 1 else: stack.pop() senate.pop(i) if senate[0] == 'R': return "Radiant" else: return "Dire"
b2ac52
e36f5a
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".   Example 1: Input: senate = "RD" Output: "Radiant" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. Example 2: Input: senate = "RDD" Output: "Dire" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.   Constraints: n == senate.length 1 <= n <= 10000 senate[i] is either 'R' or 'D'.
class Solution: def predictPartyVictory(self, senate): """ :type senate: str :rtype: str """ Char = senate[0] A = 0 B = 0 for i in range(len(senate)): c = senate[i] if c == Char: A += 1 B += 1 else: B -= 1 if B == -1: break if B == -1: return self.predictPartyVictory(senate[i:] + Char*A) else: if Char == "R": return "Radiant" else: return "Dire"
51d074
d3cf89
Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.   Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid.   Constraints: 1 <= s.length <= 100000 s[i] is either'(' , ')', or lowercase English letter.
class Solution(object): def minRemoveToMakeValid(self, s): """ :type s: str :rtype: str """ r = [False]*len(s) h = 0 t = [] for i, c in enumerate(s): if c == '(': t.append(i) elif c == ')': if t: t.pop() else: r[i] = True while t: r[t.pop()] = True return ''.join(c for i,c in enumerate(s) if not r[i])
54120f
d3cf89
Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.   Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid.   Constraints: 1 <= s.length <= 100000 s[i] is either'(' , ')', or lowercase English letter.
class Solution: def minRemoveToMakeValid(self, s: str) -> str: L=[] ct=0 drop_set=set() for i in range(len(s)): if s[i]=="(": ct+=1 L.append(i) elif s[i]==")": if ct>0: ct-=1 L.pop() else: drop_set.add(i) for i in L: drop_set.add(i) L=[] for i in range(len(s)): if i not in drop_set: L.append(s[i]) return "".join(L)
28b8ba
3669e6
Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows. If there is no common element, return -1. Example 1: Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]] Output: 5 Example 2: Input: mat = [[1,2,3],[2,3,4],[2,3,5]] Output: 2 Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 500 1 <= mat[i][j] <= 10000 mat[i] is sorted in strictly increasing order.
class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: s=set(mat[0]) for i in range(1,len(mat)): s = s.intersection(mat[i]) if s: return min(s) else: return -1
dcb5ef
3669e6
Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows. If there is no common element, return -1. Example 1: Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]] Output: 5 Example 2: Input: mat = [[1,2,3],[2,3,4],[2,3,5]] Output: 2 Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 500 1 <= mat[i][j] <= 10000 mat[i] is sorted in strictly increasing order.
class Solution(object): def smallestCommonElement(self, A): A = map(set, A) work = A.pop() for row in A: work &= row return min(work) if work else -1
558761
5abf60
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 12 Explanation: There are 12 possible way to paint the grid as shown. Example 2: Input: n = 5000 Output: 30228214   Constraints: n == grid.length 1 <= n <= 5000
class Solution(object): def numOfWays(self, n): MOD = 10**9 + 7 dp = [0] * 27 for a in range(3): for b in range(3): for c in range(3): if a != b != c: code = 9 * a + 3 * b + c dp[code] = 1 for _ in xrange(n-1): dp2 = [0] * 27 for state1 in xrange(27): a0 = state1 // 9 b0 = state1 % 9 // 3 c0 = state1 % 3 for a in xrange(3): if a != a0: for b in xrange(3): if b0 != b != a: for c in xrange(3): if b != c != c0: state2 = 9 *a + 3*b + c dp2[state2] += dp[state1] dp2[state2] %= MOD dp = dp2 return sum(dp) % MOD
4ec83f
5abf60
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 12 Explanation: There are 12 possible way to paint the grid as shown. Example 2: Input: n = 5000 Output: 30228214   Constraints: n == grid.length 1 <= n <= 5000
from functools import lru_cache class Solution: def numOfWays(self, n: int) -> int: mod = 10 ** 9 + 7 @lru_cache(None) def go(index, px, py, pz): if index == n: return 1 total = 0 for x in range(3): if x != px: for y in range(3): if y != py and y != x: for z in range(3): if z != pz and y != z: total = (total + go(index + 1, x, y, z)) % mod return total % mod total = 0 for x in range(3): for y in range(3): if x != y: for z in range(3): if y != z: total += go(1, x, y, z) % mod return total % mod
e690d9
32f46b
You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. For example, the GCD of the sequence [4,6,16] is 2. 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]. Return the number of different GCDs among all non-empty subsequences of nums.   Example 1: Input: nums = [6,10,3] Output: 5 Explanation: The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. Example 2: Input: nums = [5,15,40,5,6] Output: 7   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 2 * 100000
class Solution: def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int: ans=0 dic={} def gcd(x,y): if y==0: return x return gcd(y,x%y) for x in nums: dic[x]=1 for i in range(1,2*(10**5)+1): j=(2*(10**5))//i*i temps=-1 while(j>=i): if j not in dic: j=j-i continue if j in dic: if temps==-1: temps=j temps=gcd(temps,j) if temps==i: break j=j-i if temps==i: ans=ans+1 return ans
8b9736
8ff733
You are given two 0-indexed arrays nums and cost consisting each of n positive integers. You can do the following operation any number of times: Increase or decrease any element of the array nums by 1. The cost of doing one operation on the ith element is cost[i]. Return the minimum total cost such that all the elements of the array nums become equal.   Example 1: Input: nums = [1,3,5,2], cost = [2,3,1,14] Output: 8 Explanation: We can make all the elements equal to 2 in the following way: - Increase the 0th element one time. The cost is 2. - Decrease the 1st element one time. The cost is 3. - Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3. The total cost is 2 + 3 + 3 = 8. It can be shown that we cannot make the array equal with a smaller cost. Example 2: Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3] Output: 0 Explanation: All the elements are already equal, so no operations are needed.   Constraints: n == nums.length == cost.length 1 <= n <= 100000 1 <= nums[i], cost[i] <= 1000000
class Solution: def minCost(self, nums: List[int], cost: List[int]) -> int: order = sorted(range(len(nums)), key=nums.__getitem__) nums = [nums[i] for i in order] cost = [cost[i] for i in order] front = [0] * len(nums) curr = 0 for i in range(len(nums) - 1): curr += cost[i] front[i + 1] = front[i] + curr * (nums[i + 1] - nums[i]) sol = front[len(nums) - 1] curr, back = cost[-1], 0 for i in reversed(range(len(nums) - 1)): back += curr * (nums[i + 1] - nums[i]) sol = min(sol, front[i] + back) curr += cost[i] return sol
4bbc9c
8ff733
You are given two 0-indexed arrays nums and cost consisting each of n positive integers. You can do the following operation any number of times: Increase or decrease any element of the array nums by 1. The cost of doing one operation on the ith element is cost[i]. Return the minimum total cost such that all the elements of the array nums become equal.   Example 1: Input: nums = [1,3,5,2], cost = [2,3,1,14] Output: 8 Explanation: We can make all the elements equal to 2 in the following way: - Increase the 0th element one time. The cost is 2. - Decrease the 1st element one time. The cost is 3. - Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3. The total cost is 2 + 3 + 3 = 8. It can be shown that we cannot make the array equal with a smaller cost. Example 2: Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3] Output: 0 Explanation: All the elements are already equal, so no operations are needed.   Constraints: n == nums.length == cost.length 1 <= n <= 100000 1 <= nums[i], cost[i] <= 1000000
class Solution(object): def minCost(self, nums, cost): """ :type nums: List[int] :type cost: List[int] :rtype: int """ a, c, t, r, s = [], 0, 0, 0, 0 for i in range(len(nums)): a.append([nums[i], cost[i]]) a.sort() for i in range(len(nums) - 1, -1, -1): t, c, r, s = t + a[i][1], c + (a[i][0] - a[0][0]) * a[i][1], r + (a[i][0] - a[0][0]) * a[i][1], a[0][1] for i in range(1, len(nums)): c, r, s = c + s * (a[i][0] - a[i - 1][0]) - (t - s) * (a[i][0] - a[i - 1][0]), min(r, c + s * (a[i][0] - a[i - 1][0]) - (t - s) * (a[i][0] - a[i - 1][0])), s + a[i][1] return r
ffdb39
a5bcd2
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.   Example 1: Input: encodedText = "ch ie pr", rows = 3 Output: "cipher" Explanation: This is the same example described in the problem description. Example 2: Input: encodedText = "iveo eed l te olc", rows = 4 Output: "i love leetcode" Explanation: The figure above denotes the matrix that was used to encode originalText. The blue arrows show how we can find originalText from encodedText. Example 3: Input: encodedText = "coding", rows = 1 Output: "coding" Explanation: Since there is only 1 row, both originalText and encodedText are the same.   Constraints: 0 <= encodedText.length <= 1000000 encodedText consists of lowercase English letters and ' ' only. encodedText is a valid encoding of some originalText that does not have trailing spaces. 1 <= rows <= 1000 The testcases are generated such that there is only one possible originalText.
class Solution(object): def decodeCiphertext(self, encodedText, rows): """ :type encodedText: str :type rows: int :rtype: str """ r = [] cols = len(encodedText) // rows for i in xrange(cols): for j in xrange(rows): if i + j < cols: r.append(encodedText[j*cols+i+j]) return ''.join(r).rstrip()
03c552
a5bcd2
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.   Example 1: Input: encodedText = "ch ie pr", rows = 3 Output: "cipher" Explanation: This is the same example described in the problem description. Example 2: Input: encodedText = "iveo eed l te olc", rows = 4 Output: "i love leetcode" Explanation: The figure above denotes the matrix that was used to encode originalText. The blue arrows show how we can find originalText from encodedText. Example 3: Input: encodedText = "coding", rows = 1 Output: "coding" Explanation: Since there is only 1 row, both originalText and encodedText are the same.   Constraints: 0 <= encodedText.length <= 1000000 encodedText consists of lowercase English letters and ' ' only. encodedText is a valid encoding of some originalText that does not have trailing spaces. 1 <= rows <= 1000 The testcases are generated such that there is only one possible originalText.
class Solution: def decodeCiphertext(self, encodedText: str, rows: int) -> str: assert len(encodedText) % rows == 0 nt = len(encodedText) // rows table = [] for i in range(rows) : table.append(encodedText[nt*i:nt*i+nt]) to_ret = '' for i in range(nt) : x, y = 0, i while x < rows and y < nt : to_ret += table[x][y] x += 1 y += 1 return to_ret.rstrip()
e46c7b
0c9eeb
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. For example, when num = "5489355142": The 1st smallest wonderful integer is "5489355214". The 2nd smallest wonderful integer is "5489355241". The 3rd smallest wonderful integer is "5489355412". The 4th smallest wonderful integer is "5489355421". Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth smallest wonderful integer exists.   Example 1: Input: num = "5489355142", k = 4 Output: 2 Explanation: The 4th smallest wonderful number is "5489355421". To get this number: - Swap index 7 with index 8: "5489355142" -> "5489355412" - Swap index 8 with index 9: "5489355412" -> "5489355421" Example 2: Input: num = "11112", k = 4 Output: 4 Explanation: The 4th smallest wonderful number is "21111". To get this number: - Swap index 3 with index 4: "11112" -> "11121" - Swap index 2 with index 3: "11121" -> "11211" - Swap index 1 with index 2: "11211" -> "12111" - Swap index 0 with index 1: "12111" -> "21111" Example 3: Input: num = "00123", k = 1 Output: 1 Explanation: The 1st smallest wonderful number is "00132". To get this number: - Swap index 3 with index 4: "00123" -> "00132"   Constraints: 2 <= num.length <= 1000 1 <= k <= 1000 num only consists of digits.
class Solution: def getMinSwaps(self, s: str, k: int) -> int: # smallest permutation greater than s # simulation # once you have both the kth next larget # then you do greedy swapping to move things into place # you can do brute simulation n = len(s) a0 = list(s) a = list(s) def next_permutation(a): n = len(a) for i in reversed(range(n-1)): if a[i] < a[i+1]: #print("found inversion at", i) j = next(j for j in reversed(range(i+1,n)) if a[j] > a[i]) a[i],a[j] = a[j],a[i] a[i+1:] = a[i+1:][::-1] break for _ in range(k): next_permutation(a) ret = 0 for i in range(n): if a[i] != a0[i]: j = next(j for j in range(i,n) if a[j] == a0[i]) a[i+1:j+1] = a[i:j] ret += j-i return ret
5ae257
0c9eeb
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. For example, when num = "5489355142": The 1st smallest wonderful integer is "5489355214". The 2nd smallest wonderful integer is "5489355241". The 3rd smallest wonderful integer is "5489355412". The 4th smallest wonderful integer is "5489355421". Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth smallest wonderful integer exists.   Example 1: Input: num = "5489355142", k = 4 Output: 2 Explanation: The 4th smallest wonderful number is "5489355421". To get this number: - Swap index 7 with index 8: "5489355142" -> "5489355412" - Swap index 8 with index 9: "5489355412" -> "5489355421" Example 2: Input: num = "11112", k = 4 Output: 4 Explanation: The 4th smallest wonderful number is "21111". To get this number: - Swap index 3 with index 4: "11112" -> "11121" - Swap index 2 with index 3: "11121" -> "11211" - Swap index 1 with index 2: "11211" -> "12111" - Swap index 0 with index 1: "12111" -> "21111" Example 3: Input: num = "00123", k = 1 Output: 1 Explanation: The 1st smallest wonderful number is "00132". To get this number: - Swap index 3 with index 4: "00123" -> "00132"   Constraints: 2 <= num.length <= 1000 1 <= k <= 1000 num only consists of digits.
class Solution(object): def getMinSwaps(self, num, k): """ :type num: str :type k: int :rtype: int """ # generate k'th smallest a = list(num) n = len(a) for _ in xrange(k): for i in xrange(n-2, -1, -1): if a[i] < a[i+1]: j = i+1 for k in xrange(i+2, n): if a[j] > a[k] > a[i]: j = k a[i], a[j] = a[j], a[i] a[i+1:] = sorted(a[i+1:]) break # count swaps used = [False] * n r = 0 for ch in num: for j in xrange(n): if used[j]: continue if ch == a[j]: used[j] = True break r += 1 return r
61222c
0522f7
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return the minimum total cost to supply water to all houses. Example 1: Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]] Output: 3 Explanation: The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. Example 2: Input: n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]] Output: 2 Explanation: We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose the cheapest option. Constraints: 2 <= n <= 10000 wells.length == n 0 <= wells[i] <= 100000 1 <= pipes.length <= 10000 pipes[j].length == 3 1 <= house1j, house2j <= n 0 <= costj <= 100000 house1j != house2j
class Solution: def minCostToSupplyWater(self, n: int, w: List[int], p: List[List[int]]) -> int: def find(x): if x != up[x]: up[x] = find(up[x]) return up[x] def union(x, y, cost): a, b = find(x), find(y) if a != b and max(exp[b], exp[a]) > cost: up[a] = b sav = max(exp[b], exp[a]) - cost exp[b] = min(exp[b], exp[a]) return sav return 0 p.sort(key=lambda x: x[2]) up = [i for i in range(n + 1)] exp = [0] + w ret = sum(w) for u, v, c in p: ret -= union(u, v, c) return ret
e93617
0522f7
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return the minimum total cost to supply water to all houses. Example 1: Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]] Output: 3 Explanation: The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. Example 2: Input: n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]] Output: 2 Explanation: We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose the cheapest option. Constraints: 2 <= n <= 10000 wells.length == n 0 <= wells[i] <= 100000 1 <= pipes.length <= 10000 pipes[j].length == 3 1 <= house1j, house2j <= n 0 <= costj <= 100000 house1j != house2j
class DSU: def __init__(self): self.parents = range(10001) self.rank = [0 for i in range(10001)] def find(self, x): if self.parents[x]!=x: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): xr,yr = self.find(x),self.find(y) if xr == yr: return False if self.rank[xr]<self.rank[yr]: self.parents[xr] = yr elif self.rank[xr]>self.rank[yr]: self.parents[yr] = xr else: self.parents[xr] = yr self.rank[yr] += 1 return True class Solution(object): def minCostToSupplyWater(self, n, wells, pipes): """ :type n: int :type wells: List[int] :type pipes: List[List[int]] :rtype: int """ dsu = DSU() dic = {} for i,w in enumerate(wells): dic[(0,i+1)] = w for i,j,p in pipes: dic[(i,j)] = p keys = sorted(dic.keys(),key=lambda x: dic[x]) res = 0 for i,j in keys: if dsu.find(i)==dsu.find(j): continue else: dsu.union(i,j) res+=dic[(i,j)] return res
3405c2
716fa7
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood. Note that you can cut the piece of wood as many times as you want.   Example 1: Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]] Output: 19 Explanation: The diagram above shows a possible scenario. It consists of: - 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14. - 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 14 + 3 + 2 = 19 money earned. It can be shown that 19 is the maximum amount of money that can be earned. Example 2: Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]] Output: 32 Explanation: The diagram above shows a possible scenario. It consists of: - 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 30 + 2 = 32 money earned. It can be shown that 32 is the maximum amount of money that can be earned. Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.   Constraints: 1 <= m, n <= 200 1 <= prices.length <= 2 * 10000 prices[i].length == 3 1 <= hi <= m 1 <= wi <= n 1 <= pricei <= 1000000 All the shapes of wood (hi, wi) are pairwise distinct.
class Solution: def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: dictt = collections.defaultdict(dict) for h, w, p in prices : dictt[h][w] = p @functools.lru_cache(None) def solve(h=m, w=n) : to_ret = dictt[h].get(w, 0) for i in range(1, h//2+1) : to_ret = max(to_ret, solve(i, w)+solve(h-i, w)) for i in range(1, w//2+1) : to_ret = max(to_ret, solve(h, i)+solve(h, w-i)) return to_ret return solve()
5b9fc3
716fa7
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood. Note that you can cut the piece of wood as many times as you want.   Example 1: Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]] Output: 19 Explanation: The diagram above shows a possible scenario. It consists of: - 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14. - 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 14 + 3 + 2 = 19 money earned. It can be shown that 19 is the maximum amount of money that can be earned. Example 2: Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]] Output: 32 Explanation: The diagram above shows a possible scenario. It consists of: - 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 30 + 2 = 32 money earned. It can be shown that 32 is the maximum amount of money that can be earned. Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.   Constraints: 1 <= m, n <= 200 1 <= prices.length <= 2 * 10000 prices[i].length == 3 1 <= hi <= m 1 <= wi <= n 1 <= pricei <= 1000000 All the shapes of wood (hi, wi) are pairwise distinct.
class Solution(object): def sellingWood(self, m, n, prices): """ :type m: int :type n: int :type prices: List[List[int]] :rtype: int """ a, d = [[0] * (n + 1) for _ in range(m + 1)], [[0] * (n + 1) for _ in range(m + 1)] for p, q, r in prices: a[p][q] = r for i in range(1, m + 1): for j in range(1, n + 1): d[i][j] = a[i][j] for k in range(1, j): d[i][j] = max(d[i][j], d[i][k] + d[i][j - k]) for k in range(1, i): d[i][j] = max(d[i][j], d[k][j] + d[i - k][j]) return d[m][n]
f63ce9
69f3b5
You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Pick any ball from your hand and insert it in between two balls in the row or on either end of the row. If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left. If there are no more balls on the board, then you win the game. Repeat this process until you either win or do not have any more balls in your hand. Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.   Example 1: Input: board = "WRRBBW", hand = "RB" Output: -1 Explanation: It is impossible to clear all the balls. The best you can do is: - Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW. - Insert 'B' so the board becomes WBBBW. WBBBW -> WW. There are still balls remaining on the board, and you are out of balls to insert. Example 2: Input: board = "WWRRBBWW", hand = "WRBRW" Output: 2 Explanation: To make the board empty: - Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW. - Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty. 2 balls from your hand were needed to clear the board. Example 3: Input: board = "G", hand = "GGGGG" Output: 2 Explanation: To make the board empty: - Insert 'G' so the board becomes GG. - Insert 'G' so the board becomes GGG. GGG -> empty. 2 balls from your hand were needed to clear the board.   Constraints: 1 <= board.length <= 16 1 <= hand.length <= 5 board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'. The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
class Solution(object): def __init__(self): self.visit = set([]) self.res = 10 ** 10 def findMinStep(self, board, hand): hand = sorted(hand) board = list(board) st = [(board, hand, 0)] while st: board, hand, step = st.pop() if step > self.res: continue for i in xrange(len(hand)): if i and hand[i - 1] == hand[i]: continue for j in xrange(len(board)): if j and board[j - 1] == board[j]: continue if board[j] == hand[i]: nboard = board[:j] + [hand[i]] + board[j:] nhand = hand[:] del(nhand[i]) nboard = self.eliminate(nboard) if nboard == []: self.res = min(self.res, step + 1) else: st.append((nboard, nhand, step + 1)) return -1 if self.res >= 10 ** 10 else self.res def eliminate(self, board): board.append('X') while True: flag = False l, r = 0, 0 n = len(board) for i in xrange(len(board)): if i and board[i] == board[i - 1]: r = i + 1 elif board[i] != board[i - 1]: if r - l >= 3: board = board[:l] + board[r:] flag = True break else: l, r = i, i + 1 if not flag: break return board[:-1]
5d9a01
e3b9db
Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.   Example 1: Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".   Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters.
class Solution(object): def countSubstrings(self, s): def check(s): return s == s[::-1] cnt = len(s) for i in range(len(s)): for j in range(i + 2, len(s) + 1): if check(s[i:j]): cnt += 1 return cnt
c1a076
e3b9db
Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.   Example 1: Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".   Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters.
class Solution: def countSubstrings(self, s): """ :type s: str :rtype: int """ # dp n = len(s) # from i to j (include both ends) dp = [[0 for i in range(n)] for j in range(n)] for i in range(n): dp[i][i] = 1 for d in range(1, n): for i in range(n - d): j = i + d if s[i] == s[j]: if d == 1: dp[i][j] = 1 else: dp[i][j] = dp[i + 1][j - 1] return sum([sum(r) for r in dp])
ef8396
b02135
The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 10^9 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,2,3,2] Output: 14 Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2). 2 * (2+3+2) = 2 * 7 = 14. Example 2: Input: nums = [2,3,3,1,2] Output: 18 Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3). 3 * (3+3) = 3 * 6 = 18. Example 3: Input: nums = [3,1,5,6,4,2] Output: 60 Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4). 4 * (5+6+4) = 4 * 15 = 60.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^7
class Solution(object): def maxSumMinProduct(self, nums): """ :type nums: List[int] :rtype: int """ r = 0 a = nums n = len(a) begin = [-1]*n end = [-1]*n tot = [0]*n for v,i in sorted(((v,i) for i,v in enumerate(nums)), reverse=True): lo = hi = i s = v if i > 0 and begin[i-1] >= 0: lo = begin[i-1] s += tot[lo] if i < n-1 and end[i+1] >= 0: hi = end[i+1] s += tot[hi] end[lo] = hi begin[hi] = lo tot[lo] = tot[hi] = s r = max(r, v*s) return r % (10**9+7)
425c54
b02135
The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 10^9 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,2,3,2] Output: 14 Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2). 2 * (2+3+2) = 2 * 7 = 14. Example 2: Input: nums = [2,3,3,1,2] Output: 18 Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3). 3 * (3+3) = 3 * 6 = 18. Example 3: Input: nums = [3,1,5,6,4,2] Output: 60 Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4). 4 * (5+6+4) = 4 * 15 = 60.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^7
class Solution: def maxSumMinProduct(self, A: List[int]) -> int: left = [-1] * len(A) right = [len(A)] * len(A) stack = [] for i, a in enumerate(A): while stack and a <= stack[-1][1]: stack.pop() if stack: left[i] = stack[-1][0] stack.append([i, a]) stack = [] for i in range(len(A))[::-1]: a = A[i] while stack and a <= stack[-1][1]: stack.pop() if stack: right[i] = stack[-1][0] stack.append([i, a]) pre = [0] for i, a in enumerate(A): pre.append(a + pre[-1]) res = 0 for i, a in enumerate(A): res = max(res, (pre[right[i]] - pre[left[i]+1]) * a) return res % (10**9+7)
96152d
e9581b
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n.   Example 1: Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". Example 2: Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1. Example 3: Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"   Constraints: 1 <= n <= 10 1 <= k <= 100
class Solution(object): def getHappyString(self, n, k): path = [];ans=[] def search(i): if i == n: ans.append(path[:]) return for d in range(3): if not path or path[-1] != d: path.append(d) search(i + 1) path.pop() search(0) k -= 1 if k >= len(ans): return "" bns = ans[k] return "".join('abc'[d] for d in bns)
fc4ac3
e9581b
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n.   Example 1: Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". Example 2: Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1. Example 3: Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"   Constraints: 1 <= n <= 10 1 <= k <= 100
class Solution: def happy(self, s): if len(s) == self.n: self.k -= 1 if self.k == 0: self.ans = s return if s[-1] != 'a': self.happy(s + 'a') if s[-1] != 'b': self.happy(s + 'b') if s[-1] != 'c': self.happy(s + 'c') def getHappyString(self, n: int, k: int) -> str: self.ans = '' self.n = n self.k = k self.happy('a') self.happy('b') self.happy('c') return self.ans
95a899
4d2dc5
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] Output: true Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. Now sub = "l3e7" is a substring of s, so we return true. Example 2: Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] Output: false Explanation: The string "f00l" is not a substring of s and no replacements can be made. Note that we cannot replace '0' with 'o'. Example 3: Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] Output: true Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. Now sub = "l33tb" is a substring of s, so we return true.   Constraints: 1 <= sub.length <= s.length <= 5000 0 <= mappings.length <= 1000 mappings[i].length == 2 oldi != newi s and sub consist of uppercase and lowercase English letters and digits. oldi and newi are either uppercase or lowercase English letters or digits.
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: cs = {c:set([c]) for c in set(s)} for old, new in mappings : if new in cs : cs[new].add(old) for ps in range(len(s)-len(sub)+1) : mark = True for j in range(len(sub)) : if not sub[j] in cs[s[ps+j]] : mark = False break if mark : return True return False
bd07dc
4d2dc5
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] Output: true Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. Now sub = "l3e7" is a substring of s, so we return true. Example 2: Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] Output: false Explanation: The string "f00l" is not a substring of s and no replacements can be made. Note that we cannot replace '0' with 'o'. Example 3: Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] Output: true Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. Now sub = "l33tb" is a substring of s, so we return true.   Constraints: 1 <= sub.length <= s.length <= 5000 0 <= mappings.length <= 1000 mappings[i].length == 2 oldi != newi s and sub consist of uppercase and lowercase English letters and digits. oldi and newi are either uppercase or lowercase English letters or digits.
class Solution(object): def matchReplacement(self, s, sub, mappings): """ :type s: str :type sub: str :type mappings: List[List[str]] :rtype: bool """ mp = {} for a, b in mappings: a=a[0] b=b[0] if a not in mp: mp[a]=set() mp[a].add(b) n, m = len(s), len(sub) i=0 # print mp while i+m<=n: j=0 while j<m: if s[i+j]!=sub[j]: a = sub[j] b = s[i+j] # print a, a in mp if a not in mp or b not in mp[a]: break j+=1 if j==m: return True i+=1 return False
f70229
4b1e89
You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart.   Example 1: Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]] Output: 3 Explanation: The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price. The following 3 lines can be drawn to represent the line chart: - Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4). - Line 2 (in blue) from (4,4) to (5,4). - Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1). It can be shown that it is not possible to represent the line chart using less than 3 lines. Example 2: Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]] Output: 1 Explanation: As shown in the diagram above, the line chart can be represented with a single line.   Constraints: 1 <= stockPrices.length <= 100000 stockPrices[i].length == 2 1 <= dayi, pricei <= 10^9 All dayi are distinct.
class Solution(object): def minimumLines(self, stockPrices): """ :type stockPrices: List[List[int]] :rtype: int """ stockPrices.sort() r = min(len(stockPrices) - 1, 1) for i in range(2, len(stockPrices)): r += 1 if (stockPrices[i][1] - stockPrices[i - 1][1]) * (stockPrices[i - 1][0] - stockPrices[i - 2][0]) != (stockPrices[i - 1][1] - stockPrices[i - 2][1]) * (stockPrices[i][0] - stockPrices[i - 1][0]) else 0 return r
6072db
4b1e89
You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart.   Example 1: Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]] Output: 3 Explanation: The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price. The following 3 lines can be drawn to represent the line chart: - Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4). - Line 2 (in blue) from (4,4) to (5,4). - Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1). It can be shown that it is not possible to represent the line chart using less than 3 lines. Example 2: Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]] Output: 1 Explanation: As shown in the diagram above, the line chart can be represented with a single line.   Constraints: 1 <= stockPrices.length <= 100000 stockPrices[i].length == 2 1 <= dayi, pricei <= 10^9 All dayi are distinct.
class Solution: def minimumLines(self, p: List[List[int]]) -> int: p.sort() pre = None ans = 0 for i in range(1, len(p)): a = p[i][0] - p[i-1][0] b = p[i][1] - p[i-1][1] g = gcd(a, b) k = [a//g, b//g] if pre is None or k != pre: ans += 1 pre = k return ans
78b287
62d04f
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid. The following rules define a valid string: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".   Example 1: Input: s = "()" Output: true Example 2: Input: s = "(*)" Output: true Example 3: Input: s = "(*))" Output: true   Constraints: 1 <= s.length <= 100 s[i] is '(', ')' or '*'.
class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ n = len(s) memo = {} def dfs(idx, left): key = (idx, left) if key in memo: return memo[key] while idx < n: if left < 0: memo[key] = False return False if s[idx] == '(': left += 1 elif s[idx] == ')': left -= 1 else: memo[key] = dfs(idx + 1, left) or dfs(idx + 1, left + 1) or dfs(idx + 1, left - 1) return memo[key] idx += 1 memo[key] = left == 0 return memo[key] return dfs(0, 0)
85e938
62d04f
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid. The following rules define a valid string: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".   Example 1: Input: s = "()" Output: true Example 2: Input: s = "(*)" Output: true Example 3: Input: s = "(*))" Output: true   Constraints: 1 <= s.length <= 100 s[i] is '(', ')' or '*'.
class Solution: def checkValidString(self, s): self.s=list(s) return self.isValid(0,0) def isValid(self, index, num_open): for x in range (index,len(self.s)): if(self.s[x]=='('): num_open+=1 elif(self.s[x]==')'): if(num_open==0): return False else: num_open-=1 elif(self.s[x]=='*'): try1=self.isValid(x+1,num_open) if(try1): return True self.s[x]='(' if(self.isValid(x,num_open)): return True self.s[x]=')' if(self.isValid(x,num_open)): return True return False return num_open==0
697be0
9bdbc5
You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries: For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed. For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p. For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the elements in nums2. Return an array containing all the answers to the third type queries.   Example 1: Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] Output: [3] Explanation: After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. Example 2: Input: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] Output: [5] Explanation: After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned.   Constraints: 1 <= nums1.length,nums2.length <= 100000 nums1.length = nums2.length 1 <= queries.length <= 100000 queries[i].length = 3 0 <= l <= r <= nums1.length - 1 0 <= p <= 1000000 0 <= nums1[i] <= 1 0 <= nums2[i] <= 10^9
class Solution: def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]: ans = [] n = len(nums1) seg = LazySegmentTree(nums1) tot = sum(nums2) for t, l, r in queries: if t == 1: seg.update(l, r) elif t == 2: tot += seg.query(0, n-1) * l else: ans.append(tot) return ans class LazySegmentTree: def __init__(self, nums): self.n = len(nums) self.nums = nums self.ones = [0] * (4 * self.n) self.lazy = [True] * (4 * self.n) self._build(0, 0, self.n-1) def _build(self, tree_index, l, r): if l == r: self.ones[tree_index] = self.nums[l] return left, right = 2 * tree_index + 1, 2 * tree_index + 2 mid = (l + r) // 2 self._build(left, l, mid) self._build(right, mid+1, r) self.ones[tree_index] = self.ones[left] + self.ones[right] def update(self, ql, qr): self._update(0, 0, self.n-1, ql, qr) def _update(self, tree_index, l, r, ql, qr): if l == ql and r == qr: self.lazy[tree_index] = not self.lazy[tree_index] ones = self.ones[tree_index] zeros = r - l + 1 - ones self.ones[tree_index] = zeros return left, right = 2 * tree_index + 1, 2 * tree_index + 2 mid = (l + r) // 2 if not self.lazy[tree_index]: self._update(left, l, mid, l, mid) self._update(right, mid+1, r, mid+1, r) self.lazy[tree_index] = True if qr <= mid: self._update(left, l, mid, ql, qr) elif ql > mid: self._update(right, mid+1, r, ql, qr) else: self._update(left, l, mid, ql, mid) self._update(right, mid+1, r, mid+1, qr) self.ones[tree_index] = self.ones[left] + self.ones[right] def query(self, ql, qr): return self._query(0, 0, self.n-1, ql, qr) def _query(self, tree_index, l, r, ql, qr): if l == ql and r == qr: return self.ones[tree_index] left, right = 2 * tree_index + 1, 2 * tree_index + 2 mid = (l + r) // 2 if not self.lazy[tree_index]: self._update(left, l, mid, l, mid) self._update(right, mid+1, r, mid+1, r) self.lazy[tree_index] = True if qr <= mid: return self._query(left, l, mid, ql, qr) if ql > mid: return self._query(right, mid+1, r, ql, qr) ones1 = self._query(left, l, mid, ql, mid) ones2 = self._query(right, mid+1, r, mid+1, qr) return ones1 + ones2
ff94b3
9bdbc5
You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries: For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed. For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p. For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the elements in nums2. Return an array containing all the answers to the third type queries.   Example 1: Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] Output: [3] Explanation: After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. Example 2: Input: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] Output: [5] Explanation: After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned.   Constraints: 1 <= nums1.length,nums2.length <= 100000 nums1.length = nums2.length 1 <= queries.length <= 100000 queries[i].length = 3 0 <= l <= r <= nums1.length - 1 0 <= p <= 1000000 0 <= nums1[i] <= 1 0 <= nums2[i] <= 10^9
class Solution(object): def handleQuery(self, nums1, nums2, queries): """ :type nums1: List[int] :type nums2: List[int] :type queries: List[List[int]] :rtype: List[int] """ n = len(nums1) mx = 1 while mx<=n: mx<<=1 ix = [0]*(mx+mx) ss = [0]*(mx+mx) mk = [0]*(mx+mx) def flip(k, d, s, e): if s==0 and e==d-1: mk[k]^=1 ix[k]=d-ix[k] return k1=k*2 k2=k1+1 d>>=1 if mk[k]: mk[k1]^=1 ix[k1]=d-ix[k1] mk[k2]^=1 ix[k2]=d-ix[k2] mk[k]=0 if e<d: flip(k1, d, s, e) elif s>=d: flip(k2, d, s-d, e-d) else: flip(k1, d, s, d-1) flip(k2, d, 0, e-d) ix[k]=ix[k1]+ix[k2] for i in range(n): ix[i+mx]=nums1[i] i=mx-1 while i>0: ix[i]=ix[i*2]+ix[i*2+1] i-=1 r = [] s = sum(nums2) for t, a, b in queries: if t==1: flip(1, mx, a, b) elif t==2: c = ix[1] s+=c*a else: r.append(s) return r
06d1f5
504945
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given 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. You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component. Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.   Example 1: Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] Output: 2 Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2. Example 2: Input: nums = [2], edges = [] Output: 0 Explanation: There are no edges to be deleted.   Constraints: 1 <= n <= 2 * 10000 nums.length == n 1 <= nums[i] <= 50 edges.length == n - 1 edges[i].length == 2 0 <= edges[i][0], edges[i][1] <= n - 1 edges represents a valid tree.
class Solution(object): def componentValue(self, nums, edges): """ :type nums: List[int] :type edges: List[List[int]] :rtype: int """ s, m, g, a, j = 0, 0, [[] for _ in nums], 0, 1 def d(n, p, s): a = nums[n] for x in g[n]: if x != p: h = d(x, n, s) if h == -1: return -1 a += h if a > s: return -1 if a == s: return 0 return a for i in range(len(nums)): s, m = s + nums[i], max(m, nums[i]) for e, f in edges: g[e].append(f) g[f].append(e) while j * j <= s: a, j = max(a, s / j - 1 if not s % j and j >= m and not d(0, -1, j) else 0, j - 1 if not s % j and s / j != j and s / j >= m and not d(0, -1, s / j) else 0), j + 1 return a
84ead1
504945
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given 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. You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component. Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.   Example 1: Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] Output: 2 Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2. Example 2: Input: nums = [2], edges = [] Output: 0 Explanation: There are no edges to be deleted.   Constraints: 1 <= n <= 2 * 10000 nums.length == n 1 <= nums[i] <= 50 edges.length == n - 1 edges[i].length == 2 0 <= edges[i][0], edges[i][1] <= n - 1 edges represents a valid tree.
class Solution: def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: if not edges: return 0 tot = sum(nums) psb = set() for i in range(1, int(tot ** 0.5) + 10): if tot % i == 0: psb.add(i) psb.add(tot // i) tree = defaultdict(set) for a, b in edges: tree[a].add(b) tree[b].add(a) root = edges[0][0] psb = list(psb) psb.sort() def split(pre, node, target): cur_value = nums[node] if cur_value > target: return 0, False count = 0 for nxt in tree[node]: if nxt != pre: up, ok = split(node, nxt, target) if not ok: return 0, False count += up if count + cur_value > target: return 0, False if count + cur_value == target: return 0, True return cur_value + count, True for p in psb: if split(-1, root, p)[1]: return (tot//p)-1 return tot
fe9152
912b99
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.   Example 1: Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". Example 2: Input: words = ["cat","dog","catdog"] Output: ["catdog"]   Constraints: 1 <= words.length <= 10000 1 <= words[i].length <= 30 words[i] consists of only lowercase English letters. All the strings of words are unique. 1 <= sum(words[i].length) <= 100000
class Solution(object): def findAllConcatenatedWordsInADict(self, A): """ :type words: List[str] :rtype: List[str] """ S = set(A) def great(word): stack = [0] seen = {0} M = len(word) while stack: node = stack.pop() if node == M: return True for j in xrange(M - node + 1): if (word[node:node+j] in S and node+j not in seen and (node > 0 or node + j != M)): stack.append(node + j) seen.add(node + j) return False ans = [] for word in A: if word and great(word): ans.append(word) return ans
1662e9
14e43a
Given two positive integers num1 and num2, find the positive integer x such that: x has the same number of set bits as num2, and The value x XOR num1 is minimal. Note that XOR is the bitwise XOR operation. Return the integer x. The test cases are generated such that x is uniquely determined. The number of set bits of an integer is the number of 1's in its binary representation.   Example 1: Input: num1 = 3, num2 = 5 Output: 3 Explanation: The binary representations of num1 and num2 are 0011 and 0101, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal. Example 2: Input: num1 = 1, num2 = 12 Output: 3 Explanation: The binary representations of num1 and num2 are 0001 and 1100, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.   Constraints: 1 <= num1, num2 <= 10^9
class Solution(object): def minimizeXor(self, num1, num2): """ :type num1: int :type num2: int :rtype: int """ n, v, b, i, j, a = bin(num2).count("1"), [0] * 30, [0] * 30, 29, 0, 0 for k in range(30): b[k] = 1 if num1 & 1 << k else 0 while i >= 0 and n: n, v[i], i = n - 1 if b[i] else n, 1 if b[i] else 0, i - 1 while j < 30 and n: n, v[j], j = n if v[j] else n - 1, 1, j + 1 for i in range(30): a |= 1 << i if v[i] else 0 return a
26d51b
14e43a
Given two positive integers num1 and num2, find the positive integer x such that: x has the same number of set bits as num2, and The value x XOR num1 is minimal. Note that XOR is the bitwise XOR operation. Return the integer x. The test cases are generated such that x is uniquely determined. The number of set bits of an integer is the number of 1's in its binary representation.   Example 1: Input: num1 = 3, num2 = 5 Output: 3 Explanation: The binary representations of num1 and num2 are 0011 and 0101, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal. Example 2: Input: num1 = 1, num2 = 12 Output: 3 Explanation: The binary representations of num1 and num2 are 0001 and 1100, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.   Constraints: 1 <= num1, num2 <= 10^9
class Solution: def minimizeXor(self, num1: int, num2: int) -> int: num1 = [int(t) for t in bin(num1)[2:]] num2 = [int(t) for t in bin(num2)[2:]] s1, s2 = sum(num1), sum(num2) to_ret = [t for t in num1] sr = sum(to_ret) for i in range(len(to_ret)) : if sr > s2 and to_ret[-1-i] == 1 : to_ret[-1-i] = 0 sr -= 1 if sr < s2 and to_ret[-1-i] == 0 : to_ret[-1-i] = 1 sr += 1 assert sr <= s2 if sr < s2 : to_ret = [1] * (s2-sr) + to_ret # print(to_ret) # print(num1, num2) to_ret_f = 0 for t in to_ret : to_ret_f = to_ret_f * 2 + t return to_ret_f
a61a8e
f11d10
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.   Example 1: Input: nums = [1,5,2] Output: false Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. Example 2: Input: nums = [1,5,233,7] Output: true Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.   Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 10^7
class Solution(object): def go(self, b, e): key = (b, e) if key in self.mem: return self.mem[key] self.mem[key] = ret = -10**10 if b < e: ret = max(self.nums[b] - self.go(b + 1, e), self.nums[e - 1] - self.go(b, e - 1)) else: ret = 0 self.mem[key] = ret return ret def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ self.nums = nums[:] self.mem = {} score = self.go(0, len(nums)) # print 'score =', score return score >= 0
8899e9
5da5a0
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it. Example 2: Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0.   Constraints: 1 <= s.length <= 10000 s consists of lowercase English letters.
class Solution: def maxSubArray(self, nums: List[int]) -> int: ans = nums[0]-1 tmp = nums[0] flag = False for num in nums[1:]: if num < 0: flag = True if tmp >= 0: tmp += num else: if num > 0: flag = False tmp = num if flag: ans = max(ans, tmp) else: ans = max(ans, tmp-1) return ans def largestVariance(self, s: str) -> int: res = 0 for i in range(25): for j in range(i+1, 26): char1, char2 = chr(i+ord('a')), chr(j+ord('a')) lst = [] for char in s: if char != char1 and char != char2: continue elif char == char1: lst.append(1) else: lst.append(-1) if 1 not in lst or -1 not in lst: continue res = max(res, self.maxSubArray(lst), self.maxSubArray([-x for x in lst])) return res
ffced0
5da5a0
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it. Example 2: Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0.   Constraints: 1 <= s.length <= 10000 s consists of lowercase English letters.
class Solution(object): def largestVariance(self, s): """ :type s: str :rtype: int """ r=0 s=[ord(c)-ord('a') for c in s] mk = [0]*26 for c in s: mk[c]+=1 n = len(s) vs = [0]*(n+1) def calc(k1, k2): i, m=0, 0 while i<n: if s[i]==k1: vs[m]=1 m+=1 elif s[i]==k2: vs[m]=-1 m+=1 i+=1 c1, c2 = 0, 0 i, j = 0, 0 p = -1 mv = 0 rx=0 while i<m: while i<m: c1+=vs[i] if vs[i]==-1: if c1+i+1>0: rx=max(rx, c1-mv) p=i elif p!=-1: i+=1 break i+=1 if p==-1: break while j<p: c2+=vs[j] mv = min(c2, mv) j+=1 rx=max(rx, c1-mv) return rx for k1 in range(26): if mk[k1]==0: continue for k2 in range(26): if mk[k2]==0: continue if mk[k1]<=r: continue if k1==k2: continue t=calc(k1, k2) r=max(r, t) return r
52f0b5
57cc51
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)   Example 1: Input: poured = 1, query_row = 1, query_glass = 1 Output: 0.00000 Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. Example 2: Input: poured = 2, query_row = 1, query_glass = 1 Output: 0.50000 Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. Example 3: Input: poured = 100000009, query_row = 33, query_glass = 17 Output: 1.00000   Constraints: 0 <= poured <= 10^9 0 <= query_glass <= query_row < 100
class Solution(object): def champagneTower(self, poured, query_row, query_glass): """ :type poured: int :type query_row: int :type query_glass: int :rtype: float """ # lst = [[0 for _ in range(100)] for _ in range(100)] lst = [1.0 * poured] for row in range(query_row): lst2 = [0.0 for _ in range(len(lst) + 1)] for i in range(len(lst)): if lst[i] < 1.0: continue lst2[i] += (lst[i] - 1.0) / 2.0 lst2[i + 1] += (lst[i] - 1.0) / 2.0 lst = lst2 if lst[query_glass] > 1.0: return 1.0 return lst[query_glass]
8f98f3
57cc51
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)   Example 1: Input: poured = 1, query_row = 1, query_glass = 1 Output: 0.00000 Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. Example 2: Input: poured = 2, query_row = 1, query_glass = 1 Output: 0.50000 Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. Example 3: Input: poured = 100000009, query_row = 33, query_glass = 17 Output: 1.00000   Constraints: 0 <= poured <= 10^9 0 <= query_glass <= query_row < 100
class Solution: def champagneTower(self, poured, query_row, query_glass): f = [[0.0] * 100 for _ in range(100)] f[0][0] = poured * 1.0 for i in range(1, query_row + 1): for j in range(i + 1): if j != i and f[i - 1][j] > 1.0: f[i][j] += (f[i - 1][j] - 1.0) / 2 if j != 0 and f[i - 1][j - 1] > 1.0: f[i][j] += (f[i - 1][j - 1] - 1.0) / 2 ans = f[query_row][query_glass] return ans if ans < 1.0 else 1.0
f16b95
abf2d6
The score of an array is defined as the product of its sum and its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k. A subarray is a contiguous sequence of elements within an array.   Example 1: Input: nums = [2,1,4,3,5], k = 10 Output: 6 Explanation: The 6 subarrays having scores less than 10 are: - [2] with score 2 * 1 = 2. - [1] with score 1 * 1 = 1. - [4] with score 4 * 1 = 4. - [3] with score 3 * 1 = 3. - [5] with score 5 * 1 = 5. - [2,1] with score (2 + 1) * 2 = 6. Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10. Example 2: Input: nums = [1,1,1], k = 5 Output: 5 Explanation: Every subarray except [1,1,1] has a score less than 5. [1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5. Thus, there are 5 subarrays having scores less than 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000 1 <= k <= 10^15
class Solution: def countSubarrays(self, a: List[int], k: int) -> int: n = len(a) j = 0 s = 0 z = 0 for i in range(n): s += a[i] while s * (i - j + 1) >= k: s -= a[j] j += 1 z += i - j + 1 return z
66283f
abf2d6
The score of an array is defined as the product of its sum and its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k. A subarray is a contiguous sequence of elements within an array.   Example 1: Input: nums = [2,1,4,3,5], k = 10 Output: 6 Explanation: The 6 subarrays having scores less than 10 are: - [2] with score 2 * 1 = 2. - [1] with score 1 * 1 = 1. - [4] with score 4 * 1 = 4. - [3] with score 3 * 1 = 3. - [5] with score 5 * 1 = 5. - [2,1] with score (2 + 1) * 2 = 6. Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10. Example 2: Input: nums = [1,1,1], k = 5 Output: 5 Explanation: Every subarray except [1,1,1] has a score less than 5. [1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5. Thus, there are 5 subarrays having scores less than 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000 1 <= k <= 10^15
class Solution(object): def countSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ n = len(nums) ss = [0]*(n+1) i=0 while i<n: ss[i+1]=ss[i]+nums[i] i+=1 r=0 i=0 while i<n: j=i-1 d=n-i while d: while True: nj=j+d if nj>=n: break s=ss[nj+1]-ss[i] s*=(nj-i+1) if s>=k: break j=nj d>>=1 r+=(j-i+1) i+=1 return r
72b871
d5bd89
We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi. All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2. Return the maximum number of achievable requests.   Example 1: Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]] Output: 5 Explantion: Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. Example 2: Input: n = 3, requests = [[0,0],[1,2],[2,1]] Output: 3 Explantion: Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. Example 3: Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]] Output: 4   Constraints: 1 <= n <= 20 1 <= requests.length <= 16 requests[i].length == 2 0 <= fromi, toi < n
class Solution: def maximumRequests(self, N: int, requests: List[List[int]]) -> int: R = len(requests) best = 0 for mask in range(1 << R): buildings = [0] * N count = 0 for x, (f, t) in enumerate(requests): if ((1 << x) & mask) > 0: buildings[f] -= 1 buildings[t] += 1 count += 1 if all(x == 0 for x in buildings): best = max(best, count) return best
284006
d5bd89
We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi. All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2. Return the maximum number of achievable requests.   Example 1: Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]] Output: 5 Explantion: Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. Example 2: Input: n = 3, requests = [[0,0],[1,2],[2,1]] Output: 3 Explantion: Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. Example 3: Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]] Output: 4   Constraints: 1 <= n <= 20 1 <= requests.length <= 16 requests[i].length == 2 0 <= fromi, toi < n
class Solution(object): def maximumRequests(self, n, requests): """ :type n: int :type requests: List[List[int]] :rtype: int """ m = len(requests) net = [0]*n ans = [0] def _dfs(pos, imb, score): if pos == m: if imb == 0: ans[0] = max(ans[0], score) return _dfs(pos+1, imb, score) i, j = requests[pos] if net[i] == 0: imb += 1 net[i] -= 1 if net[i] == 0: imb -= 1 if net[j] == 0: imb += 1 net[j] += 1 if net[j] == 0: imb -= 1 _dfs(pos+1, imb, score+1) net[i] += 1 net[j] -= 1 _dfs(0, 0, 0) return ans[0]
5514e6
3fd2c9
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.   Example 1: Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: Input: grid = [[-1]] Output: [-1] Explanation: The ball gets stuck against the left wall. Example 3: Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] Output: [0,1,2,3,4,-1]   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is 1 or -1.
#!/opt/python3.9/bin/python3 from bisect import * from collections import * from functools import * from heapq import * from typing import * import sys INF = float('inf') class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: R = len(grid) C = len(grid[0]) # ball num => column balls = list(range(C)) for i in range(R): for bid in range(C): col = balls[bid] if col < 0: continue wall = grid[i][col] if wall == 1: new_col = col + 1 if new_col >= C or grid[i][new_col] == -1: new_col = -1 balls[bid] = new_col else: new_col = col - 1 if new_col < 0 or grid[i][new_col] == 1: new_col = -1 balls[bid] = new_col return balls
10e19a
3fd2c9
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.   Example 1: Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: Input: grid = [[-1]] Output: [-1] Explanation: The ball gets stuck against the left wall. Example 3: Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] Output: [0,1,2,3,4,-1]   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is 1 or -1.
class Solution(object): def findBall(self, grid): """ :type grid: List[List[int]] :rtype: List[int] """ n, m = len(grid), len(grid[0]) def answer(j): for i in xrange(n): if grid[i][j] == 1 and j + 1 < m and grid[i][j+1] == 1: j += 1 elif grid[i][j] == -1 and j - 1 >= 0 and grid[i][j-1] == -1: j -= 1 else: return -1 return j return [answer(i) for i in xrange(m)]
8f214d
9460eb
You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices.   Example 1: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] Output: 3 Explanation: From the picture above, one can see that all of the components of this graph are complete. Example 2: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] Output: 1 Explanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.   Constraints: 1 <= n <= 50 0 <= edges.length <= n * (n - 1) / 2 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no repeated edges.
class Solution(object): def countCompleteComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ class D: def __init__(self, n): self.p, self.c = [0] * n, [0] * n for i in range(n): self.p[i], self.c[i] = i, 1 def f(self, a): r = self.p[a] while r != self.p[r]: r = self.p[r] while a != self.p[a]: a, self.p[a] = self.p[a], r return r def u(self, a, b): if self.f(a) != self.f(b): if self.c[self.f(a)] >= self.c[self.f(b)]: self.c[self.f(a)], self.p[self.f(b)] = self.c[self.f(a)] + self.c[self.f(b)], self.f(a) else: self.c[self.f(b)], self.p[self.f(a)] = self.c[self.f(b)] + self.c[self.f(a)], self.f(b) def g(self, a): return self.c[self.f(a)] d, c, g, r = D(n), [0] * n, [0] * n, 0 for e, f in edges: d.u(e, f) for i in range(n): c[d.f(i)] = d.g(d.f(i)) for e in edges: g[d.f(e[0])] += 1 for i in range(n): r += 1 if c[i] > 0 and g[i] == c[i] * (c[i] - 1) / 2 else 0 return r
53b78b
9460eb
You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices.   Example 1: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] Output: 3 Explanation: From the picture above, one can see that all of the components of this graph are complete. Example 2: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] Output: 1 Explanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.   Constraints: 1 <= n <= 50 0 <= edges.length <= n * (n - 1) / 2 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no repeated edges.
class Solution: def countCompleteComponents(self, n, edges): parent = list(range(n)) size = [1] * n edge_count = [0] * n def find(x): if parent[x] != x: parent[x] = find(parent[x]) return parent[x] def union(x, y): rootX = find(x) rootY = find(y) if rootX != rootY: if size[rootX] < size[rootY]: rootX, rootY = rootY, rootX parent[rootY] = rootX size[rootX] += size[rootY] for x, y in edges: if find(x) != find(y): union(x, y) edge_count[find(x)] += 1 return sum(edge_count[i] == size[i] * (size[i] - 1) // 2 for i in range(n) if parent[i] == i)
1251c7
ddc812
There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice that the distance between the two cities is the number of edges in the path between them.   Example 1: Input: n = 4, edges = [[1,2],[2,3],[2,4]] Output: [3,4,0] Explanation: The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. Example 2: Input: n = 2, edges = [[1,2]] Output: [1] Example 3: Input: n = 3, edges = [[1,2],[2,3]] Output: [2,1]   Constraints: 2 <= n <= 15 edges.length == n-1 edges[i].length == 2 1 <= ui, vi <= n All pairs (ui, vi) are distinct.
class DSU: def __init__(self, N): self.par = list(range(N)) self.sz = [1] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return False if self.sz[xr] < self.sz[yr]: xr, yr = yr, xr self.par[yr] = xr self.sz[xr] += self.sz[yr] return True def size(self, x): return self.sz[self.find(x)] class Solution(object): def countSubgraphsForEachDiameter(self, N, edges): graph = [[] for _ in xrange(N)] for i,(u,v) in enumerate(edges): u-=1 v-=1 graph[u].append(v) graph[v].append(u) edges[i] = [u,v] #dsu = DSU() def bfs(source, mask): queue = [[source, None, 0]] for node, par, d in queue: for nei in graph[node]: if nei != par and mask[nei] == '1': queue.append([nei, node, d + 1]) return node, d ans = [0] * N for mask in xrange(1, 1 << N): bmask = bin(mask)[2:][::-1] if len(bmask) < N: bmask = bmask + '0' * (N - len(bmask)) popcount = bmask.count('1') root = bmask.index('1') ecount = 0 for u,v in edges: if bmask[u]==bmask[v]=='1': ecount += 1 if ecount + 1 == popcount: # find max distance # print("mask", bmask, mask) v1, d1 = bfs(root, bmask) v2, d2 = bfs(v1, bmask) ans[d2] += 1 # print('a', ans) ans.pop(0) return ans
249543
ddc812
There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice that the distance between the two cities is the number of edges in the path between them.   Example 1: Input: n = 4, edges = [[1,2],[2,3],[2,4]] Output: [3,4,0] Explanation: The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. Example 2: Input: n = 2, edges = [[1,2]] Output: [1] Example 3: Input: n = 3, edges = [[1,2],[2,3]] Output: [2,1]   Constraints: 2 <= n <= 15 edges.length == n-1 edges[i].length == 2 1 <= ui, vi <= n All pairs (ui, vi) are distinct.
class CGraph() : def __init__(self, edges) : # self.du_dict = collections.defaultdict(lambda:0) self.link_dict = collections.defaultdict(lambda:[]) for s, e in edges : # self.du_dict[s] += 1 # self.du_dict[e] += 1 self.link_dict[s].append(e) self.link_dict[e].append(s) def bfs(self, source, end=None, ignore_set=set()) : """ 单源最短路径,可以设置是否有终点 """ visited = {source:0} to_visit = [[0, source]] while len(to_visit) > 0 : cost, pnow = to_visit.pop(0) if pnow == end : return cost for pnext in self.link_dict[pnow] : if pnext in visited : continue if pnext in ignore_set : continue visited[pnext] = cost+1 to_visit.append([cost+1, pnext]) return visited class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: graph = CGraph(edges) distances = {i:graph.bfs(i) for i in range(1, n+1)} to_ret = [0] * (n-1) for di in range((1<<n)) : its = [i+1 for i in range(n) if (1<<i) & di > 0] if len(its) < 2 : continue ig_set = set(range(1, n+1))-set(its) dtt = graph.bfs(its[0], ignore_set=ig_set) if len(dtt) < len(its) : continue max_dis = 0 for ia in range(len(its)) : for ib in range(ia+1, len(its)) : a = its[ia] b = its[ib] max_dis = max(max_dis, distances[a][b]) to_ret[max_dis-1] += 1 return to_ret
d16ab6
79318b
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.   Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element.   Constraints: 1 <= nums.length <= 100000 nums[i] is either 0 or 1.
class Solution(object): def longestSubarray(self, nums): """ :type nums: List[int] :rtype: int """ cnt1, cnt2, ans = 0, 0, 0 for num in nums: if num == 1: cnt1 += 1 cnt2 += 1 ans = max(ans, cnt1, cnt2) continue cnt2 = cnt1 cnt1 = 0 return min(ans, len(nums) - 1)
2e059b
79318b
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.   Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element.   Constraints: 1 <= nums.length <= 100000 nums[i] is either 0 or 1.
class Solution: def longestSubarray(self, nums: List[int]) -> int: if all(num == 1 for num in nums): return sum(nums) - 1 res, d, not_d = 0, 0, 0 for i, num in enumerate(nums): if num == 0: d = not_d not_d = 0 else: not_d += 1 d += 1 res = max(res, d, not_d) return res
8ff14e
571fd5
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 100000 genetic values, each represented by an integer in the inclusive range [1, 100000]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes.   Example 1: Input: parents = [-1,0,0,2], nums = [1,2,3,4] Output: [5,1,1,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value. - 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value. - 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value. - 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value. Example 2: Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3] Output: [7,1,1,4,2,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value. - 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value. - 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value. - 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value. - 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value. - 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value. Example 3: Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8] Output: [1,1,1,1,1,1,1] Explanation: The value 1 is missing from all the subtrees.   Constraints: n == parents.length == nums.length 2 <= n <= 100000 0 <= parents[i] <= n - 1 for i != 0 parents[0] == -1 parents represents a valid tree. 1 <= nums[i] <= 100000 Each nums[i] is distinct.
class Solution(object): def smallestMissingValueSubtree(self, parents, nums): """ :type parents: List[int] :type nums: List[int] :rtype: List[int] """ n = len(parents) loc = {v: i for i, v in enumerate(nums)} ans = [1] * n if 1 not in loc: return ans found_gene = [False] * (3+max(nums)) h = 1 adj = [[] for _ in xrange(n)] for child, par in enumerate(parents): if par >= 0: adj[par].append(child) lowest_missing = 1 prv = -1 cur = loc[1] while cur >= 0: q = [cur] while q: u = q.pop() found_gene[nums[u]] = True for v in adj[u]: if v == prv: continue q.append(v) while found_gene[lowest_missing]: lowest_missing += 1 ans[cur] = lowest_missing prv = cur cur = parents[cur] return ans
e80120
571fd5
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 100000 genetic values, each represented by an integer in the inclusive range [1, 100000]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes.   Example 1: Input: parents = [-1,0,0,2], nums = [1,2,3,4] Output: [5,1,1,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value. - 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value. - 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value. - 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value. Example 2: Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3] Output: [7,1,1,4,2,1] Explanation: The answer for each subtree is calculated as follows: - 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value. - 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value. - 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value. - 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value. - 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value. - 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value. Example 3: Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8] Output: [1,1,1,1,1,1,1] Explanation: The value 1 is missing from all the subtrees.   Constraints: n == parents.length == nums.length 2 <= n <= 100000 0 <= parents[i] <= n - 1 for i != 0 parents[0] == -1 parents represents a valid tree. 1 <= nums[i] <= 100000 Each nums[i] is distinct.
class Solution: def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]: s = set(nums) gen = -1 for i in range(1, (10**5)+1): if i not in s: gen = i break d = defaultdict(list) for i in range(len(parents)): d[parents[i]].append(i) ans = [1] * len(nums) path = [] def dfs(index): if nums[index] == 1: path.append(index) return True for c in d[index]: if dfs(c): path.append(index) return True return False childS = set() @cache def dp(index): childS.add(nums[index]) for c in d[index]: dp(c) dfs(0) #print(path) minGen = 1 for index in path: dp(index) while minGen in childS: minGen += 1 ans[index] = minGen return ans
28bb89
0cf3f0
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.   Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] Example 2: Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4.   Constraints: 1 <= hand.length <= 10000 0 <= hand[i] <= 10^9 1 <= groupSize <= hand.length   Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
from collections import defaultdict class Solution: def isNStraightHand(self, hand, W): """ :type hand: List[int] :type W: int :rtype: bool """ c = defaultdict(int) for x in hand: c[x] += 1 for x in sorted(hand): if c[x]: for i in range(W): if c[x + i]: c[x + i] -= 1 else: return False return sum(c.values()) == 0
6ca597
0cf3f0
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.   Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] Example 2: Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4.   Constraints: 1 <= hand.length <= 10000 0 <= hand[i] <= 10^9 1 <= groupSize <= hand.length   Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
from collections import defaultdict class Solution(object): def isNStraightHand(self, hand, W): """ :type hand: List[int] :type W: int :rtype: bool """ n = len(hand) if n%W != 0: return False hand.sort() cts = defaultdict(int) for v in hand: cts[v] += 1 for v in hand: if cts[v] == 0: continue for j in xrange(W): if cts[v+j] == 0: return False cts[v+j] -= 1 return True