sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
300006
026b3f
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally.   Example 1: Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 43 Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1]. - The road (0,1) has an importance of 2 + 4 = 6. - The road (1,2) has an importance of 4 + 5 = 9. - The road (2,3) has an importance of 5 + 3 = 8. - The road (0,2) has an importance of 2 + 5 = 7. - The road (1,3) has an importance of 4 + 3 = 7. - The road (2,4) has an importance of 5 + 1 = 6. The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43. It can be shown that we cannot obtain a greater total importance than 43. Example 2: Input: n = 5, roads = [[0,3],[2,4],[1,3]] Output: 20 Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1]. - The road (0,3) has an importance of 4 + 5 = 9. - The road (2,4) has an importance of 2 + 1 = 3. - The road (1,3) has an importance of 3 + 5 = 8. The total importance of all roads is 9 + 3 + 8 = 20. It can be shown that we cannot obtain a greater total importance than 20.   Constraints: 2 <= n <= 5 * 10000 1 <= roads.length <= 5 * 10000 roads[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate roads.
class Solution: def maximumImportance(self, n: int, e: List[List[int]]) -> int: d = [0 for i in range(n)] for x, y in e: d[x] += 1 d[y] += 1 d.sort() z = 0 for i in range(n): z += (i + 1) * d[i] return z
364a7c
026b3f
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally.   Example 1: Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 43 Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1]. - The road (0,1) has an importance of 2 + 4 = 6. - The road (1,2) has an importance of 4 + 5 = 9. - The road (2,3) has an importance of 5 + 3 = 8. - The road (0,2) has an importance of 2 + 5 = 7. - The road (1,3) has an importance of 4 + 3 = 7. - The road (2,4) has an importance of 5 + 1 = 6. The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43. It can be shown that we cannot obtain a greater total importance than 43. Example 2: Input: n = 5, roads = [[0,3],[2,4],[1,3]] Output: 20 Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1]. - The road (0,3) has an importance of 4 + 5 = 9. - The road (2,4) has an importance of 2 + 1 = 3. - The road (1,3) has an importance of 3 + 5 = 8. The total importance of all roads is 9 + 3 + 8 = 20. It can be shown that we cannot obtain a greater total importance than 20.   Constraints: 2 <= n <= 5 * 10000 1 <= roads.length <= 5 * 10000 roads[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate roads.
class Solution(object): def maximumImportance(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ degree = [0]*n for road in roads: degree[road[0]] += 1 degree[road[1]] += 1 # print degree degree.sort() # print degree ans = 0 for i in range(n): ans += degree[i]*(i+1) return ans
af94d8
271c08
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0   Example 1: Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 Example 2: Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] Output: 1   Constraints: n == nums1.length n == nums2.length n == nums3.length n == nums4.length 1 <= n <= 200 -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
class Solution(object): def fourSumCount(self, A, B, C, D): tsum = {} for a in A: for b in B: tsum[a+b] = tsum.get(a+b,0)+1 r = 0 for c in C: for d in D: r += tsum.get(-c-d,0) return r """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """
907e9c
7372ad
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s. For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)   Example 1: Input: s = "(123)" Output: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"] Example 2: Input: s = "(0123)" Output: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed. Example 3: Input: s = "(00011)" Output: ["(0, 0.011)","(0.001, 1)"]   Constraints: 4 <= s.length <= 12 s[0] == '(' and s[s.length - 1] == ')'. The rest of s are digits.
class Solution(object): def ambiguousCoordinates(self, S): """ :type S: str :rtype: List[str] """ s=S[1:-1] res=[] for i in range(1,len(s)): list1=self.get(s[:i]) if list1: list2=self.get(s[i:]) for x in list1: for y in list2: res.append("("+x+", "+y+")") return res def get(self, s): if not s: return [] if len(s)==1: return [s] if s[0]=="0" and s[-1]=="0": return [] res=[] if s[0]=="0": res.append(s[:1]+"."+s[1:]) elif s[-1]=="0": res.append(s) else: res.append(s) for i in range(1, len(s)): res.append(s[:i]+"."+s[i:]) return res
198120
7372ad
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s. For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)   Example 1: Input: s = "(123)" Output: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"] Example 2: Input: s = "(0123)" Output: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed. Example 3: Input: s = "(00011)" Output: ["(0, 0.011)","(0.001, 1)"]   Constraints: 4 <= s.length <= 12 s[0] == '(' and s[s.length - 1] == ')'. The rest of s are digits.
class Solution: def ambiguousCoordinates(self, S): """ :type S: str :rtype: List[str] """ if not S: return [] res = {} S = S[1:-1] n = len(S) for i in range(1, n): left = S[:i] right = S[i:] if len(left)==1: for y in range(1, len(right)): rl = right[:y] rr = right[y:] if self.isValidI(left) and self.isValidI(rl) and self.isValidD(rr): temp = '(%s, %s.%s)' % (left, rl, rr) res[temp] = True elif len(right)==1: for x in range(1, len(left)): ll = left[:x] lr = left[x:] if self.isValidI(right) and self.isValidI(ll) and self.isValidD(lr): temp = '(%s.%s, %s)' % (ll, lr, right) res[temp] = True else: for x in range(1, len(left)): for y in range(1, len(right)): ll = left[:x] lr = left[x:] rl = right[:y] rr = right[y:] if self.isValidI(left) and self.isValidI(rl) and self.isValidD(rr): temp = '(%s, %s.%s)' % (left, rl, rr) res[temp] = True if self.isValidI(right) and self.isValidI(ll) and self.isValidD(lr): temp = '(%s.%s, %s)' % (ll, lr, right) res[temp] = True if self.isValidI(ll) and self.isValidI(rl) and self.isValidD(lr) and self.isValidD(rr): temp = '(%s.%s, %s.%s)' % (ll, lr, rl, rr) res[temp] = True if self.isValidI(left) and self.isValidI(right): cur = '(%s, %s)' % (str(left), str(right)) res[cur] = True rrr = [] for k in res.keys(): rrr.append(k) return rrr def isValidI(self, s): if int(s) == 0 and len(s) > 1: return False if len(s)>1 and s[0] == '0': return False return True def isValidD(self, s): if int(s) == 0: return False if s[-1] == '0': return False return True
fedd2f
056ccc
There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index i (0-indexed) is: reward1[i] if the first mouse eats it. reward2[i] if the second mouse eats it. You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k. Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.   Example 1: Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 Output: 15 Explanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. Example 2: Input: reward1 = [1,1], reward2 = [1,1], k = 2 Output: 2 Explanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve.   Constraints: 1 <= n == reward1.length == reward2.length <= 100000 1 <= reward1[i], reward2[i] <= 1000 0 <= k <= n
class Solution(object): def miceAndCheese(self, reward1, reward2, k): """ :type reward1: List[int] :type reward2: List[int] :type k: int :rtype: int """ a, r = [[] * 2 for _ in range(len(reward1))], 0 for i in range(len(reward1)): a[i] = [reward2[i] - reward1[i], reward1[i], reward2[i]] a.sort() for i in range(len(reward1)): r += a[i][1] if i < k else a[i][2] return r
d17a78
056ccc
There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index i (0-indexed) is: reward1[i] if the first mouse eats it. reward2[i] if the second mouse eats it. You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k. Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.   Example 1: Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 Output: 15 Explanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. Example 2: Input: reward1 = [1,1], reward2 = [1,1], k = 2 Output: 2 Explanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve.   Constraints: 1 <= n == reward1.length == reward2.length <= 100000 1 <= reward1[i], reward2[i] <= 1000 0 <= k <= n
class Solution: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: base = sum(reward2) n = len(reward1) diffs = [] for i in range(n): diffs.append(reward1[i] - reward2[i]) diffs.sort() while k: base += diffs.pop() k -= 1 return base
ca31c2
19d4fc
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.   Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9] Example 2: Input: mat = [[1,2],[3,4]] Output: [1,2,3,4]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 10000 1 <= m * n <= 10000 -100000 <= mat[i][j] <= 100000
class Solution(object): def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ h=len(matrix) if h == 0: return [] w=len(matrix[0]) ans=[] for a in range(0,h+w-1): if a % 2 ==0: d = (-1,1) x0=(a if a < h else h-1) y0=(0 if a < h else a-h+1) else: d = (1,-1) x0=(0 if a < w else a-w+1) y0=(a if a < w else w-1) while x0 >=0 and x0<h and y0>=0 and y0<w: ans.append(matrix[x0][y0]) x0+=d[0] y0+=d[1] return ans
451e52
db58d0
You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n. However, there are city restrictions on the heights of the new buildings: The height of each building must be a non-negative integer. The height of the first building must be 0. The height difference between any two adjacent buildings cannot exceed 1. Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti. It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions. Return the maximum possible height of the tallest building.   Example 1: Input: n = 5, restrictions = [[2,1],[4,1]] Output: 2 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2. Example 2: Input: n = 6, restrictions = [] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5. Example 3: Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.   Constraints: 2 <= n <= 10^9 0 <= restrictions.length <= min(n - 1, 100000) 2 <= idi <= n idi is unique. 0 <= maxHeighti <= 10^9
def rectify(limits): for i in range(1, len(limits)): if limits[i][1] - limits[i-1][1] > limits[i][0] - limits[i-1][0]: limits[i][1] = limits[i-1][1] + limits[i][0] - limits[i-1][0] for i in range(len(limits)-1)[::-1]: if limits[i][1] - limits[i+1][1] > limits[i+1][0] - limits[i][0]: limits[i][1] = limits[i+1][1] + limits[i+1][0] - limits[i][0] return limits def get_max_height(lim1, lim2): lo, lo_height = lim1 hi, hi_height = lim2 max_height, min_height = sorted([lo_height, hi_height]) return max_height + (hi - lo - (max_height - min_height)) // 2 class Solution: def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int: restrictions.append([1, 0]) restrictions.sort() if restrictions[-1][0] != n: restrictions.append([n, n]) restrictions = rectify(restrictions) res = 0 for i in range(1, len(restrictions)): res = max(res, get_max_height(restrictions[i-1], restrictions[i])) return res
349e06
db58d0
You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n. However, there are city restrictions on the heights of the new buildings: The height of each building must be a non-negative integer. The height of the first building must be 0. The height difference between any two adjacent buildings cannot exceed 1. Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti. It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions. Return the maximum possible height of the tallest building.   Example 1: Input: n = 5, restrictions = [[2,1],[4,1]] Output: 2 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2. Example 2: Input: n = 6, restrictions = [] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5. Example 3: Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.   Constraints: 2 <= n <= 10^9 0 <= restrictions.length <= min(n - 1, 100000) 2 <= idi <= n idi is unique. 0 <= maxHeighti <= 10^9
class Solution(object): def maxBuilding(self, n, A): A.append([1, 0]) A.sort() if A[-1][0] != n: A.append([n, float('inf')]) k = len(A) res = 0 for i in xrange(1, k): A[i][1] = min(A[i][1], A[i - 1][1] + A[i][0] - A[i - 1][0]) for i in xrange(k - 2, -1, -1): A[i][1] = min(A[i][1], A[i + 1][1] + A[i + 1][0] - A[i][0]) for i in xrange(1, k): x = A[i][0] - A[i - 1][0] - abs(A[i][1] - A[i - 1][1]) res = max(res, x / 2 + max(A[i][1], A[i - 1][1])) return res
2d05dc
603200
Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.   Example 1: Input: s1 = "abc", s2 = "xya" Output: true Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc". Example 2: Input: s1 = "abe", s2 = "acd" Output: false Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa. Example 3: Input: s1 = "leetcodee", s2 = "interview" Output: true   Constraints: s1.length == n s2.length == n 1 <= n <= 10^5 All strings consist of lowercase English letters.
class Solution: def checkIfCanBreak(self, s1: str, s2: str) -> bool: s1=list(s1) s2=list(s2) s1.sort() s2.sort() f1,f2=True,True for x,y in zip(s1,s2): if x>y: f1=False if x<y: f2=False return f1 or f2
e44272
603200
Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.   Example 1: Input: s1 = "abc", s2 = "xya" Output: true Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc". Example 2: Input: s1 = "abe", s2 = "acd" Output: false Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa. Example 3: Input: s1 = "leetcodee", s2 = "interview" Output: true   Constraints: s1.length == n s2.length == n 1 <= n <= 10^5 All strings consist of lowercase English letters.
class Solution(object): def checkIfCanBreak(self, s1, s2): # check if permutation of s1 can majorize s2 def cvt(s): count = [0] * 26 for c in s: ci = ord(c) - ord('a') count[ci] += 1 return count def majorize(s1, s2): count1 = cvt(s1) count2 = cvt(s2) for i, x in enumerate(count2): for j in range(i + 1): d = min(count1[j], x) count1[j] -= d x -= d if x == 0: break if x: return False return True return majorize(s1, s2) or majorize(s2, s1)
aaad57
7b71e8
There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique. You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that: The room has a size of at least minSizej, and abs(id - preferredj) is minimized, where abs(x) is the absolute value of x. If there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1. Return an array answer of length k where answer[j] contains the answer to the jth query.   Example 1: Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]] Output: [3,-1,3] Explanation: The answers to the queries are as follows: Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3. Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1. Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3. Example 2: Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]] Output: [2,1,3] Explanation: The answers to the queries are as follows: Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2. Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller. Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.   Constraints: n == rooms.length 1 <= n <= 100000 k == queries.length 1 <= k <= 10000 1 <= roomIdi, preferredj <= 10^7 1 <= sizei, minSizej <= 10^7
from sortedcontainers import SortedList class Solution: def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]: Q = len(queries) ans = [-1] * Q events = [] for i, s in rooms: events.append((-s, 0, i, -1)) for index, (p, m) in enumerate(queries): events.append((-m, 1, p, index)) events.sort() sl = SortedList() for s, t, c, d in events: if t == 0: sl.add(c) else: index = sl.bisect_left(c) cur = -1 if 0 <= index < len(sl): cur = sl[index] index -= 1 if 0 <= index < len(sl): if abs(sl[index] - c) <= abs(cur - c): cur = sl[index] ans[d] = cur return ans
45a182
7b71e8
There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique. You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that: The room has a size of at least minSizej, and abs(id - preferredj) is minimized, where abs(x) is the absolute value of x. If there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1. Return an array answer of length k where answer[j] contains the answer to the jth query.   Example 1: Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]] Output: [3,-1,3] Explanation: The answers to the queries are as follows: Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3. Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1. Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3. Example 2: Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]] Output: [2,1,3] Explanation: The answers to the queries are as follows: Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2. Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller. Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.   Constraints: n == rooms.length 1 <= n <= 100000 k == queries.length 1 <= k <= 10000 1 <= roomIdi, preferredj <= 10^7 1 <= sizei, minSizej <= 10^7
class Solution(object): def closestRoom(self, rooms, queries): """ :type rooms: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ arr = [] queries = [[queries[i][0],queries[i][1],i] for i in range(len(queries))] queries.sort(key=lambda x:-x[1]) rooms.sort(key=lambda x:-x[1]) left = 0 res = [-1 for _ in range(len(queries))] for pre,size,i in queries: while left<len(rooms) and rooms[left][1]>=size: bisect.insort(arr,rooms[left][0]) left+=1 if len(arr)==0: continue index = bisect.bisect_left(arr,pre) if index==0: res[i] = arr[index] elif index==len(arr): res[i] = arr[-1] else: if (pre-arr[index-1])<=(arr[index]-pre): res[i] = arr[index-1] else: res[i] = arr[index] return res
8d3492
b67c20
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right. Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3 Output: 2 Explanation: There are two paths where the sum of the elements on the path is divisible by k. The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3. The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3. Example 2: Input: grid = [[0,0]], k = 5 Output: 1 Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5. Example 3: Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1 Output: 10 Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 5 * 10000 1 <= m * n <= 5 * 10000 0 <= grid[i][j] <= 100 1 <= k <= 50
class Solution(object): def numberOfPaths(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: int """ d, m, n = [[[0] * k for _ in grid[0]] for _ in grid], grid[0][0] % k, grid[0][0] % k d[0][0][m] = 1 for i in range(1, len(grid)): m, d[i][0][m] = (m + grid[i][0]) % k, 1 for j in range(1, len(grid[0])): n, d[0][j][n] = (n + grid[0][j]) % k, 1 for i in range(1, len(grid)): for j in range(1, len(grid[0])): for p in range(k): d[i][j][(p + grid[i][j]) % k] = (d[i][j][(p + grid[i][j]) % k] + d[i - 1][j][p]) % 1000000007 for p in range(k): d[i][j][(p + grid[i][j]) % k] = (d[i][j][(p + grid[i][j]) % k] + d[i][j - 1][p]) % 1000000007 return d[len(grid) - 1][len(grid[0]) - 1][0]
2194ea
b67c20
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right. Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3 Output: 2 Explanation: There are two paths where the sum of the elements on the path is divisible by k. The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3. The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3. Example 2: Input: grid = [[0,0]], k = 5 Output: 1 Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5. Example 3: Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1 Output: 10 Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 5 * 10000 1 <= m * n <= 5 * 10000 0 <= grid[i][j] <= 100 1 <= k <= 50
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: mod = 10 ** 9 + 7 n, m = len(grid), len(grid[0]) dp = [[[0] * k for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if i == 0 and j == 0: dp[i][j][grid[i][j] % k] = 1 continue for u in range(k): if i == 0: dp[i][j][u] = dp[i][j - 1][(u + k * 100 - grid[i][j]) % k] elif j == 0: dp[i][j][u] = dp[i - 1][j][(u + k * 100 - grid[i][j]) % k] else: dp[i][j][u] = dp[i][j - 1][(u + k * 100 - grid[i][j]) % k] + dp[i - 1][j][(u + k * 100 - grid[i][j]) % k] dp[i][j][u] %= mod return dp[-1][-1][0]
b23e37
f1100b
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.   Example 1: Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3. Example 2: Input: m = 2, n = 3, k = 6 Output: 6 Explanation: The 6th smallest number is 6.   Constraints: 1 <= m, n <= 3 * 10000 1 <= k <= m * n
class Solution(object): def findKthNumber(self, m, n, k): def accepted(x): #is there at least k numbers <= x? ans = 0 for i in xrange(1, m+1): ans += min( (x-1) / i, n ) return ans < k lo, hi = 1, m*n + 1 while lo < hi: mi = (lo + hi) / 2 ami = accepted(mi) if ami: lo = mi + 1 else: hi = mi return lo - 1
a35fd0
f1100b
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.   Example 1: Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3. Example 2: Input: m = 2, n = 3, k = 6 Output: 6 Explanation: The 6th smallest number is 6.   Constraints: 1 <= m, n <= 3 * 10000 1 <= k <= m * n
class Solution: def findKthNumber(self, m, n, k): """ :type m: int :type n: int :type k: int :rtype: int """ def rank(s): r = 0 for i in range(1, m + 1): r += min(n, s//i) return r left = 1 right = n*m if k == 1: return left while right - left > 1: mid = (left + right)//2 r = rank(mid) if r < k: left = mid else: right = mid return right
ed57bc
deae9f
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.   Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Explanation: The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf. Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4   Constraints: 1 <= books.length <= 1000 1 <= thicknessi <= shelfWidth <= 1000 1 <= heighti <= 1000
class Solution(object): def minHeightShelves(self, books, shelf_width): """ :type books: List[List[int]] :type shelf_width: int :rtype: int """ memo={} def helper(idx): if idx>=len(books): return 0 if idx==len(books)-1: return books[idx][1] if idx in memo: return memo[idx] ans=1000001 curlen=0 curhigh=0 idxt=idx while idxt<len(books): curlen+=books[idxt][0] curhigh=max(curhigh,books[idxt][1]) if curlen<=shelf_width: ans=min(ans,curhigh+helper(idxt+1)) idxt+=1 else: break memo[idx]=ans return ans return helper(0)
05d19a
deae9f
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.   Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Explanation: The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf. Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4   Constraints: 1 <= books.length <= 1000 1 <= thicknessi <= shelfWidth <= 1000 1 <= heighti <= 1000
from math import inf class Solution: def minHeightShelves(self, books, width): minheight = {0: 0} nbooks = len (books) for n in range (1, nbooks+1): # decide height for first n books minheight[n] = inf maxh = 0 maxw = 0 for i in range (1, n+1): maxh = max (maxh, books[n-i][1]) maxw += books[n-i][0] if maxw <= width: minheight[n] = min (minheight[n], maxh + minheight[n - i]) else: break return minheight[nbooks]
505e0b
449868
You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].   Example 1: Input: arr = [1,2,3,5], k = 3 Output: [2,5] Explanation: The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5. Example 2: Input: arr = [1,7], k = 1 Output: [1,7]   Constraints: 2 <= arr.length <= 1000 1 <= arr[i] <= 3 * 10000 arr[0] == 1 arr[i] is a prime number for i > 0. All the numbers of arr are unique and sorted in strictly increasing order. 1 <= k <= arr.length * (arr.length - 1) / 2   Follow up: Can you solve the problem with better than O(n2) complexity?
class Solution(object): def kthSmallestPrimeFraction(self, A, K): n = len(A) A.sort() # binary search for the result def num_less_eq_to(val): x, y = 0, 1 ans = 0 while x < n: while y <= x: y += 1 while y < n and A[x] > A[y] * val: y += 1 ans += n-y x += 1 return ans lo, hi = 0.0, 1.0 while lo + 1e-7 < hi: mid = (lo + hi) / 2 if num_less_eq_to(mid) >= K: hi = mid else: lo = mid res = hi # zig-zag to find the element x, y = 0, 1 while True: while y <= x: y += 1 sign = float(A[x])/A[y] - res if abs(sign) < 1e-7: return [A[x], A[y]] if sign > 0: y += 1 else: x += 1
a8af15
449868
You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].   Example 1: Input: arr = [1,2,3,5], k = 3 Output: [2,5] Explanation: The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5. Example 2: Input: arr = [1,7], k = 1 Output: [1,7]   Constraints: 2 <= arr.length <= 1000 1 <= arr[i] <= 3 * 10000 arr[0] == 1 arr[i] is a prime number for i > 0. All the numbers of arr are unique and sorted in strictly increasing order. 1 <= k <= arr.length * (arr.length - 1) / 2   Follow up: Can you solve the problem with better than O(n2) complexity?
class Solution: def kthSmallestPrimeFraction(self, A, K): """ :type A: List[int] :type K: int :rtype: List[int] """ from heapq import heappush, heappop heap = [] for i in range(1, len(A)): heappush(heap, (1/A[i], 0, i)) for _ in range(K): _, p_i, q_i = heappop(heap) #print(A[p_i], A[q_i]) if p_i+1 < q_i: heappush(heap, (A[p_i+1]/A[q_i], p_i+1, q_i)) return [A[p_i], A[q_i]]
edb911
38b0a6
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice. Note that the digits '0' and '1' do not map to any letters, so Alice does not use them. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. For example, when Alice sent the message "bob", Bob received the string "2266622". Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: pressedKeys = "22233" Output: 8 Explanation: The possible text messages Alice could have sent are: "aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce". Since there are 8 possible messages, we return 8. Example 2: Input: pressedKeys = "222222222222222222222222222222222222" Output: 82876089 Explanation: There are 2082876103 possible text messages Alice could have sent. Since we need to return the answer modulo 10^9 + 7, we return 2082876103 % (10^9 + 7) = 82876089.   Constraints: 1 <= pressedKeys.length <= 100000 pressedKeys only consists of digits from '2' - '9'.
class Solution: def countTexts(self, s: str) -> int: kcnt=[0,0,3,3,3,3,3,4,3,4] sz=len(s) dp=[0]*sz MOD=int(1e9+7) for i, c in enumerate(s): for j in range(1,kcnt[int(c)]+1): if i-j+1<0: break if s[i]==s[i-j+1]: dp[i]+=dp[i-j] if i-j>=0 else 1 dp[i]%=MOD else: break return dp[-1]
76991f
38b0a6
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice. Note that the digits '0' and '1' do not map to any letters, so Alice does not use them. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. For example, when Alice sent the message "bob", Bob received the string "2266622". Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: pressedKeys = "22233" Output: 8 Explanation: The possible text messages Alice could have sent are: "aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce". Since there are 8 possible messages, we return 8. Example 2: Input: pressedKeys = "222222222222222222222222222222222222" Output: 82876089 Explanation: There are 2082876103 possible text messages Alice could have sent. Since we need to return the answer modulo 10^9 + 7, we return 2082876103 % (10^9 + 7) = 82876089.   Constraints: 1 <= pressedKeys.length <= 100000 pressedKeys only consists of digits from '2' - '9'.
class Solution(object): def countTexts(self, pressedKeys): """ :type pressedKeys: str :rtype: int """ r = [0] * len(pressedKeys) + [1] for i in range(len(pressedKeys) - 1, -1, -1): j = i while j < len(pressedKeys) and j < i + (4 if pressedKeys[i] == '7' or pressedKeys[i] == '9' else 3) and pressedKeys[j] == pressedKeys[i]: r[i], j = (r[i] + r[j + 1]) % 1000000007, j + 1 return r[0]
e81da6
e8ce38
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Add a positive integer to an element of a given index in the array nums2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length). Implement the FindSumPairs class: FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2. void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val. int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.   Example 1: Input ["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"] [[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]] Output [null, 8, null, 2, 1, null, null, 11] Explanation FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]); findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4] findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4] findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4] findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4   Constraints: 1 <= nums1.length <= 1000 1 <= nums2.length <= 100000 1 <= nums1[i] <= 10^9 1 <= nums2[i] <= 100000 0 <= index < nums2.length 1 <= val <= 100000 1 <= tot <= 10^9 At most 1000 calls are made to add and count each.
from typing import * class FindSumPairs: def __init__(self, nums1: List[int], nums2: List[int]): self.cnt = {} self.n2 = nums2; self.n1 = nums1 for i in self.n2: self.cnt[i] = 0 for i in self.n2: self.cnt[i] += 1 def add(self, index: int, val: int) -> None: ov = self.n2[index] self.n2[index] += val; nv = self.n2[index] self.cnt[ov] -= 1 if nv not in self.cnt: self.cnt[nv] = 1 else: self.cnt[nv] += 1 def count(self, tot: int) -> int: x = 0 for i in self.n1: if tot - i in self.cnt: x += self.cnt[tot-i] return x # Your FindSumPairs object will be instantiated and called as such: # obj = FindSumPairs(nums1, nums2) # obj.add(index,val) # param_2 = obj.count(tot)
d637c9
e8ce38
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Add a positive integer to an element of a given index in the array nums2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length). Implement the FindSumPairs class: FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2. void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val. int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.   Example 1: Input ["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"] [[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]] Output [null, 8, null, 2, 1, null, null, 11] Explanation FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]); findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4] findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4] findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4] findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4   Constraints: 1 <= nums1.length <= 1000 1 <= nums2.length <= 100000 1 <= nums1[i] <= 10^9 1 <= nums2[i] <= 100000 0 <= index < nums2.length 1 <= val <= 100000 1 <= tot <= 10^9 At most 1000 calls are made to add and count each.
from collections import Counter class FindSumPairs(object): def __init__(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] """ self.cnt1 = Counter(nums1) self.cnt2 = Counter(nums2) self.nums2 = nums2[:] def add(self, index, val): """ :type index: int :type val: int :rtype: None """ self.cnt2[self.nums2[index]] -= 1 self.nums2[index] += val self.cnt2[self.nums2[index]] += 1 def count(self, tot): """ :type tot: int :rtype: int """ return sum(v*self.cnt2[tot-k] for k,v in self.cnt1.iteritems()) # Your FindSumPairs object will be instantiated and called as such: # obj = FindSumPairs(nums1, nums2) # obj.add(index,val) # param_2 = obj.count(tot)
04c8fc
5bd295
You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi. Return the minimum number of transactions required to settle the debt. Example 1: Input: transactions = [[0,1,10],[2,0,5]] Output: 2 Explanation: Person #0 gave person #1 $10. Person #2 gave person #0 $5. Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each. Example 2: Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]] Output: 1 Explanation: Person #0 gave person #1 $10. Person #1 gave person #0 $1. Person #1 gave person #2 $5. Person #2 gave person #0 $5. Therefore, person #1 only need to give person #0 $4, and all debt is settled. Constraints: 1 <= transactions.length <= 8 transactions[i].length == 3 0 <= fromi, toi < 12 fromi != toi 1 <= amounti <= 100
class Solution(object): def minTransfers(self, transactions): """ :type transactions: List[List[int]] :rtype: int """ d = {} for x, y, z in transactions: d[x] = d.get(x, 0) - z d[y] = d.get(y, 0) + z l1 = [] l2 = [] for key, val in d.items(): if val > 0: l1.append(val) elif val < 0: l2.append(-val) d = {} return self.recursive(l1, l2, d) def recursive(self, l1, l2, d): if not l1: return 0 key = (tuple(l1), tuple(l2)) if key in d: return d[key] res = float('inf') pay = l1[-1] for i in xrange(len(l2)): debt = l2[i] if debt < pay: l1[-1] -= debt l2.pop(i) tmp = 1 + self.recursive(l1, l2, d) l2.insert(i, debt) l1[-1] += debt elif debt == pay: l1.pop() l2.pop(i) tmp = 1 + self.recursive(l1, l2, d) l2.insert(i, debt) l1.append(pay) else: l1.pop() l2[i] -= pay tmp = 1 + self.recursive(l1, l2, d) l2[i] += pay l1.append(pay) res = min(tmp, res) d[key] = res return res
3fe2ba
7a7437
Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.   Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]]   Constraints: 1 <= nums.length <= 15 -100 <= nums[i] <= 100
class Solution(object): def findSubsequences(self, A): ans = self._findSubsequences(A) return [x for x in ans if len(x) > 1] def _findSubsequences(self, A): if A == []: return [()] ans = [] for left in self._findSubsequences(A[:-1]): ans.append(left) if not left or left[-1] <= A[-1]: ans.append(left + (A[-1],)) return list(set(ans)) """ :type nums: List[int] :rtype: List[List[int]] """
2222b0
ddee49
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.   Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]   Constraints: 1 <= nums.length <= 100000 1 <= nums[i].length <= 100000 1 <= sum(nums[i].length) <= 100000 1 <= nums[i][j] <= 100000
class Solution(object): def findDiagonalOrder(self, nums): """ :type nums: List[List[int]] :rtype: List[int] """ buckets = dict() for i in range(len(nums)-1,-1,-1): for j in range(len(nums[i])): if i + j not in buckets: buckets[i+j]=[] buckets[i+j].append(nums[i][j]) keys = list(buckets.keys()) keys.sort() ans = [] for key in keys: for x in buckets[key]: ans.append(x) return ans
98539d
ddee49
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.   Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]   Constraints: 1 <= nums.length <= 100000 1 <= nums[i].length <= 100000 1 <= sum(nums[i].length) <= 100000 1 <= nums[i][j] <= 100000
from collections import defaultdict class Solution: def findDiagonalOrder(self, A: List[List[int]]) -> List[int]: d = defaultdict(list) ans = [] maxD = 0 for iRow in range(len(A)): for iCol in range(len(A[iRow])): diag = iRow + iCol d[diag].append(A[iRow][iCol]) if maxD < diag: maxD = diag for diag in range(maxD+1): a = d[diag] for i in range(len(a)-1, -1, -1): ans.append(a[i]) return ans
c6b1eb
22a526
You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see.   Example 1: Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1] Output: 3 Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight. Example 2: Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1] Output: 4 Explanation: All points can be made visible in your field of view, including the one at your location. Example 3: Input: points = [[1,0],[2,1]], angle = 13, location = [1,1] Output: 1 Explanation: You can only see one of the two points, as shown above.   Constraints: 1 <= points.length <= 100000 points[i].length == 2 location.length == 2 0 <= angle < 360 0 <= posx, posy, xi, yi <= 100
class Solution: def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: to_ret_base = 0 to_ret = 0 lx, ly = location pts = [] for x, y in points : if x == lx and y == ly : to_ret_base += 1 continue db = y-ly lb = x-lx if lb == 0 and db > 0 : pts.append(90) elif lb == 0 and db < 0 : pts.append(-90) elif lb < 0 : lb = -lb arg = math.atan(db/lb) to_append = arg/math.pi*180 if to_append > 0 : to_append = 90 + 90 - to_append elif to_append < 0 : to_append = -90 + -90 - to_append else : to_append = 180 pts.append(to_append) else : arg = math.atan(db/lb) pts.append(arg/math.pi*180) pts = sorted(pts) pts = pts + [t+360 for t in pts] # print(pts) s, e = -1, 0 while e < len(pts) : s += 1 while e < len(pts) and pts[e] <= pts[s] + angle : e += 1 to_ret = max(e-s, to_ret) return to_ret + to_ret_base
c9cbf3
22a526
You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see.   Example 1: Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1] Output: 3 Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight. Example 2: Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1] Output: 4 Explanation: All points can be made visible in your field of view, including the one at your location. Example 3: Input: points = [[1,0],[2,1]], angle = 13, location = [1,1] Output: 1 Explanation: You can only see one of the two points, as shown above.   Constraints: 1 <= points.length <= 100000 points[i].length == 2 location.length == 2 0 <= angle < 360 0 <= posx, posy, xi, yi <= 100
from math import atan2, pi class Solution(object): def visiblePoints(self, points, angle, location): """ :type points: List[List[int]] :type angle: int :type location: List[int] :rtype: int """ mx, my = location ang = pi * angle / 180. + 1e-6 c = r = 0 a = [] for x, y in points: dx, dy = x - mx, y - my if dx == dy == 0: c += 1 continue th = atan2(dy, dx) a.append(th) a.append(th + 2*pi) a.sort() i = 0 for j in xrange(len(a)): while i < j and a[j] - a[i] > ang: i += 1 r = max(r, 1 + j - i) return c + r
567864
39951b
You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.   Example 1: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 Output: true Explanation: Circle and rectangle share the point (1,0). Example 2: Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 Output: false Example 3: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 Output: true   Constraints: 1 <= radius <= 2000 -10000 <= xCenter, yCenter <= 10000 -10000 <= x1 < x2 <= 10000 -10000 <= y1 < y2 <= 10000
class Solution: def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool: def dis(x1, y1, x2, y2): return (x1 - x2) ** 2 + (y1 - y2) ** 2 if x_center <= x1: if y_center <= y1: return dis(x_center, y_center, x1, y1) <= radius ** 2 elif y1 < y_center < y2: return x1 - x_center <= radius else: return dis(x_center, y_center, x1, y2) <= radius ** 2 elif x1 < x_center < x2: if y_center <= y1: return y1 - y_center <= radius elif y1 < y_center < y2: return True else: return y_center - y2 <= radius else: if y_center <= y1: return dis(x_center, y_center, x2, y1) <= radius ** 2 elif y1 < y_center < y2: return x_center - x2 <= radius else: return dis(x_center, y_center, x2, y2) <= radius ** 2
fe81c0
39951b
You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.   Example 1: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 Output: true Explanation: Circle and rectangle share the point (1,0). Example 2: Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 Output: false Example 3: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 Output: true   Constraints: 1 <= radius <= 2000 -10000 <= xCenter, yCenter <= 10000 -10000 <= x1 < x2 <= 10000 -10000 <= y1 < y2 <= 10000
class Solution(object): def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2): """ :type radius: int :type x_center: int :type y_center: int :type x1: int :type y1: int :type x2: int :type y2: int :rtype: bool """ #return the minimum distance between (x0, y0) and line (x1,y1) - (x2,y2) #the line either // to Ox or Oy def calDisSquare(x0,y0,x1,y1): return (x1 - x0)*(x1 - x0) + (y1 - y0)*(y1 - y0) def calMinDisSquare(x0,y0,x1,y1,x2,y2): if x1 == x2: if y0 >= min(y1,y2) and y0 <= max(y1,y2): return (x0 - x1)*(x0 - x1) return min(calDisSquare(x0,y0,x1,y1), calDisSquare(x0,y0,x2,y2)) else: if x0 >= min(x1,x2) and x0 <= max(x1,x2): return (y0 - y1)*(y0 - y1) return min(calDisSquare(x0,y0,x1,y1), calDisSquare(x0,y0,x2,y2)) if x_center >= x1 and x_center <= x2 and y_center >= y1 and y_center <= y2: return True d0 = calMinDisSquare(x_center, y_center, x1, y1, x1, y2) d1 = calMinDisSquare(x_center, y_center, x1, y1, x2, y1) d2 = calMinDisSquare(x_center, y_center, x1, y2, x2, y2) d3 = calMinDisSquare(x_center, y_center, x2, y1, x2, y2) return ( (radius*radius) >= min(d0,d1,d2,d3))
d64b63
63d02a
You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text. Return all possible synonymous sentences sorted lexicographically. Example 1: Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday" Output: ["I am cheerful today but was sad yesterday","I am cheerful today but was sorrow yesterday","I am happy today but was sad yesterday","I am happy today but was sorrow yesterday","I am joy today but was sad yesterday","I am joy today but was sorrow yesterday"] Example 2: Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday" Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"] Constraints: 0 <= synonyms.length <= 10 synonyms[i].length == 2 1 <= si.length, ti.length <= 10 si != ti text consists of at most 10 words. All the pairs of synonyms are unique. The words of text are separated by single spaces.
class Solution(object): def generateSentences(self, synonyms, text): graph = collections.defaultdict(list) for u, v in synonyms: graph[u].append(v) graph[v].append(u) def dfs(word): for nei in graph[word]: if nei not in seen: seen.add(nei) dfs(nei) A = text.split() B = [] for word in A: if word not in graph: B.append([word]) continue else: seen = {word} dfs(word) B.append(list(seen)) ans = [] for cand in itertools.product(*B): ans.append(" ".join(cand)) ans.sort() return ans
a5daab
63d02a
You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text. Return all possible synonymous sentences sorted lexicographically. Example 1: Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday" Output: ["I am cheerful today but was sad yesterday","I am cheerful today but was sorrow yesterday","I am happy today but was sad yesterday","I am happy today but was sorrow yesterday","I am joy today but was sad yesterday","I am joy today but was sorrow yesterday"] Example 2: Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday" Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"] Constraints: 0 <= synonyms.length <= 10 synonyms[i].length == 2 1 <= si.length, ti.length <= 10 si != ti text consists of at most 10 words. All the pairs of synonyms are unique. The words of text are separated by single spaces.
class Solution: def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]: def s(i, lst): nonlocal ret if i == n: ret.append(' '.join(lst)) return j = get(t[i]) if j != -1: k = find(j) for w in choice[k]: s(i + 1, lst + [w]) else: s(i + 1, lst + [t[i]]) def find(x): if x != up[x]: up[x] = find(up[x]) return up[x] def union(x, y): a, b = find(x), find(y) if a != b: up[a] = b choice[b] |= choice[a] def get(x): nonlocal cnt if x not in label: label[x] = cnt up.append(cnt) choice.append({x}) cnt += 1 return label[x] ret = [] t = text.split(' ') n = len(t) up = [] cnt = 0 label = collections.defaultdict(lambda: -1) choice = [] for a, b in synonyms: union(get(a), get(b)) s(0, []) return sorted(ret)
e2c0f7
35b447
You are given an integer array nums and an integer k. Find the longest subsequence of nums that meets the following requirements: The subsequence is strictly increasing and The difference between adjacent elements in the subsequence is at most k. Return the length of the longest subsequence that meets the requirements. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: nums = [4,2,1,4,3,4,5,8,15], k = 3 Output: 5 Explanation: The longest subsequence that meets the requirements is [1,3,4,5,8]. The subsequence has a length of 5, so we return 5. Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3. Example 2: Input: nums = [7,4,5,1,8,12,4,7], k = 5 Output: 4 Explanation: The longest subsequence that meets the requirements is [4,5,8,12]. The subsequence has a length of 4, so we return 4. Example 3: Input: nums = [1,5], k = 1 Output: 1 Explanation: The longest subsequence that meets the requirements is [1]. The subsequence has a length of 1, so we return 1.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 100000
class Solution(object): def lengthOfLIS(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ n = max(nums) t = [0] * (n * 4) def u(o, c): if t[n + o] < c: t[n + o], p = c, n + o while p > 0: t[p / 2], p = max(t[p - p % 2], t[p - p % 2 + 1]), p / 2 def f(m, o): l, r, s = m + n, o + n, 0 while l <= r: s, l, r = max(s, t[l] if l % 2 else s, s if r % 2 else t[r]), (l + l % 2) / 2, (r + r % 2 - 1) / 2 return s for o in nums: c = f(max(1, o - k), max(0, o - 1)) u(o, c + 1) return f(0, n)
2419a0
35b447
You are given an integer array nums and an integer k. Find the longest subsequence of nums that meets the following requirements: The subsequence is strictly increasing and The difference between adjacent elements in the subsequence is at most k. Return the length of the longest subsequence that meets the requirements. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: nums = [4,2,1,4,3,4,5,8,15], k = 3 Output: 5 Explanation: The longest subsequence that meets the requirements is [1,3,4,5,8]. The subsequence has a length of 5, so we return 5. Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3. Example 2: Input: nums = [7,4,5,1,8,12,4,7], k = 5 Output: 4 Explanation: The longest subsequence that meets the requirements is [4,5,8,12]. The subsequence has a length of 4, so we return 4. Example 3: Input: nums = [1,5], k = 1 Output: 1 Explanation: The longest subsequence that meets the requirements is [1]. The subsequence has a length of 1, so we return 1.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 100000
class Solution: def lengthOfLIS(self, nums: List[int], k: int) -> int: tmp = SegmentTree([0] * (10 ** 5 + 1)) for x in nums: note = tmp.query(max(0, x-k), x-1) tmp.update(x, note + 1) return tmp.query(0, 10 ** 5) class SegmentTree: def __init__(self, data, merge=max): ''' data:传入的数组 merge:处理的业务逻辑,例如求和/最大值/最小值,lambda表达式 ''' self.data = data self.n = len(data) # 申请4倍data长度的空间来存线段树节点 self.tree = [None] * (4 * self.n) # 索引i的左孩子索引为2i+1,右孩子为2i+2 self._merge = merge if self.n: self._build(0, 0, self.n-1) def query(self, ql, qr): ''' 返回区间[ql,..,qr]的值 ''' return self._query(0, 0, self.n-1, ql, qr) def update(self, index, value): # 将data数组index位置的值更新为value,然后递归更新线段树中被影响的各节点的值 self.data[index] = value self._update(0, 0, self.n-1, index) def _build(self, tree_index, l, r): ''' 递归创建线段树 tree_index : 线段树节点在数组中位置 l, r : 该节点表示的区间的左,右边界 ''' if l == r: self.tree[tree_index] = self.data[l] return mid = (l+r) // 2 # 区间中点,对应左孩子区间结束,右孩子区间开头 left, right = 2 * tree_index + 1, 2 * tree_index + 2 # tree_index的左右子树索引 self._build(left, l, mid) self._build(right, mid+1, r) self.tree[tree_index] = self._merge(self.tree[left], self.tree[right]) def _query(self, tree_index, l, r, ql, qr): ''' 递归查询区间[ql,..,qr]的值 tree_index : 某个根节点的索引 l, r : 该节点表示的区间的左右边界 ql, qr: 待查询区间的左右边界 ''' if l == ql and r == qr: return self.tree[tree_index] mid = (l+r) // 2 # 区间中点,对应左孩子区间结束,右孩子区间开头 left, right = tree_index * 2 + 1, tree_index * 2 + 2 if qr <= mid: # 查询区间全在左子树 return self._query(left, l, mid, ql, qr) elif ql > mid: # 查询区间全在右子树 return self._query(right, mid+1, r, ql, qr) # 查询区间一部分在左子树一部分在右子树 return self._merge(self._query(left, l, mid, ql, mid), self._query(right, mid+1, r, mid+1, qr)) def _update(self, tree_index, l, r, index): ''' tree_index:某个根节点索引 l, r : 此根节点代表区间的左右边界 index : 更新的值的索引 ''' if l == r == index: self.tree[tree_index] = self.data[index] return mid = (l+r)//2 left, right = 2 * tree_index + 1, 2 * tree_index + 2 if index > mid: # 要更新的区间在右子树 self._update(right, mid+1, r, index) else: # 要更新的区间在左子树index<=mid self._update(left, l, mid, index) # 里面的小区间变化了,包裹的大区间也要更新 self.tree[tree_index] = self._merge(self.tree[left], self.tree[right])
d6deeb
61a8b5
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node.   Example 1: Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75. Example 2: Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30 Output: 25 Explanation: One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30. The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25. Example 3: Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50 Output: 7 Explanation: One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50. The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.   Constraints: n == values.length 1 <= n <= 1000 0 <= values[i] <= 10^8 0 <= edges.length <= 2000 edges[j].length == 3 0 <= uj < vj <= n - 1 10 <= timej, maxTime <= 100 All the pairs [uj, vj] are unique. There are at most four edges connected to each node. The graph may not be connected.
class Solution(object): def maximalPathQuality(self, values, edges, maxTime): """ :type values: List[int] :type edges: List[List[int]] :type maxTime: int :rtype: int """ n = len(values) adj = [[] for _ in xrange(n)] for u, v, w in edges: adj[u].append((v, w)) adj[v].append((u, w)) vis = [False] * n best = [0] vis[0] = True def _dfs(u, t, score): if u == 0: best[0] = max(best[0], score) for v, w in adj[u]: if w > t: continue if not vis[v]: vis[v] = True _dfs(v, t-w, score+values[v]) vis[v] = False if vis[v]: _dfs(v, t-w, score) _dfs(0, maxTime, values[0]) return best[0]
d7187d
61a8b5
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node.   Example 1: Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75. Example 2: Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30 Output: 25 Explanation: One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30. The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25. Example 3: Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50 Output: 7 Explanation: One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50. The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.   Constraints: n == values.length 1 <= n <= 1000 0 <= values[i] <= 10^8 0 <= edges.length <= 2000 edges[j].length == 3 0 <= uj < vj <= n - 1 10 <= timej, maxTime <= 100 All the pairs [uj, vj] are unique. There are at most four edges connected to each node. The graph may not be connected.
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: N = len(values) graph = [[] for i in range(N)] for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w)) ans = 0 def dfs(path, seen, cost, score): nonlocal ans if path[0] == path[-1]: ans = max(ans, score) for v, w in graph[path[-1]]: if cost + w <= maxTime: path.append(v) if v in seen: dfs(path, seen, cost + w, score) else: seen.add(v) dfs(path, seen, cost + w, score + values[v]) seen.remove(v) path.pop() u = 0 dfs([u], {u}, 0, values[u]) return ans
d8cb9f
1439da
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Test cases are designed so that the answer will fit in a 32-bit integer.   Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16   Constraints: n == nums.length 1 <= nums.length <= 100000 -10^9 <= nums[i] <= 10^9
class Solution(object): def minMoves2(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 nums = sorted(nums) start = nums[0] end = nums[-1] while start + 1 < end: mid = start + (end - start) / 2 res1 = self.count(mid - 1, nums) res2 = self.count(mid, nums) if res1 == res2: return res1 if res1 > res2: start = mid else: end = mid res1 = self.count(start, nums) res2 = self.count(end, nums) return min(res1, res2) def count(self, i, nums): res = 0 for num in nums: res += abs(num - i) return res
2a534e
7e4e81
Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'. In C++, there are two types of comments, line comments, and block comments. The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored. The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning. The first effective comment takes precedence over others. For example, if the string "//" occurs in a block comment, it is ignored. Similarly, if the string "/*" occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format.   Example 1: Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] Explanation: The line by line code is visualized as below: /*Test program */ int main() { // variable declaration int a, b, c; /* This is a test multiline comment for testing */ a = b + c; } The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments. The line by line output code is visualized as below: int main() { int a, b, c; a = b + c; } Example 2: Input: source = ["a/*comment", "line", "more_comment*/b"] Output: ["ab"] Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].   Constraints: 1 <= source.length <= 100 0 <= source[i].length <= 80 source[i] consists of printable ASCII characters. Every open block comment is eventually closed. There are no single-quote or double-quote in the input.
import re class Solution: def removeComments(self, source): """ :type source: List[str] :rtype: List[str] """ r1 = re.compile(r'//') r2 = re.compile(r'/\*') r3 = re.compile(r'\*/') i = 0 while i < len(source): m1 = r1.search(source[i]) m2 = r2.search(source[i]) if m1 and (not m2 or (m2 and m1.start() < m2.start())): source[i] = source[i][0:m1.start()] i += 1 continue if m2 and (not m1 or (m1 and m2.start() < m1.start())): m3 = r3.search(source[i][m2.end():]) if m3: source[i] = source[i][:m2.start()] + source[i][m2.end() + m3.end():] continue j = i+1 while True: m3 = r3.search(source[j]) if m3: break j += 1 source[i] = source[i][:m2.start()] + source[j][m3.end():] for k in range(i+1, j+1): del source[i+1] continue # no match i += 1 return [s for s in source if s]
ab2589
7e4e81
Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'. In C++, there are two types of comments, line comments, and block comments. The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored. The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning. The first effective comment takes precedence over others. For example, if the string "//" occurs in a block comment, it is ignored. Similarly, if the string "/*" occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format.   Example 1: Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] Explanation: The line by line code is visualized as below: /*Test program */ int main() { // variable declaration int a, b, c; /* This is a test multiline comment for testing */ a = b + c; } The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments. The line by line output code is visualized as below: int main() { int a, b, c; a = b + c; } Example 2: Input: source = ["a/*comment", "line", "more_comment*/b"] Output: ["ab"] Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].   Constraints: 1 <= source.length <= 100 0 <= source[i].length <= 80 source[i] consists of printable ASCII characters. Every open block comment is eventually closed. There are no single-quote or double-quote in the input.
class Solution(object): def removeComments(self, source): """ :type source: List[str] :rtype: List[str] """ source='\n'.join(source) isinblock=False hasline=False result='' i=0 n=len(source) while i<len(source): # print [result] if source[i]=='/': if i!=n-1: if source[i+1]=='/': while i<n and source[i]!='\n': i+=1 continue if source[i+1]=='*': i=i+2 while i<n-2 and source[i:i+2]!='*/': i+=1 i+=2 continue else: result+=source[i] else: result+=source[i] else: result+=source[i] i+=1 return [i for i in result.split('\n') if i!='']
50437b
e93b72
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].   Example 1: Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] Example 2: Input: firstList = [[1,3],[5,9]], secondList = [] Output: []   Constraints: 0 <= firstList.length, secondList.length <= 1000 firstList.length + secondList.length >= 1 0 <= starti < endi <= 10^9 endi < starti+1 0 <= startj < endj <= 10^9 endj < startj+1
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def intervalIntersection(self, A, B): """ :type A: List[Interval] :type B: List[Interval] :rtype: List[Interval] """ idxA=idxB=0 ans=[] while idxA<len(A) and idxB<len(B): if B[idxB].end<=A[idxA].end: if B[idxB].end>=A[idxA].start: ans.append(Interval(max(A[idxA].start,B[idxB].start),B[idxB].end)) idxB+=1 else: if B[idxB].start<=A[idxA].end: ans.append(Interval(max(A[idxA].start,B[idxB].start),A[idxA].end)) idxA+=1 return ans
e8cc15
e93b72
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].   Example 1: Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] Example 2: Input: firstList = [[1,3],[5,9]], secondList = [] Output: []   Constraints: 0 <= firstList.length, secondList.length <= 1000 firstList.length + secondList.length >= 1 0 <= starti < endi <= 10^9 endi < starti+1 0 <= startj < endj <= 10^9 endj < startj+1
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def intervalIntersection(self, A: 'List[Interval]', B: 'List[Interval]') -> 'List[Interval]': i = j = 0 output = [] while i < len(A) and j < len(B): a = A[i] b = B[j] if a.end < b.start: i += 1 elif b.end < a.start: j += 1 elif a.end < b.end: output.append(Interval(max(a.start, b.start), a.end)) i += 1 else: output.append(Interval(max(a.start, b.start), b.end)) j += 1 return output
efc6cf
598030
You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get.   Example 1: Input: nums = [1,-1,-2,4,-7,3], k = 2 Output: 7 Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. Example 2: Input: nums = [10,-5,-2,4,0,3], k = 3 Output: 17 Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. Example 3: Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2 Output: 0   Constraints: 1 <= nums.length, k <= 100000 -10000 <= nums[i] <= 10000
class MMQueue: def __init__(self): self.maq = collections.deque() self.len = 0 def enqueue(self, v): self.len += 1 c = 1 while self.maq and self.maq[-1][0] < v: c += self.maq.pop()[1] self.maq.append([v, c]) def dequeue(self): self.len -= 1 self.maq[0][1] -= 1 if self.maq[0][1] <= 0: self.maq.popleft() def max(self): return self.maq[0][0] if self.maq else 0 def __len__(self): return self.len class Solution: def maxResult(self, A: List[int], K: int) -> int: N = len(A) mq = MMQueue() mq.enqueue(A[0]) ans = A[0] for i in range(1, N): if len(mq) > K: mq.dequeue() ans = A[i] + mq.max() mq.enqueue(ans) return ans
7b060b
598030
You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get.   Example 1: Input: nums = [1,-1,-2,4,-7,3], k = 2 Output: 7 Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. Example 2: Input: nums = [10,-5,-2,4,0,3], k = 3 Output: 17 Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. Example 3: Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2 Output: 0   Constraints: 1 <= nums.length, k <= 100000 -10000 <= nums[i] <= 10000
from collections import deque class Solution(object): def maxResult(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # f[i] = max(f[i-k:i]) + num[i] a = nums n = len(a) f = [0]*n f[0] = a[0] s = deque() s.append((0, a[0])) for i in xrange(1, n): if s[0][0] == i-k-1: s.popleft() f[i] = s[0][1] + a[i] while s and f[i] >= s[-1][1]: s.pop() s.append((i, f[i])) return f[-1]
161974
8a3ca7
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.   Example 1: Input: s = "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". Example 2: Input: s = "aba" Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". Example 3: Input: s = "aaa" Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".   Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters.
class Solution(object): def distinctSubseqII(self, S): """ :type S: str :rtype: int """ from collections import defaultdict mod = 10 ** 9 + 7 seen = defaultdict(lambda : -1) subseq = [0 for _ in S] + [0] subseq[0] = 1 for i, c in enumerate(S): last = seen[c] if last == -1: subseq[i + 1] = subseq[i] * 2 % mod else: subseq[i + 1] = (subseq[i] * 2 - subseq[last - 1] + mod) % mod seen[c] = i + 1 return (subseq[-1] + mod - 1) % mod
25c7e1
8a3ca7
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.   Example 1: Input: s = "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". Example 2: Input: s = "aba" Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". Example 3: Input: s = "aaa" Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".   Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters.
class Solution: def distinctSubseqII(self, S): """ :type S: str :rtype: int """ N = len(S) mod = 10**9 + 7 dp = [1] pred = {} for i, c in enumerate(S, start=1): dp.append(2 * dp[i-1] - (dp[pred[c]] if c in pred else 0)) # print(pred, dp) dp[-1] %= mod pred[c] = i-1 return dp[-1] -1
d48e8d
a530bb
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward. On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward. Given the base k and the number n, return the sum of the n smallest k-mirror numbers.   Example 1: Input: k = 2, n = 5 Output: 25 Explanation: The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows: base-10 base-2 1 1 3 11 5 101 7 111 9 1001 Their sum = 1 + 3 + 5 + 7 + 9 = 25. Example 2: Input: k = 3, n = 7 Output: 499 Explanation: The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows: base-10 base-3 1 1 2 2 4 11 8 22 121 11111 151 12121 212 21212 Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. Example 3: Input: k = 7, n = 17 Output: 20379000 Explanation: The 17 smallest 7-mirror numbers are: 1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596   Constraints: 2 <= k <= 9 1 <= n <= 30
class Solution: def kMirror(self, b: int, n: int) -> int: res = 0 cnt = 0 def get_num(): for l in range(30): for v in range(10**l,10**(l+1)): s = str(v) + str(v)[::-1][1:] yield int(s) for v in range(10**l,10**(l+1)): s = str(v) + str(v)[::-1] yield int(s) for num in get_num(): new_num = [] k = 0 curr = num while curr: new_num += [curr%b] curr //= b if new_num == new_num[::-1]: res += 1 cnt += num if res == n: return cnt
940110
a530bb
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward. On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward. Given the base k and the number n, return the sum of the n smallest k-mirror numbers.   Example 1: Input: k = 2, n = 5 Output: 25 Explanation: The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows: base-10 base-2 1 1 3 11 5 101 7 111 9 1001 Their sum = 1 + 3 + 5 + 7 + 9 = 25. Example 2: Input: k = 3, n = 7 Output: 499 Explanation: The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows: base-10 base-3 1 1 2 2 4 11 8 22 121 11111 151 12121 212 21212 Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. Example 3: Input: k = 7, n = 17 Output: 20379000 Explanation: The 17 smallest 7-mirror numbers are: 1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596   Constraints: 2 <= k <= 9 1 <= n <= 30
class Solution(object): def kMirror(self, k, n): """ :type k: int :type n: int :rtype: int """ bs = [0]*128 def fit(v): i=0 while v: bs[i]=v%k v/=k i+=1 j=0 i-=1 while j<i: if bs[j]!=bs[i]: return False j+=1 i-=1 return True ds = [0]*128 r =[] def dfs(v, b1, b2): if len(r) >= n: return if b1>b2: if fit(v): r.append(v) return if b1==b2: if b1==1: for i in range(1, 10): dfs(v+b1*i, b1*10, b2/10) else: for i in range(0, 10): dfs(v+b1*i, b1*10, b2/10) else: if b1==1: for i in range(1, 10): dfs(v+b1*i+b2*i, b1*10, b2/10) else: for i in range(0, 10): dfs(v+b1*i+b2*i, b1*10, b2/10) i=1 while True: if len(r)>=n: break dfs(0, 1, i) i*=10 # print r return sum(r[:n])
01616a
91bfee
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j) in the following way: During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. It may be the case that for some index i, there are no legal jumps. A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices.   Example 1: Input: arr = [10,13,12,14,15] Output: 2 Explanation: From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. Example 2: Input: arr = [2,3,1,1,4] Output: 3 Explanation: From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. Example 3: Input: arr = [5,1,3,4,2] Output: 3 Explanation: We can reach the end from starting indices 1, 2, and 4.   Constraints: 1 <= arr.length <= 2 * 10000 0 <= arr[i] < 100000
import bisect class Solution: def oddEvenJumps(self, A): """ :type A: List[int] :rtype: int """ a = A n = len(a) p = [None for _ in range(n)] v = [] idx = {} for i in range(n)[::-1]: if i != n - 1: if a[i] in idx: p[i] = idx[a[i]] elif a[i] > v[-1]: p[i] = None else: tmp = bisect.bisect(v, a[i]) p[i] = idx[v[tmp]] if a[i] not in idx: bisect.insort(v, a[i]) idx[a[i]] = i q = [None for _ in range(n)] v = [] idx = {} for i in range(n)[::-1]: if i != n - 1: if a[i] in idx: q[i] = idx[a[i]] elif a[i] < v[0]: q[i] = None else: tmp = bisect.bisect(v, a[i]) q[i] = idx[v[tmp - 1]] if a[i] not in idx: bisect.insort(v, a[i]) idx[a[i]] = i # print(p) # print(q) pvalid = [None for _ in range(n)] qvalid = [None for _ in range(n)] pvalid[-1] = qvalid[-1] = True ans = 1 for i in range(n - 1)[::-1]: pvalid[i] = False if p[i] is None else qvalid[p[i]] qvalid[i] = False if q[i] is None else pvalid[q[i]] # print(i, pvalid[i], qvalid[i]) ans += pvalid[i] return ans
f989a2
91bfee
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j) in the following way: During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. It may be the case that for some index i, there are no legal jumps. A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices.   Example 1: Input: arr = [10,13,12,14,15] Output: 2 Explanation: From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. Example 2: Input: arr = [2,3,1,1,4] Output: 3 Explanation: From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. Example 3: Input: arr = [5,1,3,4,2] Output: 3 Explanation: We can reach the end from starting indices 1, 2, and 4.   Constraints: 1 <= arr.length <= 2 * 10000 0 <= arr[i] < 100000
class Solution(object): def oddEvenJumps(self, A): """ :type A: List[int] :rtype: int """ n = len(A) odd = [0] * n even = [0] * n sa1 = sorted([[a, i] for i, a in enumerate(A)]) sa2 = sorted([[a, i] for i, a in enumerate(A)], key = lambda x: (x[0], -x[1])) for i in range(n): j = i+1 while j < n and sa1[i][1] > sa1[j][1]: j += 1 if j < n: odd[sa1[i][1]] = sa1[j][1] else: odd[sa1[i][1]] = -1 for i in range(n): j = i-1 while j >= 0 and sa2[i][1] > sa2[j][1]: j -= 1 if j >= 0: even[sa2[i][1]] = sa2[j][1] else: even[sa2[i][1]] = -1 dp = [[False, False] for _ in range(n)] dp[-1] = [True, True] res = 1 for i in range(n-2, -1, -1): if odd[i] != -1 and dp[odd[i]][1]: dp[i][0] = True res += 1 if even[i] != -1 and dp[even[i]][0]: dp[i][1] = True return res
bc9cfa
82e874
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array.   Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4]. Example 2: Input: arr = [5,4,3,2,1] Output: 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]. Example 3: Input: arr = [1,2,3] Output: 0 Explanation: The array is already non-decreasing. We do not need to remove any elements.   Constraints: 1 <= arr.length <= 100000 0 <= arr[i] <= 10^9
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: l = 0 while l<len(arr)-1 and arr[l]<=arr[l+1]: l += 1 if l == len(arr)-1: return 0 r = len(arr)-1 while arr[r]>=arr[r-1]: r -= 1 i,j = l,len(arr)-1 best=0 locs=[-1,-1] while i>=0: while j>=r and arr[i]<=arr[j]: j-=1 if i+len(arr)-j>=best: best=i+len(arr)-j locs=[i+1,j+1] i-=1 if len(arr)-r>best: return len(arr)-len(arr[r:]) return len(arr)-(len(arr[:locs[0]] + arr[locs[1]:]))
a38ace
82e874
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array.   Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4]. Example 2: Input: arr = [5,4,3,2,1] Output: 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]. Example 3: Input: arr = [1,2,3] Output: 0 Explanation: The array is already non-decreasing. We do not need to remove any elements.   Constraints: 1 <= arr.length <= 100000 0 <= arr[i] <= 10^9
class Solution(object): def findLengthOfShortestSubarray(self, A): N = len(A) if N == 1: return 0 j = N-1 while j>0 and A[j] >= A[j-1]: j -= 1 ans = j i = 0 while True: while j < N and A[i] > A[j]: j += 1 if i < j: ans = min(ans, j - 1 - i) else: ans = 0 if i + 1 < N and A[i] <= A[i+1]: i += 1 else: break return ans """ i = 0 j = N - 1 ans = N - 1 found = True while i < j and found: found = False if i < j and A[i] <= A[j]: cand = j-i-1 if cand < ans: ans=cand if A[i] <= A[i + 1]: i += 1 found = True if i< j and A[i] <= A[j]: cand = j-i-1 if cand < ans: ans=cand if A[j] >= A[j - 1]: j -= 1 found = True if i < j and A[i] <= A[j]: cand = j-i-1 if cand < ans: ans=cand ans = min(ans, j, N - 1 - i) return ans """
247bb0
7b5629
You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR. In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1. The bitwise OR of an array is the bitwise OR of all the numbers in it. Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,0,2,1,3] Output: [3,3,2,2,1] Explanation: The maximum possible bitwise OR starting at any index is 3. - Starting at index 0, the shortest subarray that yields it is [1,0,2]. - Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1]. - Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1]. - Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3]. - Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3]. Therefore, we return [3,3,2,2,1]. Example 2: Input: nums = [1,2] Output: [2,1] Explanation: Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2. Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1. Therefore, we return [2,1].   Constraints: n == nums.length 1 <= n <= 100000 0 <= nums[i] <= 10^9
class Solution: def smallestSubarrays(self, a: List[int]) -> List[int]: b = [0 for i in range(32)] n = len(a) z = [0 for i in range(n)] for i in range(n)[::-1]: for j in range(32): if a[i] >> j & 1: b[j] = i z[i] = max(max(b) - i + 1, 1) return z
417bed
7b5629
You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR. In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1. The bitwise OR of an array is the bitwise OR of all the numbers in it. Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,0,2,1,3] Output: [3,3,2,2,1] Explanation: The maximum possible bitwise OR starting at any index is 3. - Starting at index 0, the shortest subarray that yields it is [1,0,2]. - Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1]. - Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1]. - Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3]. - Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3]. Therefore, we return [3,3,2,2,1]. Example 2: Input: nums = [1,2] Output: [2,1] Explanation: Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2. Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1. Therefore, we return [2,1].   Constraints: n == nums.length 1 <= n <= 100000 0 <= nums[i] <= 10^9
class Solution(object): def smallestSubarrays(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) maximum = [0]*(n+1) for i in range(n-1,-1,-1): maximum[i] = maximum[i+1] | nums[i] accu1 = [[-1] for _ in range(31)] for i in range(n): for d in range(31): if (1<<d) & nums[i] > 0: accu1[d].append(i) print accu1 cul = [0]*31 ans = [1]*n for i in range(n): for d in range(31): if (1<<d) & maximum[i] > 0: ans[i] = max(ans[i], accu1[d][cul[d]+1] - i + 1) if (1<<d) & nums[i] > 0: cul[d] += 1 # print cul return ans
b91a0c
4fc251
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.   Example 1: Input: machines = [1,0,5] Output: 3 Explanation: 1st move: 1 0 <-- 5 => 1 1 4 2nd move: 1 <-- 1 <-- 4 => 2 1 3 3rd move: 2 1 <-- 3 => 2 2 2 Example 2: Input: machines = [0,3,0] Output: 2 Explanation: 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1 Example 3: Input: machines = [0,2,0] Output: -1 Explanation: It's impossible to make all three washing machines have the same number of dresses.   Constraints: n == machines.length 1 <= n <= 10000 0 <= machines[i] <= 100000
class Solution(object): def findMinMoves(self, machines): if not machines: return 0 n = len(machines) if sum(machines) % n != 0: return -1 ave = sum(machines) / n dp0 = [0 for i in xrange(n)] dp1 = [0 for i in xrange(n)] cnt = 0 for i, num in enumerate(machines[:-1]): num += cnt cnt = 0 if num > ave: dp1[i] += abs(num - ave) else: dp0[i] += abs(num - ave) cnt = num - ave ans = 0 for i in xrange(n): a = 0 if i == 0 else dp0[i - 1] b = dp1[i] ans = max(ans, a + b) return ans S = Solution() assert(S.findMinMoves([1,0,5]) == 3) assert(S.findMinMoves([0,3,0]) == 2) assert(S.findMinMoves([0,2,0]) == -1)
a7e892
61081d
You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions. Return the minimum cost to change the final value of the expression. For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0. The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Turn a '1' into a '0'. Turn a '0' into a '1'. Turn a '&' into a '|'. Turn a '|' into a '&'. Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.   Example 1: Input: expression = "1&(0|1)" Output: 1 Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation. The new expression evaluates to 0. Example 2: Input: expression = "(0&0)&(0&0&0)" Output: 3 Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations. The new expression evaluates to 1. Example 3: Input: expression = "(0|(1|0&1))" Output: 1 Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation. The new expression evaluates to 0.   Constraints: 1 <= expression.length <= 100000 expression only contains '1','0','&','|','(', and ')' All parentheses are properly matched. There will be no empty parentheses (i.e: "()" is not a substring of expression).
class Solution(object): def minOperationsToFlip(self, expression): """ :type expression: str :rtype: int """ e = expression n = len(expression) class Node(object): def __init__(self, t, v, left=None, right=None): self.t=t; self.v=v; self.l=left self.r=right self.vv=None self.dp = None def eval(self): if self.vv is not None: return self.vv if self.t==0: self.vv = self.v else: v1=self.l.eval() v2=self.r.eval() if self.v=='&': self.vv = v1&v2 else: self.vv = v1|v2 return self.vv def dfs(self): if self.dp is not None: return self.dp r = -1 if self.t==0: r = 1 else: v1=self.l.eval() v2=self.r.eval() if self.v=='&': if self.vv==1: t = self.l.dfs() if r<0 or r>t: r=t t = self.r.dfs() if r<0 or r>t: r=t else: if v1==1: t = self.r.dfs() if r<0 or r>t: r=t elif v2==1: t = self.l.dfs() if r<0 or r>t: r=t else: t = self.r.dfs()+self.l.dfs() if r<0 or r>t: r=t # change to | vv = v1|v2 if vv==self.vv: if self.vv==0: t = self.l.dfs()+1 if r<0 or r>t: r=t t = self.r.dfs()+1 if r<0 or r>t: r=t else: if v1==0: t = self.l.dfs()+1 if r<0 or r>t: r=t elif v2==0: t = self.r.dfs()+1 if r<0 or r>t: r=t else: t = self.r.dfs()+self.l.dfs()+1 if r<0 or r>t: r=t else: r=1 else: if self.vv==0: t = self.l.dfs() if r<0 or r>t: r=t t = self.r.dfs() if r<0 or r>t: r=t else: if v1==0: t = self.l.dfs() if r<0 or r>t: r=t elif v2==0: t = self.r.dfs() if r<0 or r>t: r=t else: t = self.r.dfs()+self.l.dfs() if r<0 or r>t: r=t vv = v1&v2 if vv==self.vv: if self.vv==1: t = self.l.dfs()+1 if r<0 or r>t: r=t t = self.r.dfs()+1 if r<0 or r>t: r=t else: if v1==1: t = self.r.dfs()+1 if r<0 or r>t: r=t elif v2==1: t = self.l.dfs()+1 if r<0 or r>t: r=t else: t = self.r.dfs()+self.l.dfs()+1 if r<0 or r>t: r=t else: r=1 self.dp = r return r def build(i): n1 = None while True: cn = None if i>=n: break if e[i]=='1': cn = Node(0, 1) i+=1 elif e[i]=='0': cn = Node(0, 0) i+=1 elif e[i]=='(': cn, i = build(i+1) i+=1 elif e[i]==')': break elif e[i]=='&' or e[i]=='|': op = e[i] i+=1 if cn: if n1==None: n1=cn else: n1 = Node(1, op, n1, cn) return n1, i n, _ = build(0) n.eval() return n.dfs()
f0084b
61081d
You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions. Return the minimum cost to change the final value of the expression. For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0. The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Turn a '1' into a '0'. Turn a '0' into a '1'. Turn a '&' into a '|'. Turn a '|' into a '&'. Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.   Example 1: Input: expression = "1&(0|1)" Output: 1 Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation. The new expression evaluates to 0. Example 2: Input: expression = "(0&0)&(0&0&0)" Output: 3 Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations. The new expression evaluates to 1. Example 3: Input: expression = "(0|(1|0&1))" Output: 1 Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation. The new expression evaluates to 0.   Constraints: 1 <= expression.length <= 100000 expression only contains '1','0','&','|','(', and ')' All parentheses are properly matched. There will be no empty parentheses (i.e: "()" is not a substring of expression).
class Tree: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right def dp(self): if self.val == 0 or self.val == 1: return self.val, 1 u, uc = self.left.dp() v, vc = self.right.dp() if self.val == '&': val = u & v else: # | val = u | v if u != v: return val, 1 if (self.val == '&' and u == 1) or (self.val == '|' and u == 0): res = min(uc, vc) else: res = min(uc, vc) + 1 return val, res class Solution: def minOperationsToFlip(self, expression: str) -> int: def maintain(): nonlocal tree_stack, op_stack q = tree_stack.pop() p = tree_stack.pop() ch = op_stack.pop() tree_stack.append(Tree(ch, p, q)) tree_stack = [] # type: Tree op_stack = [] # type: str for ch in expression: if ch == '0' or ch == '1': tree_stack.append(Tree(int(ch))) while len(tree_stack) >= 2 and len(op_stack) != 0 and op_stack[-1] != '(': maintain() elif ch == '&' or ch == '|': op_stack.append(ch) elif ch == '(': op_stack.append(ch) else: # ch == ')' while op_stack[-1] != '(': maintain() op_stack.pop() while len(tree_stack) >= 2 and len(op_stack) != 0 and op_stack[-1] != '(': maintain() tree = tree_stack[0] # print(tree.dp()) _, ans = tree.dp() return ans
5cc37b
154c1f
You are given an array nums consisting of positive integers. Starting with score = 0, apply the following algorithm: Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index. Add the value of the chosen integer to score. Mark the chosen element and its two adjacent elements if they exist. Repeat until all the array elements are marked. Return the score you get after applying the above algorithm.   Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2]. - 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2]. - 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2]. Our score is 1 + 2 + 4 = 7. Example 2: Input: nums = [2,3,5,1,3,2] Output: 5 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2]. - 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2]. - 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2]. Our score is 1 + 2 + 2 = 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 1000000
class Solution: def findScore(self, nums: List[int]) -> int: fuck = [[nums[i], i] for i in range(len(nums))] fuck.sort() fucked = [False] * len(nums) ans = 0 for [val, idx] in fuck: if fucked[idx]: continue fucked[idx] = True if idx - 1 >= 0: fucked[idx - 1] = True if idx + 1 < len(nums): fucked[idx + 1] = True ans += val print(fuck) print(fucked) return ans
be2109
154c1f
You are given an array nums consisting of positive integers. Starting with score = 0, apply the following algorithm: Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index. Add the value of the chosen integer to score. Mark the chosen element and its two adjacent elements if they exist. Repeat until all the array elements are marked. Return the score you get after applying the above algorithm.   Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2]. - 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2]. - 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2]. Our score is 1 + 2 + 4 = 7. Example 2: Input: nums = [2,3,5,1,3,2] Output: 5 Explanation: We mark the elements as follows: - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2]. - 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2]. - 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2]. Our score is 1 + 2 + 2 = 5.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 1000000
class Solution(object): def findScore(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) arr = [] marked = [0] * (n+2) for i in range(n): arr.append((nums[i], i+1)) arr.sort() ans = 0 for n, pos in arr: if marked[pos]: continue ans += n marked[pos] = 1 marked[pos+1] = 1 marked[pos-1] = 1 return ans
4c0804
92bc25
You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree.   Example 1: Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3 Explanation: Longest ZigZag path in blue nodes (right -> left -> right). Example 2: Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4 Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). Example 3: Input: root = [1] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 5 * 10000]. 1 <= Node.val <= 100
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def longestZigZag(self, root: TreeNode) -> int: ans = 0 if root == None: return 0 def dfs(cur): nonlocal ans cur.lll = 0 cur.rrr = 0 if cur.left != None: dfs(cur.left) cur.lll = max(cur.lll, cur.left.rrr + 1) if cur.right != None: dfs(cur.right) cur.rrr = max(cur.rrr, cur.right.lll + 1) ans = max(ans, cur.lll) ans = max(ans, cur.rrr) dfs(root) return ans
7a2022
92bc25
You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree.   Example 1: Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3 Explanation: Longest ZigZag path in blue nodes (right -> left -> right). Example 2: Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4 Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). Example 3: Input: root = [1] Output: 0   Constraints: The number of nodes in the tree is in the range [1, 5 * 10000]. 1 <= Node.val <= 100
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def longestZigZag(self, root): """ :type root: TreeNode :rtype: int """ def dfs(node): if not node: return -1, -1 ll, lr = dfs(node.left) rl, rr = dfs(node.right) l = lr + 1 r = rl + 1 self.ans = max(self.ans, l, r) return l, r self.ans = 0 dfs(root) return self.ans
5b4090
9bc03d
On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.   Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Explanation: One way to remove 5 stones is as follows: 1. Remove stone [2,2] because it shares the same row as [2,1]. 2. Remove stone [2,1] because it shares the same column as [0,1]. 3. Remove stone [1,2] because it shares the same row as [1,0]. 4. Remove stone [1,0] because it shares the same column as [0,0]. 5. Remove stone [0,1] because it shares the same row as [0,0]. Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane. Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Explanation: One way to make 3 moves is as follows: 1. Remove stone [2,2] because it shares the same row as [2,0]. 2. Remove stone [2,0] because it shares the same column as [0,0]. 3. Remove stone [0,2] because it shares the same row as [0,0]. Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane. Example 3: Input: stones = [[0,0]] Output: 0 Explanation: [0,0] is the only stone on the plane, so you cannot remove it.   Constraints: 1 <= stones.length <= 1000 0 <= xi, yi <= 10000 No two stones are at the same coordinate point.
class Solution(object): def removeStones(self, stones): """ :type stones: List[List[int]] :rtype: int """ self.Father={} stone=sorted(stones) def find( item): while(item !=self.Father[item]): self.Father[item]=self.Father[self.Father[item]] item=self.Father[item] return item def union(a,b): ta,tb=sorted([a,b]) Fa=find(ta) Fb=find(tb) self.Father[Fb]=Fa from collections import defaultdict Map_X=defaultdict(list) Map_Y=defaultdict(list) for x,y in stones: Map_X[x].append(y) Map_Y[y].append(x) self.Father[(x,y)]=(x,y) for x,y in stones: for ty in Map_X[x]: union((x,y),(x,ty)) for tx in Map_Y[y]: union((x,y),(tx,y)) Temp_fathers=[find((x,y)) for x,y in stones] return len(set(Temp_fathers))
fcb88a
9bc03d
On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.   Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Explanation: One way to remove 5 stones is as follows: 1. Remove stone [2,2] because it shares the same row as [2,1]. 2. Remove stone [2,1] because it shares the same column as [0,1]. 3. Remove stone [1,2] because it shares the same row as [1,0]. 4. Remove stone [1,0] because it shares the same column as [0,0]. 5. Remove stone [0,1] because it shares the same row as [0,0]. Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane. Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Explanation: One way to make 3 moves is as follows: 1. Remove stone [2,2] because it shares the same row as [2,0]. 2. Remove stone [2,0] because it shares the same column as [0,0]. 3. Remove stone [0,2] because it shares the same row as [0,0]. Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane. Example 3: Input: stones = [[0,0]] Output: 0 Explanation: [0,0] is the only stone on the plane, so you cannot remove it.   Constraints: 1 <= stones.length <= 1000 0 <= xi, yi <= 10000 No two stones are at the same coordinate point.
class Solution: def removeStones(self, stones): """ :type stones: List[List[int]] :rtype: int """ d,dd,i={},{},0 for x,y in stones: a,b=d.get((x,-1),-1),d.get((-1,y),-1) if a==-1: if b==-1: d[(x,-1)]=i d[(-1,y)]=i dd[i]=set([(x,-1),(-1,y)]) i+=1 else: d[(x,-1)]=b d[(-1,y)]=b dd[b].add((x,-1)) dd[b].add((-1,y)) else: if b==-1 or a==b: d[(x,-1)]=a d[(-1,y)]=a dd[a].add((x,-1)) dd[a].add((-1,y)) else: for xx,yy in dd[b]: d[(xx,yy)]=a dd[a]|=dd[b] del dd[b] return len(dd)
34247b
f35bdf
You are given a 0-indexed integer array nums and an integer value. In one operation, you can add or subtract value from any element of nums. For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3]. The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it. For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2. Return the maximum MEX of nums after applying the mentioned operation any number of times.   Example 1: Input: nums = [1,-10,7,13,6,8], value = 5 Output: 4 Explanation: One can achieve this result by applying the following operations: - Add value to nums[1] twice to make nums = [1,0,7,13,6,8] - Subtract value from nums[2] once to make nums = [1,0,2,13,6,8] - Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8] The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve. Example 2: Input: nums = [1,-10,7,13,6,8], value = 7 Output: 2 Explanation: One can achieve this result by applying the following operation: - subtract value from nums[2] once to make nums = [1,-10,0,13,6,8] The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.   Constraints: 1 <= nums.length, value <= 100000 -10^9 <= nums[i] <= 10^9
class Solution(object): def findSmallestInteger(self, nums, value): """ :type nums: List[int] :type value: int :rtype: int """ m, v, f = defaultdict(int), float('inf'), float('inf') for x in nums: m[abs(((abs(x) / value + (1 if abs(x) % value else 0)) * value + x if x < 0 else x) % value)] += 1 for i in range(value): f, v = min(m[i], f), i if m[i] < f else v return v + value * f
cc0db3
f35bdf
You are given a 0-indexed integer array nums and an integer value. In one operation, you can add or subtract value from any element of nums. For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3]. The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it. For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2. Return the maximum MEX of nums after applying the mentioned operation any number of times.   Example 1: Input: nums = [1,-10,7,13,6,8], value = 5 Output: 4 Explanation: One can achieve this result by applying the following operations: - Add value to nums[1] twice to make nums = [1,0,7,13,6,8] - Subtract value from nums[2] once to make nums = [1,0,2,13,6,8] - Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8] The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve. Example 2: Input: nums = [1,-10,7,13,6,8], value = 7 Output: 2 Explanation: One can achieve this result by applying the following operation: - subtract value from nums[2] once to make nums = [1,-10,0,13,6,8] The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.   Constraints: 1 <= nums.length, value <= 100000 -10^9 <= nums[i] <= 10^9
class Solution: def findSmallestInteger(self, nums: List[int], value: int) -> int: counts = [0 for i in range(value)] for x in nums: counts[x % value]+=1 if counts[0] == 0: return 0 print(counts) def check(counts, x): x1 = x % value x2 = x//value for i in range(value): if i < x1 and counts[i] < x2+1: return False if i >= x1 and counts[i] < x2: return False return True s = 0 e = len(nums)+2 while s+1 < e: m = (s+e)//2 if check(counts, m): s, e = m, e else: s, e = s, m return s
cdc98a
44d16d
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment.   Example 1: Input: jobs = [3,2,3], k = 3 Output: 3 Explanation: By assigning each person one job, the maximum time is 3. Example 2: Input: jobs = [1,2,4,7,8], k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11.   Constraints: 1 <= k <= jobs.length <= 12 1 <= jobs[i] <= 10^7
class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: best = [float('inf')] n = len(jobs) @lru_cache(None) def f(idx, t): if idx == n: best[0] = min(best[0], t[0]) return if len(t) and t[0] >= best[0]: return l = list(t) v = jobs[idx] for i in range(len(l)): x = l[:] x[i] += v x.sort(reverse=True) f(idx+1, tuple(x)) if len(t) < k: x = l + [v] x.sort(reverse=True) f(idx+1, tuple(x)) f(0, tuple([])) return best[0]
160595
44d16d
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment.   Example 1: Input: jobs = [3,2,3], k = 3 Output: 3 Explanation: By assigning each person one job, the maximum time is 3. Example 2: Input: jobs = [1,2,4,7,8], k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11.   Constraints: 1 <= k <= jobs.length <= 12 1 <= jobs[i] <= 10^7
class Solution(object): def minimumTimeRequired(self, jobs, k): """ :type jobs: List[int] :type k: int :rtype: int """ js = sorted(jobs) its = [0]*k gr = [0x7ffffffff] n = len(js) def dfs(i, ts): if gr[0]<=ts[k-1]: return if i==n: gr[0]=ts[k-1] return if i==0: ts[k-1]=js[i] dfs(i+1, ts) else: nts = [t for t in ts] j=0 while j<k: if ts[j]+js[i]>=gr[0]: break if j==0 or ts[j]!=ts[j-1]: ct=ts[j]+js[i] jj=j+1 while jj<k: if ts[jj]<ct: nts[jj-1]=ts[jj] else: break jj+=1 nts[jj-1]=ct dfs(i+1, nts) nts[j]=ts[j] j+=1 dfs(0, its) return gr[0]
7f9560
159244
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] < perm[i + 1], and s[i] == 'D' if perm[i] > perm[i + 1]. Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.   Example 1: Input: s = "IDID" Output: [0,4,1,3,2] Example 2: Input: s = "III" Output: [0,1,2,3] Example 3: Input: s = "DDI" Output: [3,2,0,1]   Constraints: 1 <= s.length <= 100000 s[i] is either 'I' or 'D'.
class Solution(object): def diStringMatch(self, S): """ :type S: str :rtype: List[int] """ # 0 - N n = len(S) nums = list(range(n + 1)) i, j = 0, len(nums) - 1 ans = [] for ch in S: if ch == 'I': ans.append(nums[i]) i += 1 else: ans.append(nums[j]) j -= 1 ans.append(i) return ans
745f52
159244
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] < perm[i + 1], and s[i] == 'D' if perm[i] > perm[i + 1]. Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.   Example 1: Input: s = "IDID" Output: [0,4,1,3,2] Example 2: Input: s = "III" Output: [0,1,2,3] Example 3: Input: s = "DDI" Output: [3,2,0,1]   Constraints: 1 <= s.length <= 100000 s[i] is either 'I' or 'D'.
from collections import deque class Solution: def diStringMatch(self, S): """ :type S: str :rtype: List[int] """ q = deque(range(0, len(S) + 1)) result = [] if S[0] == 'I': result.append(q.popleft()) else: result.append(q.pop()) for i in range(0, len(S) - 1): if S[i] == 'I': if S[i + 1] == 'I': result.append(q.popleft()) else: result.append(q.pop()) else: if S[i + 1] == 'D': result.append(q.pop()) else: result.append(q.popleft()) result.append(q.pop()) return result
a5197d
adba41
Given a positive integer n, return the punishment number of n. The punishment number of n is defined as the sum of the squares of all integers i such that: 1 <= i <= n The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.   Example 1: Input: n = 10 Output: 182 Explanation: There are exactly 3 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 Example 2: Input: n = 37 Output: 1478 Explanation: There are exactly 4 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478   Constraints: 1 <= n <= 1000
class Solution(object): def punishmentNumber(self, n): """ :type n: int :rtype: int """ def p(s, i, c, t): if i == len(s): return c == t v = 0 for j in range(i, len(s)): v = v * 10 + ord(s[j]) - ord('0') if p(s, j + 1, c + v, t): return True return False a = 0 for i in range(1, n + 1): a += i * i if p(str(i * i), 0, 0, i) else 0 return a
25d6b8
adba41
Given a positive integer n, return the punishment number of n. The punishment number of n is defined as the sum of the squares of all integers i such that: 1 <= i <= n The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.   Example 1: Input: n = 10 Output: 182 Explanation: There are exactly 3 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 Example 2: Input: n = 37 Output: 1478 Explanation: There are exactly 4 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478   Constraints: 1 <= n <= 1000
class Solution: def punishmentNumber(self, n: int) -> int: def check(x): s = str(x * x) n = len(s) def dfs(i, tar): if tar < 0: return False if i >= n and tar == 0: return True for j in range(i, n): if dfs(j+1, tar - int(s[i:j+1])): return True return False return dfs(0, x) ans = 0 for i in range(1, n+1): if check(i): ans += i * i return ans
c757cf
1c154c
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. Your friend Bob will pick the next slice in the clockwise direction of your pick. Repeat until there are no more slices of pizzas. Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.   Constraints: 3 * n == slices.length 1 <= slices.length <= 500 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: import functools @functools.lru_cache(None) def dp(i, j, k, loop = 0): if k == 1: return max(slices[i:j+1]) if j - i + 1 < k * 2 - 1: return -float('inf') return max(dp(i + loop, j - 2, k - 1) + slices[j], dp(i, j - 1, k)) return dp(0, len(slices) - 1, len(slices) // 3, 1)
2df76b
1c154c
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. Your friend Bob will pick the next slice in the clockwise direction of your pick. Repeat until there are no more slices of pizzas. Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.   Constraints: 3 * n == slices.length 1 <= slices.length <= 500 1 <= slices[i] <= 1000
class Solution(object): def maxSizeSlices(self, slices): """ :type slices: List[int] :rtype: int """ m = len(slices) n = m // 3 dp = [[[0, 0] for j in range(n + 1)] for i in range(m + 1)] dp[1][1] = [slices[0], 0] for i in range(1, m + 1): for j in range(1, min(n + 1, i + 1)): if i - 2 >= 0: dp[i][j][0] = max(dp[i - 2][j - 1][0] + slices[i - 1], dp[i - 1][j][0]) dp[i][j][1] = max(dp[i - 2][j - 1][1] + slices[i - 1], dp[i - 1][j][1]) if i - 1 >= 0: dp[i][j][0] = max(dp[i][j][0], dp[i - 1][j][0]) dp[i][j][1] = max(dp[i][j][1], dp[i - 1][j][1]) #print(dp) return max(dp[m][n][1], max(dp[m - 1][n][1], dp[m - 1][n][0]))
f4af4f
a8cee2
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.   Example 1: Input: nums = [10,5,2,6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. Example 2: Input: nums = [1,2,3], k = 0 Output: 0   Constraints: 1 <= nums.length <= 3 * 10000 1 <= nums[i] <= 1000 0 <= k <= 1000000
class Solution: def numSubarrayProductLessThanK(self, nums, k): q, ans = [], 0 for x in nums: if x >= k: q = [] continue else:#search the position for pos in range(len(q) - 1, -1, -1): tmp = q[pos] * x if tmp >= k: q = q[pos + 1:] if pos + 1 < len(q) else [] break; else: q[pos] = tmp q.append(x) ans += len(q) return ans
92bf04
a8cee2
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.   Example 1: Input: nums = [10,5,2,6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. Example 2: Input: nums = [1,2,3], k = 0 Output: 0   Constraints: 1 <= nums.length <= 3 * 10000 1 <= nums[i] <= 1000 0 <= k <= 1000000
class Solution(object): def numSubarrayProductLessThanK(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ length=len(nums) products=1 last=-1 output=0 for i in range(length): products*=nums[i] if products<k: output+=(i-last) else: while products>=k and last<i: last+=1 products/=nums[last] output+=(i-last) return output
3069dc
58ff8a
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.   Example 1: Input: n = 4, connections = [[0,1],[0,2],[1,2]] Output: 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Example 3: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] Output: -1 Explanation: There are not enough cables.   Constraints: 1 <= n <= 100000 1 <= connections.length <= min(n * (n - 1) / 2, 100000) connections[i].length == 2 0 <= ai, bi < n ai != bi There are no repeated connections. No two computers are connected by more than one cable.
class DSU: def __init__(self, N): self.par = list(range(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 self.par[yr] = xr return True class Solution(object): def makeConnected(self, n, connections): dsu = DSU(n) spare = 0 components = n for u, v in connections: if not dsu.union(u, v): spare += 1 else: components -= 1 if components == 1: return 0 if spare >= (components - 1): return components - 1 else: return -1
96c3ac
58ff8a
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.   Example 1: Input: n = 4, connections = [[0,1],[0,2],[1,2]] Output: 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Example 3: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] Output: -1 Explanation: There are not enough cables.   Constraints: 1 <= n <= 100000 1 <= connections.length <= min(n * (n - 1) / 2, 100000) connections[i].length == 2 0 <= ai, bi < n ai != bi There are no repeated connections. No two computers are connected by more than one cable.
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: def union(i,j): leader_i, leader_j = find(i), find(j) sets[j] = sets[i] = sets[leader_j] = leader_i def find(i): while i != sets[i]: i = sets[i] return i sets = list(range(n)) cables = len(connections) if cables < n - 1: return -1 for a, b in connections: union(a,b) leaders = 0 for i in range(n): if find(i) == i: leaders += 1 return leaders - 1
baef3a
a4462e
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0. Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z'). Return the final string after all such shifts to s are applied.   Example 1: Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]] Output: "ace" Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac". Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd". Finally, shift the characters from index 0 to index 2 forward. Now s = "ace". Example 2: Input: s = "dztz", shifts = [[0,0,0],[1,1,1]] Output: "catz" Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz". Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".   Constraints: 1 <= s.length, shifts.length <= 5 * 10000 shifts[i].length == 3 0 <= starti <= endi < s.length 0 <= directioni <= 1 s consists of lowercase English letters.
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) d = [0]*(n+1) for l, r, t in shifts: if t: d[l] += 1 d[r+1] -= 1 else: d[l] -= 1 d[r+1] += 1 cur = 0 t = [] for i in range(n): cur += d[i] z = (ord(s[i])-97+cur)%26 t.append(chr(z+97)) return ''.join(t)
6bf234
a4462e
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0. Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z'). Return the final string after all such shifts to s are applied.   Example 1: Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]] Output: "ace" Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac". Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd". Finally, shift the characters from index 0 to index 2 forward. Now s = "ace". Example 2: Input: s = "dztz", shifts = [[0,0,0],[1,1,1]] Output: "catz" Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz". Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".   Constraints: 1 <= s.length, shifts.length <= 5 * 10000 shifts[i].length == 3 0 <= starti <= endi < s.length 0 <= directioni <= 1 s consists of lowercase English letters.
class Solution(object): def shiftingLetters(self, s, shifts): """ :type s: str :type shifts: List[List[int]] :rtype: str """ t, c, u = [0] * len(s), 0, [] for v, e, d in shifts: t[v] += 1 if d == 1 else -1 if e + 1 < len(s): t[e + 1] -= 1 if d == 1 else -1 for i in range(len(s)): t[i], c = t[i] + c, t[i] + c for i in range(len(s)): u.append(chr(ord(s[i]) + t[i] % 26 + (-26 if ord(s[i]) + t[i] % 26 > ord('z') else -26 if ord(s[i]) + t[i] % 26 < ord('a') else 0))) return ''.join(u)
f902ca
b780be
There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi]. You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle. Return the minimum time during which the computer should be turned on to complete all tasks.   Example 1: Input: tasks = [[2,3,1],[4,5,1],[1,5,2]] Output: 2 Explanation: - The first task can be run in the inclusive time range [2, 2]. - The second task can be run in the inclusive time range [5, 5]. - The third task can be run in the two inclusive time ranges [2, 2] and [5, 5]. The computer will be on for a total of 2 seconds. Example 2: Input: tasks = [[1,3,2],[2,5,3],[5,6,2]] Output: 4 Explanation: - The first task can be run in the inclusive time range [2, 3]. - The second task can be run in the inclusive time ranges [2, 3] and [5, 5]. - The third task can be run in the two inclusive time range [5, 6]. The computer will be on for a total of 4 seconds.   Constraints: 1 <= tasks.length <= 2000 tasks[i].length == 3 1 <= starti, endi <= 2000 1 <= durationi <= endi - starti + 1
class Solution(object): def findMinimumTime(self, tasks): """ :type tasks: List[List[int]] :rtype: int """ tasks.sort(key = lambda x : x[1]) c = [0] * 2001 for a, b, d, in tasks: e, f = sum(c[a:b + 1]), b while e < d: e, c[b], b = e if c[b] else e + 1, 1, b - 1 return sum(c)
90227b
b780be
There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi]. You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle. Return the minimum time during which the computer should be turned on to complete all tasks.   Example 1: Input: tasks = [[2,3,1],[4,5,1],[1,5,2]] Output: 2 Explanation: - The first task can be run in the inclusive time range [2, 2]. - The second task can be run in the inclusive time range [5, 5]. - The third task can be run in the two inclusive time ranges [2, 2] and [5, 5]. The computer will be on for a total of 2 seconds. Example 2: Input: tasks = [[1,3,2],[2,5,3],[5,6,2]] Output: 4 Explanation: - The first task can be run in the inclusive time range [2, 3]. - The second task can be run in the inclusive time ranges [2, 3] and [5, 5]. - The third task can be run in the two inclusive time range [5, 6]. The computer will be on for a total of 4 seconds.   Constraints: 1 <= tasks.length <= 2000 tasks[i].length == 3 1 <= starti, endi <= 2000 1 <= durationi <= endi - starti + 1
class Solution: def findMinimumTime(self, tasks: List[List[int]]) -> int: tasks.sort(key=itemgetter(1)) tmp = set() for s, e, d in tasks: cnt = 0 for x in tmp: if s <= x <= e: cnt += 1 while cnt < d: if e not in tmp: tmp.add(e) cnt += 1 e -= 1 return len(tmp)
18c4b6
c1cc0f
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.   Example 1: Input: prices = [3,2,1,4] Output: 7 Explanation: There are 7 smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], and [3,2,1] Note that a period with one day is a smooth descent period by the definition. Example 2: Input: prices = [8,6,7,7] Output: 4 Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7] Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1. Example 3: Input: prices = [1] Output: 1 Explanation: There is 1 smooth descent period: [1]   Constraints: 1 <= prices.length <= 100000 1 <= prices[i] <= 100000
class Solution: def getDescentPeriods(self, prices: List[int]) -> int: ans = 0 p = -1 c = 0 for i in prices: if p == i+1: c += 1 p = i else: ans += c*(c+1)//2 c = 1 p = i ans += c*(c+1)//2 return ans
e6d457
c1cc0f
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.   Example 1: Input: prices = [3,2,1,4] Output: 7 Explanation: There are 7 smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], and [3,2,1] Note that a period with one day is a smooth descent period by the definition. Example 2: Input: prices = [8,6,7,7] Output: 4 Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7] Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1. Example 3: Input: prices = [1] Output: 1 Explanation: There is 1 smooth descent period: [1]   Constraints: 1 <= prices.length <= 100000 1 <= prices[i] <= 100000
class Solution(object): def getDescentPeriods(self, prices): """ :type prices: List[int] :rtype: int """ ans = 1 accu = 1 for i in range(1,len(prices)): if prices[i]==prices[i-1]-1: accu += 1 else: accu = 1 ans += accu return ans
10e91b
52c795
You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index.   Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 3 Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.   Constraints: 1 <= nums.length <= 10000 0 <= nums[i] <= 10000 0 <= k <= 10000
class Solution(object): def smallestRangeII(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ # assume everything already -K so we pick some to +2K if not A: return 0 A = sorted(set(A)) K *= 2 m = A[-1] r = A[-1] - A[0] for i in xrange(len(A)-1): if A[i] >= A[0] + K: break m = max(m, A[i] + K) r = min(r, m - min(A[i+1], A[0] + K)) return r
1aa2f1
52c795
You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index.   Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 3 Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.   Constraints: 1 <= nums.length <= 10000 0 <= nums[i] <= 10000 0 <= k <= 10000
class Solution: def smallestRangeII(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ B = sorted(A) min_e, max_e = B[0], B[-1] ret = max_e - min_e for i in range(len(B)-1): ret = min(ret, max(max_e - K, B[i] + K) - min(min_e + K, B[i+1] - K)) return ret
b475b6
a21d88
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: i + minJump <= j <= min(i + maxJump, s.length - 1), and s[j] == '0'. Return true if you can reach index s.length - 1 in s, or false otherwise.   Example 1: Input: s = "011010", minJump = 2, maxJump = 3 Output: true Explanation: In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. Example 2: Input: s = "01101110", minJump = 2, maxJump = 3 Output: false   Constraints: 2 <= s.length <= 100000 s[i] is either '0' or '1'. s[0] == '0' 1 <= minJump <= maxJump < s.length
class NumArray: def __init__(self, nums: List[int]): self.raw = [t for t in nums] T = 2 while T <= len(nums) : for i in range(T, len(nums)+1, T) : nums[i-1] += nums[i-1-T//2] T = T * 2 self.nums = nums self.lowbit = lambda x : x&(-x) def update(self, index: int, val: int) -> None: dis = val - self.raw[index] self.raw[index] = val while index < len(self.nums) : self.nums[index] += dis index += self.lowbit(index+1) def presums(self, index) : to_ret = 0 while index >= 0 : to_ret += self.nums[index] index -= self.lowbit(index+1) return to_ret def sumRange(self, left: int, right: int) -> int: return self.presums(right)-self.presums(left-1) class Solution: def canReach(self, ss: str, minJump: int, maxJump: int) -> bool: na = NumArray([0]*len(ss)) na.update(0, 1) for i, t in enumerate(ss) : if i == 0 : continue if t == '1' : continue if i - minJump < 0 : continue s, e = max(0, i-maxJump), i-minJump t = na.sumRange(s, e) if t > 0 : if i == len(ss) - 1 : return True na.update(i, 1) # print(na.raw) return False
db80eb
a21d88
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: i + minJump <= j <= min(i + maxJump, s.length - 1), and s[j] == '0'. Return true if you can reach index s.length - 1 in s, or false otherwise.   Example 1: Input: s = "011010", minJump = 2, maxJump = 3 Output: true Explanation: In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. Example 2: Input: s = "01101110", minJump = 2, maxJump = 3 Output: false   Constraints: 2 <= s.length <= 100000 s[i] is either '0' or '1'. s[0] == '0' 1 <= minJump <= maxJump < s.length
class Solution(object): def canReach(self, s, minJump, maxJump): """ :type s: str :type minJump: int :type maxJump: int :rtype: bool """ lo = minJump hi = maxJump n = len(s) r = [0] * n r[0] = 1 w = 0 # sum(r[i-hi:i-lo]) for i in xrange(lo, n): w += r[i-lo] if s[i] == '0' and w > 0: r[i] = 1 if i >= hi: w -= r[i-hi] return r[n-1]
5e9670
f5b11f
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.   Example 1: Input: arr = [3,5,1,2,4], m = 1 Output: 4 Explanation: Step 1: "00100", groups: ["1"] Step 2: "00101", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "11101", groups: ["111", "1"] Step 5: "11111", groups: ["11111"] The latest step at which there exists a group of size 1 is step 4. Example 2: Input: arr = [3,1,5,4,2], m = 2 Output: -1 Explanation: Step 1: "00100", groups: ["1"] Step 2: "10100", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "10111", groups: ["1", "111"] Step 5: "11111", groups: ["11111"] No group of size 2 exists during any step.   Constraints: n == arr.length 1 <= m <= n <= 100000 1 <= arr[i] <= n All integers in arr are distinct.
class UnionFindSet: def __init__(self, n): self.parents = list(range(n)) self.ranks = [1] * n def find(self, u): if u != self.parents[u]: self.parents[u] = self.find(self.parents[u]) return self.parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False if self.ranks[pu] > self.ranks[pv]: self.parents[pv] = pu self.ranks[pu] += self.ranks[pv] elif self.ranks[pv] > self.ranks[pu]: self.parents[pu] = pv self.ranks[pv] += self.ranks[pu] else: self.parents[pu] = pv self.ranks[pv] += self.ranks[pu] return True class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: n = len(arr) uf = UnionFindSet(n) b_arr = [0] * n ans = -1 for step, num in enumerate(arr): idx = num - 1 b_arr[idx] = 1 if idx > 0 and b_arr[idx - 1]: p = uf.find(idx - 1) if uf.ranks[p] == m: ans = step uf.union(idx, idx - 1) if idx < n - 1 and b_arr[idx + 1]: p = uf.find(idx + 1) if uf.ranks[p] == m: ans = step uf.union(idx, idx + 1) p = uf.find(idx) if uf.ranks[p] == m: ans = step + 1 for idx in range(n): p = uf.find(idx) if uf.ranks[p] == m: return n return ans
d95f11
f5b11f
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.   Example 1: Input: arr = [3,5,1,2,4], m = 1 Output: 4 Explanation: Step 1: "00100", groups: ["1"] Step 2: "00101", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "11101", groups: ["111", "1"] Step 5: "11111", groups: ["11111"] The latest step at which there exists a group of size 1 is step 4. Example 2: Input: arr = [3,1,5,4,2], m = 2 Output: -1 Explanation: Step 1: "00100", groups: ["1"] Step 2: "10100", groups: ["1", "1"] Step 3: "10101", groups: ["1", "1", "1"] Step 4: "10111", groups: ["1", "111"] Step 5: "11111", groups: ["11111"] No group of size 2 exists during any step.   Constraints: n == arr.length 1 <= m <= n <= 100000 1 <= arr[i] <= n All integers in arr are distinct.
class Solution(object): def findLatestStep(self, A, m): n = len(A) count = [0] * n counter = collections.Counter() res = -1 for i,a in enumerate(A): a -= 1 count[a] = 1 left = right = 0 if a: left = count[a-1] if a < n - 1: right = count[a + 1] count[a] = count[a-left] = count[a+right] = left+right+1 counter[left] -= 1 counter[right] -= 1 counter[count[a]] += 1 if counter[m]: res = i + 1 return res
0c0bb5
bbe17b
Alice and Bob take turns playing a game, with Alice starting first. You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num: Choose an index i where num[i] == '?'. Replace num[i] with any digit between '0' and '9'. The game ends when there are no more '?' characters in num. For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal. For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3. Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.   Example 1: Input: num = "5023" Output: false Explanation: There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3. Example 2: Input: num = "25??" Output: true Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal. Example 3: Input: num = "?3295???" Output: false Explanation: It can be proven that Bob will always win. One possible outcome is: - Alice replaces the first '?' with '9'. num = "93295???". - Bob replaces one of the '?' in the right half with '9'. num = "932959??". - Alice replaces one of the '?' in the right half with '2'. num = "9329592?". - Bob replaces the last '?' in the right half with '7'. num = "93295927". Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.   Constraints: 2 <= num.length <= 100000 num.length is even. num consists of only digits and '?'.
class Solution(object): def sumGame(self, num): """ :type num: str :rtype: bool """ n = len(num) z = ord('0') cc = 0 c1, c2 = 0, 0 s1, s2 = 0, 0 for c in num: if c=='?': cc+=1 if cc&1: return True m = n/2 i = 0 while i<m: c = num[i] if c=='?': c1+=1 else: s1 += ord(c)-z i+=1 while i<n: c=num[i] if c=='?': c2+=1 else: s2 += ord(c)-z i+=1 # try left > right d = s1+(c1+1)/2*9-s2 if d>(c2+1)/2*9: return True d = s2+(c2+1)/2*9-s1 if d>(c1+1)/2*9: return True return False
31f88b
bbe17b
Alice and Bob take turns playing a game, with Alice starting first. You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num: Choose an index i where num[i] == '?'. Replace num[i] with any digit between '0' and '9'. The game ends when there are no more '?' characters in num. For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal. For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3. Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.   Example 1: Input: num = "5023" Output: false Explanation: There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3. Example 2: Input: num = "25??" Output: true Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal. Example 3: Input: num = "?3295???" Output: false Explanation: It can be proven that Bob will always win. One possible outcome is: - Alice replaces the first '?' with '9'. num = "93295???". - Bob replaces one of the '?' in the right half with '9'. num = "932959??". - Alice replaces one of the '?' in the right half with '2'. num = "9329592?". - Bob replaces the last '?' in the right half with '7'. num = "93295927". Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.   Constraints: 2 <= num.length <= 100000 num.length is even. num consists of only digits and '?'.
class Solution: def sumGame(self, num: str) -> bool: s1 = s2 = x = y = 0 n = len(num) for i in range(n // 2): if num[i] == '?': x += 1 else: s1 += int(num[i]) for i in range(n // 2, n): if num[i] == '?': y += 1 else: s2 += int(num[i]) return s2 - s1 != 4.5 * (x - y)
ef80b4
4bf9f4
Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced.   Example 1: Input: s = "(()))" Output: 1 Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced. Example 2: Input: s = "())" Output: 0 Explanation: The string is already balanced. Example 3: Input: s = "))())(" Output: 3 Explanation: Add '(' to match the first '))', Add '))' to match the last '('.   Constraints: 1 <= s.length <= 100000 s consists of '(' and ')' only.
class Solution(object): def minInsertions(self, S): bal = ans = 0 for c in S: if c == '(': bal += 2 if bal & 1: bal -= 1 ans += 1 else: bal -= 1 if bal < 0: ans += 1 bal += 2 ans += bal return ans
b178ae
4bf9f4
Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced.   Example 1: Input: s = "(()))" Output: 1 Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced. Example 2: Input: s = "())" Output: 0 Explanation: The string is already balanced. Example 3: Input: s = "))())(" Output: 3 Explanation: Add '(' to match the first '))', Add '))' to match the last '('.   Constraints: 1 <= s.length <= 100000 s consists of '(' and ')' only.
class Solution: def minInsertions(self, s: str) -> int: ret = 0 a = [] for i in range(len(s)): if s[i] == '(': if len(a) > 0 and a[-1] == ')': ret += 1 a.pop() else: a.append('(') else: if len(a) > 0 and a[-1] == ')': a.pop() a.pop() elif len(a) == 0: ret += 1 a.append('(') a.append(')') else: a.append(')') if len(a) > 0 and a[-1] == ')': ret += 1 a.pop() a.pop() ret += len(a) * 2 return ret
230814
e36ca2
You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2) However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]). In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k.   Example 1: Input: arr = [5,4,3,2,1], k = 1 Output: 4 Explanation: For k = 1, the resultant array has to be non-decreasing. Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations. It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations. It can be shown that we cannot make the array K-increasing in less than 4 operations. Example 2: Input: arr = [4,1,5,2,6,2], k = 2 Output: 0 Explanation: This is the same example as the one in the problem description. Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i]. Since the given array is already K-increasing, we do not need to perform any operations. Example 3: Input: arr = [4,1,5,2,6,2], k = 3 Output: 2 Explanation: Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5. One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5. The array will now be [4,1,5,4,6,5]. Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i], k <= arr.length
class Solution: def kIncreasing(self, arr: List[int], k: int) -> int: n = len(arr) ans = 0 for i in range(k): vt = [] for j in range(i, n, k): vt.append(arr[j]) st = [] for c in vt: j = bisect.bisect_left(st,c+1) if j == len(st): st.append(c) else: st[j] = c ans += len(vt)-len(st) return ans
f1e4ed
e36ca2
You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2) However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]). In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k.   Example 1: Input: arr = [5,4,3,2,1], k = 1 Output: 4 Explanation: For k = 1, the resultant array has to be non-decreasing. Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations. It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations. It can be shown that we cannot make the array K-increasing in less than 4 operations. Example 2: Input: arr = [4,1,5,2,6,2], k = 2 Output: 0 Explanation: This is the same example as the one in the problem description. Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i]. Since the given array is already K-increasing, we do not need to perform any operations. Example 3: Input: arr = [4,1,5,2,6,2], k = 3 Output: 2 Explanation: Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5. One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5. The array will now be [4,1,5,4,6,5]. Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i], k <= arr.length
class Solution(object): def kIncreasing(self, arr, k): """ :type arr: List[int] :type k: int :rtype: int """ def lcs(arr1): temp = [] for num in arr1: loc = bisect.bisect(temp,num) if loc==len(temp): temp.append(num) else: temp[loc] = num return len(temp) ans = 0 for i in range(k): temp = arr[i::k] ans += len(temp) - lcs(temp) return ans
63d310
54d23f
You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together. We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct). Return the K-Sum of the array. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Note that the empty subsequence is considered to have a sum of 0.   Example 1: Input: nums = [2,4,-2], k = 5 Output: 2 Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order: - 6, 4, 4, 2, 2, 0, 0, -2. The 5-Sum of the array is 2. Example 2: Input: nums = [1,-2,3,4,-10,12], k = 16 Output: 10 Explanation: The 16-Sum of the array is 10.   Constraints: n == nums.length 1 <= n <= 100000 -10^9 <= nums[i] <= 10^9 1 <= k <= min(2000, 2n)
from heapq import heappush, heappop class Solution: def kSum(self, nums: List[int], k: int) -> int: total = sum(max(0, num) for num in nums) pos = sorted([abs(num) for num in nums]) s, heap = 0, [(pos[0], 0)] for j in range(k - 1): s, i = heappop(heap) if i + 1 < len(nums): heappush(heap, (s - pos[i] + pos[i + 1], i + 1)) heappush(heap, (s + pos[i + 1], i + 1)) return total - s
6414ed
54d23f
You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together. We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct). Return the K-Sum of the array. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Note that the empty subsequence is considered to have a sum of 0.   Example 1: Input: nums = [2,4,-2], k = 5 Output: 2 Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order: - 6, 4, 4, 2, 2, 0, 0, -2. The 5-Sum of the array is 2. Example 2: Input: nums = [1,-2,3,4,-10,12], k = 16 Output: 10 Explanation: The 16-Sum of the array is 10.   Constraints: n == nums.length 1 <= n <= 100000 -10^9 <= nums[i] <= 10^9 1 <= k <= min(2000, 2n)
class Solution(object): def kSum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ s, l, d, q = 0, [], [0], [] for n in nums: l.append(abs(n)) s += n if n > 0 else 0 l.sort() heapq.heappush(q, [l[0], 0]) while k > 1 and q: c, e = heapq.heappop(q) d.append(c) n = e + 1 if n < len(l): heapq.heappush(q, [c + l[n], n]) heapq.heappush(q, [c + l[n] - l[n - 1], n]) k -= 1 return s - d[-1]