sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
ae1c2c
4a480f
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.   Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20   Constraints: 2 <= arr1.length == arr2.length <= 40000 -10^6 <= arr1[i], arr2[i] <= 10^6
class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: n = len(arr1) rtn = 0 for sign1 in [-1, 1]: for sign2 in [-1, 1]: b = [] for i in range(n): b.append(arr1[i] * sign1 + arr2[i] * sign2 + i) rtn = max(rtn, max(b) - min(b)) return rtn
63bce4
4a480f
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.   Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20   Constraints: 2 <= arr1.length == arr2.length <= 40000 -10^6 <= arr1[i], arr2[i] <= 10^6
class Solution(object): def maxAbsValExpr(self, A, B): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ # max Ai - Aj + Bi - Bj, Aj - Ai + Bi - Bj, Ai - Aj + Bj - Bi, Aj - Ai + Bj - Bi T = [A[0] + B[0], A[0] - B[0], -A[0] + B[0], -A[0] - B[0]] I = [0] * 4 ans = 0 for i in xrange(1, len(A)): for j in I: ans = max(ans, abs(A[i] - A[j]) + abs(B[i] - B[j]) + abs(i - j)) for t, (ka, kb) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))): k = ka * A[i] + kb * B[i] if k > T[t]: T[t] = k I[t] = i return ans
3d79cf
88be47
There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect. For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4. Return the maximum number of prizes you can win if you choose the two segments optimally.   Example 1: Input: prizePositions = [1,1,2,2,3,3,5], k = 2 Output: 7 Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. Example 2: Input: prizePositions = [1,2,3,4], k = 0 Output: 2 Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes.   Constraints: 1 <= prizePositions.length <= 100000 1 <= prizePositions[i] <= 10^9 0 <= k <= 10^9 prizePositions is sorted in non-decreasing order.  
class Solution: def maximizeWin(self, prizePositions: List[int], k: int) -> int: n = len(prizePositions) pre = [0]*(n+1) for i in range(n): cur = i + 1 - bisect.bisect_left(prizePositions, prizePositions[i]-k) pre[i+1] = pre[i] if pre[i] > cur else cur post = [0] * (n + 1) for i in range(n-1, -1, -1): cur = bisect.bisect_right(prizePositions, prizePositions[i] + k) - i post[i] = post[i+1] if post[i+1] > cur else cur ans = max(pre[i]+post[i] for i in range(n)) for i in range(n): cur = i + 1 - bisect.bisect_left(prizePositions, prizePositions[i]-2*k) ans = ans if ans > cur else cur return ans
c34354
88be47
There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect. For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4. Return the maximum number of prizes you can win if you choose the two segments optimally.   Example 1: Input: prizePositions = [1,1,2,2,3,3,5], k = 2 Output: 7 Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. Example 2: Input: prizePositions = [1,2,3,4], k = 0 Output: 2 Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes.   Constraints: 1 <= prizePositions.length <= 100000 1 <= prizePositions[i] <= 10^9 0 <= k <= 10^9 prizePositions is sorted in non-decreasing order.  
from collections import Counter class Solution(object): def maximizeWin(self, prizePositions, k): """ :type prizePositions: List[int] :type k: int :rtype: int """ cnt = Counter(prizePositions) pos = list(sorted(cnt.keys())) n = len(pos) max_price = [0] * (n + 1) j = n - 1 prize_cnt = 0 now_max = 0 for i in range(n - 1, -1, -1): p = pos[i] prize_cnt += cnt[p] while pos[j] > pos[i] + k: prize_cnt -= cnt[pos[j]] j -= 1 now_max = max(now_max, prize_cnt) max_price[i] = now_max ans = 0 j = 0 now_max = 0 prize_cnt = 0 # print(max_price) for i in range(n): p = pos[i] prize_cnt += cnt[p] while pos[j] < pos[i] - k: prize_cnt -= cnt[pos[j]] j += 1 now_max = max(now_max, prize_cnt) # print(i, p, prize_cnt, now_max) ans = max(now_max + max_price[i + 1], ans) return ans
64c83d
9e74d0
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news.   Example 1: Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown.   Constraints: 1 <= n <= 100000 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.
class Solution(object): def numOfMinutes(self, n, headID, parent, informTime): children = collections.defaultdict(list) for i, x in enumerate(parent): if x >= 0: children[x].append(i) self.ans = 0 def dfs(node, w): if w > self.ans: self.ans = w for nei in children[node]: dfs(nei, informTime[node] + w) dfs(headID, 0) return self.ans
4a4f63
9e74d0
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news.   Example 1: Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown.   Constraints: 1 <= n <= 100000 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.
from functools import lru_cache class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: @lru_cache(maxsize=None) def dfs(x): fa=manager[x] if fa==-1: return 0 return dfs(fa)+informTime[fa] return max(dfs(i) for i in range(n))
dd376d
36c675
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t.   Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 → 1.   Constraints: The number of nodes in the tree is n. 2 <= n <= 100000 1 <= Node.val <= n All the values in the tree are unique. 1 <= startValue, destValue <= n startValue != destValue
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def getDirections(self, root, startValue, destValue): """ :type root: Optional[TreeNode] :type startValue: int :type destValue: int :rtype: str """ path = [] loc = [None, None] def _f(u): if u is None: return if u.val == startValue: loc[0] = ''.join(path) if u.val == destValue: loc[1] = ''.join(path) path.append('L') _f(u.left) path[-1] = 'R' _f(u.right) path.pop() _f(root) i = 0 m = min(map(len, loc)) while i < m and loc[0][i] == loc[1][i]: i += 1 return 'U'*(len(loc[0])-i) + loc[1][i:]
676775
36c675
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t.   Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 → 1.   Constraints: The number of nodes in the tree is n. 2 <= n <= 100000 1 <= Node.val <= n All the values in the tree are unique. 1 <= startValue, destValue <= n startValue != destValue
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: d = defaultdict(dict) q = deque([root]) while q: curr = q.popleft() if curr.left: d[curr.val]["L"] = curr.left.val d[curr.left.val]["U"] = curr.val q.append(curr.left) if curr.right: d[curr.val]["R"] = curr.right.val d[curr.right.val]["U"] = curr.val q.append(curr.right) q = deque([(startValue, "")]) visited = set() visited.add(startValue) while q: val, pattern = q.popleft() if val == destValue: return pattern for k, v in d[val].items(): if v not in visited: visited.add(v) q.append((v, pattern + k)) return ""
28044a
f99e7a
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously. It takes the same amount of time to water each plant regardless of how much water it needs. Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant. In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.   Example 1: Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5 Output: 1 Explanation: - Initially, Alice and Bob have 5 units of water each in their watering cans. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 3 units and 2 units of water respectively. - Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it. So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1. Example 2: Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4 Output: 2 Explanation: - Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively. - Since neither of them have enough water for their current plants, they refill their cans and then water the plants. So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2. Example 3: Input: plants = [5], capacityA = 10, capacityB = 8 Output: 0 Explanation: - There is only one plant. - Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant. So, the total number of times they have to refill is 0.   Constraints: n == plants.length 1 <= n <= 100000 1 <= plants[i] <= 1000000 max(plants[i]) <= capacityA, capacityB <= 10^9
class Solution: def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int: n = len(plants) half = n // 2 refill = 0 balance = capacityA for i in range(half): if balance < plants[i]: balance = capacityA refill += 1 balance -= plants[i] balance2 = capacityB for i in range(half): if balance2 < plants[-1-i]: balance2 = capacityB refill += 1 balance2 -= plants[-1-i] if n % 2 == 1: rem = plants[half] if balance >= balance2: if balance < rem: refill += 1 else: if balance2 < rem: refill += 1 return refill
2dfe73
f99e7a
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously. It takes the same amount of time to water each plant regardless of how much water it needs. Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant. In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.   Example 1: Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5 Output: 1 Explanation: - Initially, Alice and Bob have 5 units of water each in their watering cans. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 3 units and 2 units of water respectively. - Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it. So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1. Example 2: Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4 Output: 2 Explanation: - Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively. - Since neither of them have enough water for their current plants, they refill their cans and then water the plants. So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2. Example 3: Input: plants = [5], capacityA = 10, capacityB = 8 Output: 0 Explanation: - There is only one plant. - Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant. So, the total number of times they have to refill is 0.   Constraints: n == plants.length 1 <= n <= 100000 1 <= plants[i] <= 1000000 max(plants[i]) <= capacityA, capacityB <= 10^9
class Solution(object): def minimumRefill(self, plants, capacityA, capacityB): """ :type plants: List[int] :type capacityA: int :type capacityB: int :rtype: int """ a = plants i = 0 j = len(a)-1 r = 0 ci = capacityA cj = capacityB while i < j: if ci < a[i]: r += 1 ci = capacityA ci -= a[i] i += 1 if cj < a[j]: r += 1 cj = capacityB cj -= a[j] j -= 1 if i == j: if max(ci, cj) < a[i]: r += 1 return r
28540b
e66801
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct password is "345" and you enter in "012345": After typing 0, the most recent 3 digits is "0", which is incorrect. After typing 1, the most recent 3 digits is "01", which is incorrect. After typing 2, the most recent 3 digits is "012", which is incorrect. After typing 3, the most recent 3 digits is "123", which is incorrect. After typing 4, the most recent 3 digits is "234", which is incorrect. After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. Return any string of minimum length that will unlock the safe at some point of entering it.   Example 1: Input: n = 1, k = 2 Output: "10" Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe. Example 2: Input: n = 2, k = 2 Output: "01100" Explanation: For each possible password: - "00" is typed in starting from the 4th digit. - "01" is typed in starting from the 1st digit. - "10" is typed in starting from the 3rd digit. - "11" is typed in starting from the 2nd digit. Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.   Constraints: 1 <= n <= 4 1 <= k <= 10 1 <= kn <= 4096
import itertools import sys sys.setrecursionlimit(20000) class Solution: def dfs(self, grams, prefix, n, k): if not grams: return prefix suffix = prefix[1 - n:] for c in range(k): candidate = suffix + str(c) if candidate in grams: # Try it grams.remove(candidate) ans = self.dfs(grams, prefix + str(c), n, k) if ans: return ans grams.add(candidate) return '' def crackSafe(self, n, k): # run a dfs to enumerate all possible combinations digits = ''.join(str(i) for i in range(k)) if n == 1: return digits grams = set([''.join(list(x)) for x in itertools.product(digits, repeat=n)]) return self.dfs(grams, '0' * (n - 1), n, k)
37b1fa
e66801
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct password is "345" and you enter in "012345": After typing 0, the most recent 3 digits is "0", which is incorrect. After typing 1, the most recent 3 digits is "01", which is incorrect. After typing 2, the most recent 3 digits is "012", which is incorrect. After typing 3, the most recent 3 digits is "123", which is incorrect. After typing 4, the most recent 3 digits is "234", which is incorrect. After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. Return any string of minimum length that will unlock the safe at some point of entering it.   Example 1: Input: n = 1, k = 2 Output: "10" Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe. Example 2: Input: n = 2, k = 2 Output: "01100" Explanation: For each possible password: - "00" is typed in starting from the 4th digit. - "01" is typed in starting from the 1st digit. - "10" is typed in starting from the 3rd digit. - "11" is typed in starting from the 2nd digit. Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.   Constraints: 1 <= n <= 4 1 <= k <= 10 1 <= kn <= 4096
class Solution(object): def crackSafe(self, n, k): """ :type n: int :type k: int :rtype: str """ alph = list(map(str, range(k))) if n == 1: return "".join(i for i in alph) if k == 1: return "0" * n a = [0] * k * n seq = [] def db(t, p): if t > n: if n % p == 0: seq.extend(a[1:p+1]) else: a[t] = a[t-p] db(t+1, p) for j in range(a[t-p]+1, k): a[t] = j db(t+1, t) db(1, 1) circ_ret = "".join(alph[i] for i in seq) return circ_ret + circ_ret[:n-1]
e465e5
35c9d2
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x to your score. Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on. Remove x from nums. Return the maximum score after performing m operations.   Example 1: Input: nums = [1,2,3], multipliers = [3,2,1] Output: 14 Explanation: An optimal solution is as follows: - Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score. - Choose from the end, [1,2], adding 2 * 2 = 4 to the score. - Choose from the end, [1], adding 1 * 1 = 1 to the score. The total score is 9 + 4 + 1 = 14. Example 2: Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6] Output: 102 Explanation: An optimal solution is as follows: - Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score. - Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score. - Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score. - Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score. - Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102.   Constraints: n == nums.length m == multipliers.length 1 <= m <= 300 m <= n <= 100000 -1000 <= nums[i], multipliers[i] <= 1000
from typing import * from functools import lru_cache import bisect from queue import Queue import math class Solution: def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: n, m = len(nums), len(multipliers) @lru_cache(None) def helper(i, j, idx): if idx == m: return 0 r1 = multipliers[idx] * nums[i] + helper(i+1, j, idx+1) r2 = multipliers[idx] * nums[j] + helper(i, j-1, idx + 1) return max(r1, r2) res = helper(0, n-1, 0) helper.cache_clear() return res
63e038
35c9d2
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x to your score. Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on. Remove x from nums. Return the maximum score after performing m operations.   Example 1: Input: nums = [1,2,3], multipliers = [3,2,1] Output: 14 Explanation: An optimal solution is as follows: - Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score. - Choose from the end, [1,2], adding 2 * 2 = 4 to the score. - Choose from the end, [1], adding 1 * 1 = 1 to the score. The total score is 9 + 4 + 1 = 14. Example 2: Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6] Output: 102 Explanation: An optimal solution is as follows: - Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score. - Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score. - Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score. - Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score. - Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102.   Constraints: n == nums.length m == multipliers.length 1 <= m <= 300 m <= n <= 100000 -1000 <= nums[i], multipliers[i] <= 1000
class Solution(object): def maximumScore(self, nums, multipliers): """ :type nums: List[int] :type multipliers: List[int] :rtype: int """ n = len(nums) r = [0] for k, mult in enumerate(multipliers, 1): rr = [-float('inf')] * (k+1) for i in xrange(k+1): j = k-i if i > 0: rr[i] = max(rr[i], r[i-1] + mult * nums[i-1]) if j > 0: rr[i] = max(rr[i], r[i] + mult * nums[n-j]) r = rr return max(r)
523571
071557
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/three". Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders) should all be marked: /a /a/x /a/x/y /a/z /b /b/x /b/x/y /b/z However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical. Note that "/a/x" and "/b/x" would still be considered identical even with the added folder. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.   Example 1: Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]] Output: [["d"],["d","a"]] Explanation: The file structure is as shown. Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty folder named "b". Example 2: Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]] Output: [["c"],["c","b"],["a"],["a","b"]] Explanation: The file structure is as shown. Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y". Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand. Example 3: Input: paths = [["a","b"],["c","d"],["c"],["a"]] Output: [["c"],["c","d"],["a"],["a","b"]] Explanation: All folders are unique in the file system. Note that the returned array can be in a different order as the order does not matter.   Constraints: 1 <= paths.length <= 2 * 10000 1 <= paths[i].length <= 500 1 <= paths[i][j].length <= 10 1 <= sum(paths[i][j].length) <= 2 * 100000 path[i][j] consists of lowercase English letters. No two paths lead to the same folder. For any folder not at the root level, its parent folder will also be in the input.
from collections import Counter class Trie: def __init__(self): self.ch = {} self.is_dir = False class Solution(object): def deleteDuplicateFolder(self, paths): """ :type paths: List[List[str]] :rtype: List[List[str]] """ r = Trie() for path in paths: u = r for part in path: if part not in u.ch: u.ch[part] = Trie() u = u.ch[part] u.is_dir = True c = Counter() def _sign(u): z = [] for part in sorted(u.ch): z.append((part, _sign(u.ch[part]))) u.sig = hash(tuple(z)) if z: c[u.sig] += 1 return u.sig _sign(r) ans = [] path = [] def _walk(u): if c[u.sig] >= 2: return if u.is_dir: ans.append(path[:]) for part in sorted(u.ch): path.append(part) _walk(u.ch[part]) path.pop() _walk(r) return ans
cfa919
071557
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/three". Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders) should all be marked: /a /a/x /a/x/y /a/z /b /b/x /b/x/y /b/z However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical. Note that "/a/x" and "/b/x" would still be considered identical even with the added folder. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.   Example 1: Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]] Output: [["d"],["d","a"]] Explanation: The file structure is as shown. Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty folder named "b". Example 2: Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]] Output: [["c"],["c","b"],["a"],["a","b"]] Explanation: The file structure is as shown. Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y". Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand. Example 3: Input: paths = [["a","b"],["c","d"],["c"],["a"]] Output: [["c"],["c","d"],["a"],["a","b"]] Explanation: All folders are unique in the file system. Note that the returned array can be in a different order as the order does not matter.   Constraints: 1 <= paths.length <= 2 * 10000 1 <= paths[i].length <= 500 1 <= paths[i][j].length <= 10 1 <= sum(paths[i][j].length) <= 2 * 100000 path[i][j] consists of lowercase English letters. No two paths lead to the same folder. For any folder not at the root level, its parent folder will also be in the input.
import collections class Solution: def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]: paths.sort() path_tree = {} # list of subfolders. For each subfolder, key is name, value is list of sub-folders for i in paths: cur = path_tree for j in i[:-1]: cur = cur[j] cur[i[-1]] = {} #print(path_tree) # ['LABEL'] becomes a hash of its children label_dir = collections.defaultdict(list) def label_tree(root): if not root: l = 'EMPTY' else: labels = [] for k, v in root.items(): labels.append((k, label_tree(v))) labels.sort() l = hash(tuple(labels)) label_dir[l].append(root) root['LABEL'] = l return l label_tree(path_tree) #print(path_tree) #print(label_dir) ans = [] def get_result(root, pwd=()): if len(label_dir[root['LABEL']]) > 1: #print('duplicate:', root) return #print('iter:', root) if pwd: ans.append(list(pwd)) for k, v in root.items(): if k == 'LABEL': continue get_result(v, pwd + (k,)) get_result(path_tree) return ans
8317a3
d1c842
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.   Example 1: Input: expression = "-1/2+1/2" Output: "0/1" Example 2: Input: expression = "-1/2+1/2+1/3" Output: "1/3" Example 3: Input: expression = "1/3-1/2" Output: "-1/6"   Constraints: The input string only contains '0' to '9', '/', '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1, 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
class Solution(object): def fractionAddition(self, expression): from itertools import groupby from fractions import Fraction sign = 1 fra = [0, 0] part = 0 ans = Fraction(0, 1) for k, v in groupby(expression, lambda x: x.isdigit()): w = "".join(v) if not k: if w == '+': sign = 1 elif w == '-': sign = -1 elif w == '/': pass else: fra[part] = int(w) part ^= 1 if part == 0: ans += Fraction(sign*fra[0], fra[1]) return "{}/{}".format(ans.numerator, ans.denominator)
d036ed
d1c842
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.   Example 1: Input: expression = "-1/2+1/2" Output: "0/1" Example 2: Input: expression = "-1/2+1/2+1/3" Output: "1/3" Example 3: Input: expression = "1/3-1/2" Output: "-1/6"   Constraints: The input string only contains '0' to '9', '/', '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1, 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
class Solution: def fractionAddition(self, expression): """ :type expression: str :rtype: str """ def gcd(a, b): if a < 0: return gcd(-a, b) if b < 0: return gcd(a, -b) if a < b: return gcd(b, a) if b == 0: return a else: return gcd(b, a%b) expression = expression.replace('+', ' +') expression = expression.replace('-', ' -') expression = expression.split() n = 0 d = 1 print(expression) for num in expression: x = num.split("/") a = int(x[0]) b = int(x[1]) n = n*b + d*a d = d*b g = gcd(n, d) n = n//g d = d//g return str(n) + "/" + str(d)
f6d2bb
950a39
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2.   Example 1: Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] Output: [2,11,7,15] Example 2: Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11] Output: [24,32,8,12]   Constraints: 1 <= nums1.length <= 100000 nums2.length == nums1.length 0 <= nums1[i], nums2[i] <= 10^9
class Solution: def advantageCount(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ n = len(A) A = list(sorted(A)) b = [(v, i) for i, v in enumerate(B)] b.sort() r = [-1] * n used = [False] * n i = 0 for v, j in b: while i < n and A[i] <= v: i += 1 if i < n: r[j] = A[i] used[i] = True i += 1 i = 0 for j in range(n): if used[j]: continue while r[i] >=0: i += 1 r[i] = A[j] i += 1 return r
b3dd0b
950a39
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2.   Example 1: Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] Output: [2,11,7,15] Example 2: Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11] Output: [24,32,8,12]   Constraints: 1 <= nums1.length <= 100000 nums2.length == nums1.length 0 <= nums1[i], nums2[i] <= 10^9
class Solution(object): def advantageCount(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ N = len(B) Bs = sorted([(B[i], i) for i in xrange(N)]) As = sorted([(A[i], i) for i in xrange(N)]) per = [None for i in xrange(N)] left = [] j = 0 for i in xrange(N): while j < N and As[j][0] <= Bs[i][0]: left.append(As[j][0]) j += 1 if j < N: per[Bs[i][1]] = As[j][0] j += 1 else: per[Bs[i][1]] = left.pop() return per
e0380d
4a4186
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= nums1 < nums2 <= right . nums1 and nums2 are both prime numbers. nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array ans = [nums1, nums2]. If there are multiple pairs satisfying these conditions, return the one with the minimum nums1 value or [-1, -1] if such numbers do not exist. A number greater than 1 is called prime if it is only divisible by 1 and itself.   Example 1: Input: left = 10, right = 19 Output: [11,13] Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19. The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19]. Since 11 is smaller than 17, we return the first pair. Example 2: Input: left = 4, right = 6 Output: [-1,-1] Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.   Constraints: 1 <= left <= right <= 1000000  
def euler_flag_prime(n): # 欧拉线性筛素数 # 说明:返回小于等于 n 的所有素数 flag = [False for _ in range(n + 1)] prime_numbers = [] for num in range(2, n + 1): if not flag[num]: prime_numbers.append(num) for prime in prime_numbers: if num * prime > n: break flag[num * prime] = True if num % prime == 0: # 这句是最有意思的地方 下面解释 break return prime_numbers class Solution: def closestPrimes(self, left: int, right: int) -> List[int]: primes = euler_flag_prime(right) primes = [x for x in primes if x>=left] ans = [] m = len(primes) for i in range(m-1): x,y = primes[i], primes[i+1] if not ans or y-x<ans[1]-ans[0]: ans = [x,y] return ans if ans else [-1, -1]
ce6336
4a4186
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= nums1 < nums2 <= right . nums1 and nums2 are both prime numbers. nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array ans = [nums1, nums2]. If there are multiple pairs satisfying these conditions, return the one with the minimum nums1 value or [-1, -1] if such numbers do not exist. A number greater than 1 is called prime if it is only divisible by 1 and itself.   Example 1: Input: left = 10, right = 19 Output: [11,13] Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19. The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19]. Since 11 is smaller than 17, we return the first pair. Example 2: Input: left = 4, right = 6 Output: [-1,-1] Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.   Constraints: 1 <= left <= right <= 1000000  
class Solution(object): def closestPrimes(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ p, i, a, b, d = [False, True] + [False] * (right - 1), 2, [], [-1, -1], float('inf') while i * i <= right: if not p[i]: j = i * i while j <= right: p[j], j = True, j + i i += 1 for i in range(left, right + 1): if not p[i]: a.append(i) for i in range(len(a) - 1): d, b = a[i + 1] - a[i] if a[i + 1] - a[i] < d else d, [a[i], a[i + 1]] if a[i + 1] - a[i] < d else b return b
63e8fa
e277bf
You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to: Trim each number in nums to its rightmost trimi digits. Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller. Reset each number in nums to its original length. Return an array answer of the same length as queries, where answer[i] is the answer to the ith query. Note: To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain. Strings in nums may contain leading zeros.   Example 1: Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]] Output: [2,2,1,0] Explanation: 1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2. 2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2. 3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73. 4. Trimmed to the last 2 digits, the smallest number is 2 at index 0. Note that the trimmed number "02" is evaluated as 2. Example 2: Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]] Output: [3,0] Explanation: 1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3. There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3. 2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.   Constraints: 1 <= nums.length <= 100 1 <= nums[i].length <= 100 nums[i] consists of only digits. All nums[i].length are equal. 1 <= queries.length <= 100 queries[i].length == 2 1 <= ki <= nums.length 1 <= trimi <= nums[i].length   Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: ans=[] for k,trim in queries: arr=[] for i,v in enumerate(nums): arr.append((v[-trim:],i)) arr.sort() ans.append(arr[k-1][1]) return ans
b78601
e277bf
You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to: Trim each number in nums to its rightmost trimi digits. Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller. Reset each number in nums to its original length. Return an array answer of the same length as queries, where answer[i] is the answer to the ith query. Note: To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain. Strings in nums may contain leading zeros.   Example 1: Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]] Output: [2,2,1,0] Explanation: 1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2. 2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2. 3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73. 4. Trimmed to the last 2 digits, the smallest number is 2 at index 0. Note that the trimmed number "02" is evaluated as 2. Example 2: Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]] Output: [3,0] Explanation: 1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3. There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3. 2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.   Constraints: 1 <= nums.length <= 100 1 <= nums[i].length <= 100 nums[i] consists of only digits. All nums[i].length are equal. 1 <= queries.length <= 100 queries[i].length == 2 1 <= ki <= nums.length 1 <= trimi <= nums[i].length   Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?
class Solution(object): def smallestTrimmedNumbers(self, nums, queries): """ :type nums: List[str] :type queries: List[List[int]] :rtype: List[int] """ r, i, n = [0] * len(queries), 0, [None] * len(nums) for q in queries: for j in range(0, len(nums)): n[j] = [j, nums[j][len(nums[j]) - q[1]:]] n.sort(key=lambda a: a[1]) r[i], i = n[q[0] - 1][0], i + 1 return r
7261f2
45b588
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.   Example 1: Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Example 2: Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 1 <= mat[i][j] <= 100
class Solution(object): def diagonalSort(self, A): R, C = len(A), len(A[0]) vals = collections.defaultdict(list) for r, row in enumerate(A): for c,v in enumerate(row): vals[r-c].append(v) for row in vals.values(): row.sort(reverse=True) for r, row in enumerate(A): for c,v in enumerate(row): A[r][c] = vals[r-c].pop() return A
db2dcc
45b588
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.   Example 1: Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Example 2: Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 1 <= mat[i][j] <= 100
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: m=len(mat) n=len(mat[0]) for i in range(n): ind=[(k,i+k) for k in range(100) if k in range(m) and i+k in range(n)] L=[mat[x[0]][x[1]] for x in ind] L.sort() for k in range(len(ind)): mat[ind[k][0]][ind[k][1]]=L[k] for i in range(m): ind=[(i+k,k) for k in range(100) if i+k in range(m) and k in range(n)] L=[mat[x[0]][x[1]] for x in ind] L.sort() for k in range(len(ind)): mat[ind[k][0]][ind[k][1]]=L[k] return mat
c8994b
623c36
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters.   Example 1: Input: s = "aaabcccd", k = 2 Output: 4 Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. Example 2: Input: s = "aabbaa", k = 2 Output: 2 Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. Example 3: Input: s = "aaaaaaaaaaa", k = 0 Output: 3 Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.   Constraints: 1 <= s.length <= 100 0 <= k <= s.length s contains only lowercase English letters.
from functools import lru_cache from itertools import groupby class Solution: def getLengthOfOptimalCompression(self, S, K): def rle(x): if x <= 1: return x return len(str(x)) + 1 N = len(S) if N == K: return 0 """ left = [1] * N for i in range(N - 1): if S[i] == S[i + 1]: left[i + 1] = left[i] + 1 right = [1] * N for i in reversed(range(N - 1)): if S[i] == S[i + 1]: right[i] = right[i + 1] + 1 R = [len(list(g)) for _, g in groupby(S)] prefix = [0] * N prev = 0 i = 0 for x in R: for j in range(1, 1 + x): prefix[i] = prev + rle(j) i += 1 prev += rle(x) suffix = [0] * N prev = 0 i = N - 1 for x in reversed(R): for j in range(1, 1 + x): suffix[i] = prev + rle(j) i -= 1 prev += rle(x) """ INF = int(1e9) @lru_cache(None) def dp(i, curlength, lastcur, eaten): if eaten > K: return INF if i == N: return 0 # Eat this character: ans = dp(i + 1, curlength, lastcur, eaten + 1) # Or add: if S[i] == lastcur: delta = rle(curlength + 1) - rle(curlength) cand = dp(i + 1, curlength + 1, lastcur, eaten) + delta if cand < ans: ans = cand else: cand = dp(i + 1, 1, S[i], eaten) + 1 if cand < ans: ans = cand return ans return dp(0, 0, '', 0)
26f915
623c36
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters.   Example 1: Input: s = "aaabcccd", k = 2 Output: 4 Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. Example 2: Input: s = "aabbaa", k = 2 Output: 2 Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. Example 3: Input: s = "aaaaaaaaaaa", k = 0 Output: 3 Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.   Constraints: 1 <= s.length <= 100 0 <= k <= s.length s contains only lowercase English letters.
class Solution(object): def getLengthOfOptimalCompression(self, s, k): """ :type s: str :type k: int :rtype: int """ n = len(s) cost = [0] * max(n+1, 5) cost[1] = 1 cost[2] = 2 t = 10 for i in xrange(3, n+1): cost[i] = cost[i-1] if i == t: t *= 10 cost[i] += 1 f = {(0, 0, None): 0} for d in s: ff = {} for (j, x, c), v in f.iteritems(): # not deleting if c == d: jj, xx, cc, vv = j, x+1, c, v else: jj, xx, cc, vv = j, 1, d, v+cost[x] if (jj, xx, cc) in ff: ff[(jj, xx, cc)] = min(ff[(jj, xx, cc)], vv) else: ff[(jj, xx, cc)] = vv # delete if j == k: continue if (j+1, x, c) in ff: ff[(j+1, x, c)] = min(ff[(j+1, x, c)], v) else: ff[(j+1, x, c)] = v f = ff return min(cost[x]+v for (_, x, _), v in f.iteritems())
90b9eb
2e4b72
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets.   Example 1: Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3] Output: 1 Explanation: There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet. Example 2: Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] Output: 4 Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).   Constraints: n == nums1.length == nums2.length 3 <= n <= 100000 0 <= nums1[i], nums2[i] <= n - 1 nums1 and nums2 are permutations of [0, 1, ..., n - 1].
class Solution: def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) self.n = n pos1 = [0 for i in range(n)] pos2 = [0 for i in range(n)] for i in range(n): x = nums1[i] pos1[x] = i x = nums2[i] pos2[x] = i pos = [] for i in range(n): pos.append([pos1[i], pos2[i]]) pos.sort() cnt = [[0 for i in range(n + 2)] for j in range(2)] def lb(x): return -x & x def ask(x, pid): s = 0 while x > 0: s += cnt[pid][x] x -= lb(x) return s def add(x, pid, w): while x <= self.n: cnt[pid][x] += w x += lb(x) ret = 0 for x, y in pos: tmp = ask(y + 1, 0) add(y + 1, 0, 1) ret += ask(y, 1) add(y + 1, 1, tmp) return ret
de019d
2e4b72
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets.   Example 1: Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3] Output: 1 Explanation: There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet. Example 2: Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] Output: 4 Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).   Constraints: n == nums1.length == nums2.length 3 <= n <= 100000 0 <= nums1[i], nums2[i] <= n - 1 nums1 and nums2 are permutations of [0, 1, ..., n - 1].
class Solution(object): def goodTriplets(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ d = {} for i, n in enumerate(nums1): d[n] = i nums = [] for n in nums2: nums.append(d[n]) left = [] res = 0 for i, n in enumerate(nums): if i == 0: left.append(n) else: m = bisect.bisect(left, n) bisect.insort(left, n) print(i, n, m) res += m * (len(nums) - n - i + m - 1) return res
ec8939
dfc0a7
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[i + 1]. Return the number of valid permutations perm. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: s = "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) Example 2: Input: s = "D" Output: 1   Constraints: n == s.length 1 <= n <= 200 s[i] is either 'I' or 'D'.
class Solution(object): def numPermsDISequence(self, S): """ :type S: str :rtype: int """ # dp[number of elements in the permutation][ranking of last element in the permutation] li1=[1] # previous list for i in range(len(S)): li2=[0]*(i+2) # next list if S[i]=='D': for j in range(i+1): for k in range(j+1): li2[k]+=li1[j] else: for j in range(i+1): for k in range(j+1,i+2): li2[k]+=li1[j] #print(li1,li2) li1=[x%1000000007 for x in li2] return sum(li1)%1000000007
b3734f
dfc0a7
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[i + 1]. Return the number of valid permutations perm. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: s = "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) Example 2: Input: s = "D" Output: 1   Constraints: n == s.length 1 <= n <= 200 s[i] is either 'I' or 'D'.
class Solution: def numPermsDISequence(self, S): """ :type S: str :rtype: int """ x = [1] mod = 10**9 + 7 for c in S: new_x = [0] if c == "I": for i in x: new_x.append((new_x[-1] + i)%mod) else: x.reverse() for i in x: new_x.append((new_x[-1] + i)%mod) new_x.reverse() x = new_x return sum(x)%mod
99b427
7cd4d0
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions: arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1. arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2. No integer is present in both arr1 and arr2. Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.   Example 1: Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3 Output: 4 Explanation: We can distribute the first 4 natural numbers into arr1 and arr2. arr1 = [1] and arr2 = [2,3,4]. We can see that both arrays satisfy all the conditions. Since the maximum value is 4, we return it. Example 2: Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1 Output: 3 Explanation: Here arr1 = [1,2], and arr2 = [3] satisfy all conditions. Since the maximum value is 3, we return it. Example 3: Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2 Output: 15 Explanation: Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6]. It can be shown that it is not possible to obtain a lower maximum satisfying all conditions.   Constraints: 2 <= divisor1, divisor2 <= 100000 1 <= uniqueCnt1, uniqueCnt2 < 10^9 2 <= uniqueCnt1 + uniqueCnt2 <= 10^9
class Solution: def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int: low, high = 1, 10**20 while low != high: mid = (low+high) >> 1 x = mid - mid // divisor1 y = mid - mid // divisor2 both = mid - mid // lcm(divisor1, divisor2) #print(mid, x, y, both, x >= uniqueCnt1 and y >= uniqueCnt2 and both >= uniqueCnt1+uniqueCnt2) if x >= uniqueCnt1 and y >= uniqueCnt2 and both >= uniqueCnt1+uniqueCnt2: high = mid else: low = mid+1 #print('#') return low
2d38c0
7cd4d0
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions: arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1. arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2. No integer is present in both arr1 and arr2. Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.   Example 1: Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3 Output: 4 Explanation: We can distribute the first 4 natural numbers into arr1 and arr2. arr1 = [1] and arr2 = [2,3,4]. We can see that both arrays satisfy all the conditions. Since the maximum value is 4, we return it. Example 2: Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1 Output: 3 Explanation: Here arr1 = [1,2], and arr2 = [3] satisfy all conditions. Since the maximum value is 3, we return it. Example 3: Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2 Output: 15 Explanation: Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6]. It can be shown that it is not possible to obtain a lower maximum satisfying all conditions.   Constraints: 2 <= divisor1, divisor2 <= 100000 1 <= uniqueCnt1, uniqueCnt2 < 10^9 2 <= uniqueCnt1 + uniqueCnt2 <= 10^9
class Solution(object): def minimizeSet(self, divisor1, divisor2, uniqueCnt1, uniqueCnt2): """ :type divisor1: int :type divisor2: int :type uniqueCnt1: int :type uniqueCnt2: int :rtype: int """ def gcd(a, b): while a: a, b = b%a, a return b g = gcd(divisor1, divisor2) cm = divisor1/g*divisor2 def check(v): c0 = v/cm c1 = v/divisor1 c2 = v/divisor2 if v-c1<uniqueCnt1: return False if v-c2<uniqueCnt2: return False v-=c0 c1-=c0 c2-=c0 n1=uniqueCnt1-c2 n2 =uniqueCnt2-c1 v-=(c1+c2) if n1<0: n1=0 if n2<0: n2=0 return v>=n1+n2 v=0 d = uniqueCnt1 + uniqueCnt2 while d: while True: nv=v+d if check(nv): break v=nv d>>=1 return v+1
869604
026443
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.   Example 1: Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102". Example 2: Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". Example 3: Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We cannot reach the target without getting stuck.   Constraints: 1 <= deadends.length <= 500 deadends[i].length == 4 target.length == 4 target will not be in the list deadends. target and deadends[i] consist of digits only.
class Solution: def openLock(self, deadends, target): # BFS for the target deadends = set(deadends) level = ['0000'] visited = set('0000') nLevel = 0 if '0000' in deadends or target in deadends: return -1 while level: nLevel += 1 newLevel = [] for curr in level: for i in range(4): for j in [(int(curr[i]) - 1) % 10, (int(curr[i]) + 1) % 10]: candidate = curr[:i] + str(j) + curr[i + 1:] if candidate not in visited and candidate not in deadends: newLevel.append(candidate) visited.add(candidate) if candidate == target: return nLevel level = newLevel return -1
806f4d
026443
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.   Example 1: Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102". Example 2: Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". Example 3: Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We cannot reach the target without getting stuck.   Constraints: 1 <= deadends.length <= 500 deadends[i].length == 4 target.length == 4 target will not be in the list deadends. target and deadends[i] consist of digits only.
class Solution(object): def openLock(self, deadends, target): """ :type deadends: List[str] :type target: str :rtype: int """ dic = {} dic['0000'] = True blocked = {} for de in deadends: blocked[de] = True if "0000" in blocked: return -1 q = [] q.append(('0000', 0)) while q: cur = q.pop(0) if cur[0] == target: return cur[1] for i in range(4): if cur[0][i] == '0': temp = cur[0][0:i] + '9' + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) temp = cur[0][0:i] + '1' + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) elif cur[0][i] == '9': temp = cur[0][0:i] + '0' + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) temp = cur[0][0:i] + '8' + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) else: temp = cur[0][0:i] + chr(ord(cur[0][i]) - 1) + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) temp = cur[0][0:i] + chr(ord(cur[0][i]) + 1) + cur[0][i + 1:4] if temp not in dic and temp not in blocked: dic[temp] = True q.append((temp, cur[1] + 1)) return -1
fc1d61
a8cc6e
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges that are connected to either node a or b. The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: a < b incident(a, b) > queries[j] Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query. Note that there can be multiple edges between the same two nodes.   Example 1: Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3] Output: [6,5] Explanation: The calculations for incident(a, b) are shown in the table above. The answers for each of the queries are as follows: - answers[0] = 6. All the pairs have an incident(a, b) value greater than 2. - answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3. Example 2: Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5] Output: [10,10,9,8,6]   Constraints: 2 <= n <= 2 * 10000 1 <= edges.length <= 100000 1 <= ui, vi <= n ui != vi 1 <= queries.length <= 20 0 <= queries[j] < edges.length
class Solution: def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: deg = [0] * n for x, y in edges: deg[x - 1] += 1 deg[y - 1] += 1 wtf = Counter() for x, y in edges: wtf[(min(x, y), max(x, y))] += 1 # print(wtf) s = sorted(deg) ans = list() for q in queries: tot = 0 for x in range(n): it = bisect.bisect_left(s, q - deg[x] + 1) tot += n - it if deg[x] + deg[x] > q: tot -= 1 # print(tot) for (x, y), z in wtf.items(): if deg[x - 1] + deg[y - 1] > q and deg[x - 1] + deg[y - 1] - z <= q: tot -= 2 ans.append(tot // 2) return ans
a6b4d6
a8cc6e
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges that are connected to either node a or b. The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: a < b incident(a, b) > queries[j] Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query. Note that there can be multiple edges between the same two nodes.   Example 1: Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3] Output: [6,5] Explanation: The calculations for incident(a, b) are shown in the table above. The answers for each of the queries are as follows: - answers[0] = 6. All the pairs have an incident(a, b) value greater than 2. - answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3. Example 2: Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5] Output: [10,10,9,8,6]   Constraints: 2 <= n <= 2 * 10000 1 <= edges.length <= 100000 1 <= ui, vi <= n ui != vi 1 <= queries.length <= 20 0 <= queries[j] < edges.length
from sortedcontainers import SortedList class Solution(object): def countPairs(self, n, edges, queries): """ :type n: int :type edges: List[List[int]] :type queries: List[int] :rtype: List[int] """ g=[[] for i in range(n)] cnt=[0 for i in range(n)] for i in edges: x,y=i[0]-1,i[1]-1 g[x].append(y) g[y].append(x) cnt[x]+=1 cnt[y]+=1 s=SortedList() for i in cnt: s.add(i) arr=[] for i in queries: val=0 for j in range(n): if 2*cnt[j]>i: val-=1 pos=s.bisect_left(i-cnt[j]+1) val+=n-pos d={} for k in g[j]: d[k]=d.get(k,0)+1 for k in d.keys(): x=cnt[k]+cnt[j] if x>i and x-d[k]<=i: val-=1 arr.append(val/2) return arr
95a0b7
c738eb
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.   Example 1: Input: matrix = [   [0,1,1,1],   [1,1,1,1],   [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7.   Constraints: 1 <= arr.length <= 300 1 <= arr[0].length <= 300 0 <= arr[i][j] <= 1
class Solution(object): def countSquares(self, A): R, C = len(A), len(A[0]) dp = [[0] * (C+1) for _ in xrange(R+1)] ans = 0 # largest square ending here for r, row in enumerate(A): for c, val in enumerate(row): if val: dp[r+1][c+1] = min(dp[r][c], dp[r][c+1], dp[r+1][c]) + 1 ans += dp[r+1][c+1] return ans
3dca89
c738eb
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.   Example 1: Input: matrix = [   [0,1,1,1],   [1,1,1,1],   [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7.   Constraints: 1 <= arr.length <= 300 1 <= arr[0].length <= 300 0 <= arr[i][j] <= 1
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m, n = len(matrix), len(matrix[0]) f = [[0] * n for _ in range(m)] ans = 0 for i in range(m): for j in range(n): if i == 0 or j == 0: f[i][j] = matrix[i][j] else: if matrix[i][j] == 0: f[i][j] = 0 else: f[i][j] = min(f[i - 1][j], f[i][j - 1]) if matrix[i - f[i][j]][j - f[i][j]] == 1: f[i][j] += 1 ans += f[i][j] return ans
e014e1
760e3d
Given the root of a binary tree, return the sum of values of its deepest leaves.   Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19   Constraints: The number of nodes in the tree is in the range [1, 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 deepestLeavesSum(self, root): stack = [(root, 0)] if root else [] ans = 0 ansd = 0 while stack: node, d = stack.pop() if d == ansd: ans += node.val elif d > ansd: ans = node.val ansd = d if node: if node.left: stack.append((node.left, d+1)) if node.right: stack.append((node.right, d+1)) return ans
0cb62c
760e3d
Given the root of a binary tree, return the sum of values of its deepest leaves.   Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19   Constraints: The number of nodes in the tree is in the range [1, 10000]. 1 <= Node.val <= 100
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: ret = 0 b = collections.deque([(0, root)]) deep = -1 while b: l, p = b.popleft() if l > deep: deep = l ret = 0 ret += p.val if p.left: b.append((l + 1, p.left)) if p.right: b.append((l + 1, p.right)) return ret
ae5ce4
87412d
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1. A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.   Example 1: Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]] Output: 2 Explanation: One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. Example 2: Input: board = [[0,1],[1,0]] Output: 0 Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard. Example 3: Input: board = [[1,0],[1,0]] Output: -1 Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.   Constraints: n == board.length n == board[i].length 2 <= n <= 30 board[i][j] is either 0 or 1.
class Solution(object): def movesToChessboard(self, board): def dist(set1, set2): x = [item for item in set1 if item in set2] return len(set1)-len(x) N = len(board) if N<=1: return 0 sm = sum(sum(row) for row in board) if N%2==0: if sm!=(N*N//2): return -1 else: m = N//2 if sm not in (2*m*m+2*m+1, 2*m*m+2*m): return -1 if sm== 2*m*(m+1): for i in range(N): for j in range(N): board[i][j] = 1-board[i][j] rows1, rows2, cols1, cols2 = set(), set(), set(), set() for T in range(N*N): r = T//N c = T%N if board[r][c]==1: rows1.add(r) cols1.add(c) break for i in range (N): if board[r][i]==1: cols1.add(i) if board[i][c]==1: rows1.add(i) for i in range (N): if i not in rows1: rows2.add(i) if i not in cols1: cols2.add(i) for i in range (N): for j in range(N): if i in rows1 and j in cols1 and board[i][j]==0: return -1 elif i in rows1 and j in cols2 and board[i][j]==1: return -1 elif i in rows2 and j in cols1 and board[i][j]==1: return -1 elif i in rows2 and j in cols2 and board[i][j]==0: return -1 if len(rows1)!=len(cols1): return -1 evens = set(range(0,N,2)) odds = set(range(1,N,2)) if N%2==0: A = dist(rows1, odds) B = dist(rows1, evens) C = dist(cols1, odds) D = dist(cols1, evens) return min(A,B)+min(C,D) else: if len(rows1)==m: return dist(rows1, odds)+dist(cols1, odds) else: return dist(rows1,evens)+dist(cols1, evens) """ :type board: List[List[int]] :rtype: int """
3314da
9473c1
Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr. int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.   Example 1: Input ["MajorityChecker", "query", "query", "query"] [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]] Output [null, 1, -1, 2] Explanation MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]); majorityChecker.query(0, 5, 4); // return 1 majorityChecker.query(0, 3, 3); // return -1 majorityChecker.query(2, 3, 2); // return 2   Constraints: 1 <= arr.length <= 2 * 10000 1 <= arr[i] <= 2 * 10000 0 <= left <= right < arr.length threshold <= right - left + 1 2 * threshold > right - left + 1 At most 10000 calls will be made to query.
class MajorityChecker: def __init__(self, arr: List[int]): self.loc_dict = collections.defaultdict(list) for i in range(len(arr)): self.loc_dict[arr[i]] += [i] self.cnt = [] for i in self.loc_dict: self.cnt += [[i,len(self.loc_dict[i])]] self.cnt = sorted(self.cnt,key = lambda l: l[1]) self.freq = [i[1] for i in self.cnt] def query(self, left: int, right: int, threshold: int) -> int: loc = bisect.bisect_left(self.freq,threshold,0,len(self.freq)) tot = right - left + 1 i = loc while i < len(self.freq): n = self.cnt[i][0] l = bisect.bisect_left(self.loc_dict[n],left,0,len(self.loc_dict[n])) r = bisect.bisect_right(self.loc_dict[n],right,0,len(self.loc_dict[n])) if r - l >= threshold: return n tot -= (l-r) if tot < threshold: return -1 i += 1 return -1 # Your MajorityChecker object will be instantiated and called as such: # obj = MajorityChecker(arr) # param_1 = obj.query(left,right,threshold)
0d0d55
9473c1
Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr. int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.   Example 1: Input ["MajorityChecker", "query", "query", "query"] [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]] Output [null, 1, -1, 2] Explanation MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]); majorityChecker.query(0, 5, 4); // return 1 majorityChecker.query(0, 3, 3); // return -1 majorityChecker.query(2, 3, 2); // return 2   Constraints: 1 <= arr.length <= 2 * 10000 1 <= arr[i] <= 2 * 10000 0 <= left <= right < arr.length threshold <= right - left + 1 2 * threshold > right - left + 1 At most 10000 calls will be made to query.
class MajorityChecker(object): def __init__(self, arr): """ :type arr: List[int] """ self.D = collections.defaultdict(list) for i, x in enumerate(arr): self.D[x].append(i) #print sorted((len(self.D[x]), x) for x in self.D) self.vals, self.keys = zip(*sorted((len(self.D[x]), x) for x in self.D)) #print self.keys, self.vals def query(self, left, right, threshold): """ :type left: int :type right: int :type threshold: int :rtype: int """ if threshold > self.vals[-1]: return -1 #print "call", left, right, threshold item_index = bisect.bisect_left(self.vals, threshold) for i in range(item_index, len(self.vals)): num = self.keys[i] i_left = bisect.bisect_left(self.D[num], left) i_right = bisect.bisect_right(self.D[num], right) #print num, i_left, i_right if i_right - i_left >= threshold: return num return -1 # Your MajorityChecker object will be instantiated and called as such: # obj = MajorityChecker(arr) # param_1 = obj.query(left,right,threshold)
32b2f1
2681d4
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.   Example 1: Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] Example 2: Input: preorder = [1,3] Output: [1,null,3]   Constraints: 1 <= preorder.length <= 100 1 <= preorder[i] <= 1000 All the values of preorder are unique.
# 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 bstFromPreorder(self, p): """ :type preorder: List[int] :rtype: TreeNode """ if not p: return None ret = TreeNode(p[0]) i = 1 while i < len(p) and p[i] < p[0]: i += 1 ret.left = self.bstFromPreorder(p[1 : i]) ret.right = self.bstFromPreorder(p[i : ]) return ret
d018a6
2681d4
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.   Example 1: Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] Example 2: Input: preorder = [1,3] Output: [1,null,3]   Constraints: 1 <= preorder.length <= 100 1 <= preorder[i] <= 1000 All the values of preorder are unique.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder) == 0: return None node = TreeNode(preorder[0]) next_split = 1 while next_split < len(preorder) and preorder[next_split] < preorder[0]: next_split += 1 node.left = self.bstFromPreorder(preorder[1:next_split]) node.right = self.bstFromPreorder(preorder[next_split:]) return node
ccf0f1
c3fea8
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false.   Example 1: Input: mass = 10, asteroids = [3,9,19,5,21] Output: true Explanation: One way to order the asteroids is [9,19,5,3,21]: - The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19 - The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38 - The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43 - The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46 - The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67 All asteroids are destroyed. Example 2: Input: mass = 5, asteroids = [4,9,23,4] Output: false Explanation: The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23. After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22. This is less than 23, so a collision would not destroy the last asteroid.   Constraints: 1 <= mass <= 100000 1 <= asteroids.length <= 100000 1 <= asteroids[i] <= 100000
class Solution: def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: asteroids.sort() for asteroid in asteroids: if mass < asteroid: return False mass += asteroid return True
c6f62b
c3fea8
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false.   Example 1: Input: mass = 10, asteroids = [3,9,19,5,21] Output: true Explanation: One way to order the asteroids is [9,19,5,3,21]: - The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19 - The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38 - The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43 - The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46 - The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67 All asteroids are destroyed. Example 2: Input: mass = 5, asteroids = [4,9,23,4] Output: false Explanation: The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23. After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22. This is less than 23, so a collision would not destroy the last asteroid.   Constraints: 1 <= mass <= 100000 1 <= asteroids.length <= 100000 1 <= asteroids[i] <= 100000
class Solution(object): def asteroidsDestroyed(self, mass, asteroids): """ :type mass: int :type asteroids: List[int] :rtype: bool """ for v in sorted(asteroids): if v > mass: return False mass += v return True
65c8c4
072fc1
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children.   Example 1: Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] Example 2: Input: n = 3 Output: [[0,0,0]]   Constraints: 1 <= n <= 20
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ if N%2==0: return [] if N==1: return [TreeNode(0)] s=[] for i in range(1,N-1,2): l,r=self.allPossibleFBT(i),self.allPossibleFBT(N-i-1) for ll in l: for rr in r: p=TreeNode(0) p.left=ll p.right=rr s.append(p) return s
f24e03
072fc1
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children.   Example 1: Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] Example 2: Input: n = 3 Output: [[0,0,0]]   Constraints: 1 <= n <= 20
# 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 allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ def maketree(lhs, rhs): t = TreeNode(0) t.left = lhs t.right = rhs return t if N % 2 == 0: return [] r = [[TreeNode(0)]] for _ in xrange(1, N, 2): r.append([maketree(lhs,rhs) for i in xrange(len(r)) for lhs in r[i] for rhs in r[-i-1]]) return r[-1]
717e2e
21a5ef
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the TreeAncestor class: TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array. int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.   Example 1: Input ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] Output [null, 1, 0, -1] Explanation TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor   Constraints: 1 <= k <= n <= 5 * 10000 parent.length == n parent[0] == -1 0 <= parent[i] < n for all 0 < i < n 0 <= node < n There will be at most 5 * 10000 queries.
class TreeAncestor(object): def __init__(self, n, parent): self.pars = [parent] self.n = n for k in xrange(17): row = [] for i in xrange(n): p = self.pars[-1][i] if p != -1: p = self.pars[-1][p] row.append(p) self.pars.append(row) def getKthAncestor(self, node, k): """ :type node: int :type k: int :rtype: int """ i = 0 while k: if node == -1: break if (k&1): node = self.pars[i][node] i += 1 k >>= 1 return node # Your TreeAncestor object will be instantiated and called as such: # obj = TreeAncestor(n, parent) # param_1 = obj.getKthAncestor(node,k)
ca0492
21a5ef
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the TreeAncestor class: TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array. int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.   Example 1: Input ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] Output [null, 1, 0, -1] Explanation TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor   Constraints: 1 <= k <= n <= 5 * 10000 parent.length == n parent[0] == -1 0 <= parent[i] < n for all 0 < i < n 0 <= node < n There will be at most 5 * 10000 queries.
class TreeAncestor: def __init__(self, n: int, par: List[int]): self.lca=[par] for _ in range(20): pvr=self.lca[-1] cur=[x for x in pvr] for i,x in enumerate(pvr): if x==-1: continue cur[i]=pvr[x] self.lca.append(cur) def getKthAncestor(self, node: int, k: int) -> int: ans=node i=0 while k: if k%2: ans=self.lca[i][ans] if ans==-1: return ans i+=1 k//=2 return ans # Your TreeAncestor object will be instantiated and called as such: # obj = TreeAncestor(n, parent) # param_1 = obj.getKthAncestor(node,k)
e2ae76
942f9d
LeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow. Rules and restrictions: You can only travel among n cities, represented by indexes from 0 to n - 1. Initially, you are in the city indexed 0 on Monday. The cities are connected by flights. The flights are represented as an n x n matrix (not necessarily symmetrical), called flights representing the airline status from the city i to the city j. If there is no flight from the city i to the city j, flights[i][j] == 0; Otherwise, flights[i][j] == 1. Also, flights[i][i] == 0 for all i. You totally have k weeks (each week has seven days) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time. For each city, you can only have restricted vacation days in different weeks, given an n x k matrix called days representing this relationship. For the value of days[i][j], it represents the maximum days you could take a vacation in the city i in the week j. You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days. If you fly from city A to city B and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city B in that week. We do not consider the impact of flight hours on the calculation of vacation days. Given the two matrices flights and days, return the maximum vacation days you could take during k weeks. Example 1: Input: flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]] Output: 12 Explanation: One of the best strategies is: 1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day. (Although you start at city 0, we could also fly to and start at other cities since it is Monday.) 2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days. 3rd week : stay at city 2, and play 3 days and work 4 days. Ans = 6 + 3 + 3 = 12. Example 2: Input: flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]] Output: 3 Explanation: Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks. For each week, you only have one day to play and six days to work. So the maximum number of vacation days is 3. Ans = 1 + 1 + 1 = 3. Example 3: Input: flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]] Output: 21 Explanation: One of the best strategies is: 1st week : stay at city 0, and play 7 days. 2nd week : fly from city 0 to city 1 on Monday, and play 7 days. 3rd week : fly from city 1 to city 2 on Monday, and play 7 days. Ans = 7 + 7 + 7 = 21 Constraints: n == flights.length n == flights[i].length n == days.length k == days[i].length 1 <= n, k <= 100 flights[i][j] is either 0 or 1. 0 <= days[i][j] <= 7
class Solution(object): def maxVacationDays(self, flights, days): """ :type flights: List[List[int]] :type days: List[List[int]] :rtype: int """ n, t = len(flights), len(days[0]) prev = [-float('inf')] * n prev[0] = 0 for i in range(t): cur = [-float('inf')] * n for x in range(n): for y in range(n): if (x == y or flights[x][y]) and cur[y] < prev[x] + days[y][i]: cur[y] = prev[x] + days[y][i] prev = cur res = -float('inf') for i in range(n): if prev[i] > res: res = prev[i] return res
95dc69
ba71bd
You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note that: val1 | val2 is bitwise OR of val1 and val2. val1 & val2 is bitwise AND of val1 and val2.   Example 1: Input: nums = [1,4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0,0,0) with effective value ((1 | 1) & 1) = 1 - (0,0,1) with effective value ((1 | 1) & 4) = 0 - (0,1,0) with effective value ((1 | 4) & 1) = 1 - (0,1,1) with effective value ((1 | 4) & 4) = 4 - (1,0,0) with effective value ((4 | 1) & 1) = 1 - (1,0,1) with effective value ((4 | 1) & 4) = 4 - (1,1,0) with effective value ((4 | 4) & 1) = 0 - (1,1,1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5. Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Explanation: The xor-beauty of the given array is 34.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution: def xorBeauty(self, a: List[int]) -> int: ans = 0 for i in a: ans ^= i return ans
8d113f
ba71bd
You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note that: val1 | val2 is bitwise OR of val1 and val2. val1 & val2 is bitwise AND of val1 and val2.   Example 1: Input: nums = [1,4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0,0,0) with effective value ((1 | 1) & 1) = 1 - (0,0,1) with effective value ((1 | 1) & 4) = 0 - (0,1,0) with effective value ((1 | 4) & 1) = 1 - (0,1,1) with effective value ((1 | 4) & 4) = 4 - (1,0,0) with effective value ((4 | 1) & 1) = 1 - (1,0,1) with effective value ((4 | 1) & 4) = 4 - (1,1,0) with effective value ((4 | 4) & 1) = 0 - (1,1,1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5. Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Explanation: The xor-beauty of the given array is 34.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution(object): def xorBeauty(self, nums): """ :type nums: List[int] :rtype: int """ n=len(nums) dp=[0 for i in range(32)] for i in nums: for j in range(32): if i&(1<<j): dp[j]+=1 print dp val=0 for i in nums: for j in range(32): if i&(1<<j): ct=n*n c=n-dp[j] ct-=c*c if(ct%2==1): val^=(1<<j) return val
406ea2
961c7d
Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high]. Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13. Note that the digit d = 1 occurs twice in the number 11. Example 2: Input: d = 3, low = 100, high = 250 Output: 35 Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243. Constraints: 0 <= d <= 9 1 <= low <= high <= 2 * 10^8
class Solution: def digitsCount(self, d: int, low: int, high: int) -> int: # Count from 1 to x def pre_count(x): if x == 0: return 0 str_x = str(x) N = len(str_x) ans = 0 # Numbers with less digits for i in range(1, N): cnt_num = 9 * 10 ** (i - 1) ans += cnt_num * (i - 1) // 10 + cnt_num // 9 * (d != 0) # print(ans) # Same length for i, c in enumerate(str_x): if d < int(c) and (i > 0 or d > 0): ans += 10 ** (N - i - 1) if d == int(c): if i == N - 1: ans += 1 else: ans += int(str_x[i + 1:]) + 1 ans += (int(c) - (i == 0)) * 10 ** (N - i - 1) * (N - i - 1) // 10 # print(i, c) return ans return pre_count(high) - pre_count(low - 1)
1ccd5a
961c7d
Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high]. Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13. Note that the digit d = 1 occurs twice in the number 11. Example 2: Input: d = 3, low = 100, high = 250 Output: 35 Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243. Constraints: 0 <= d <= 9 1 <= low <= high <= 2 * 10^8
class Solution(object): def digitsCount(self, d, low, high): """ :type d: int :type low: int :type high: int :rtype: int """ def count(N): if N == 0: return 0 A = map(int, str(N)) res = 0 n = len(A) for i, v in enumerate(A): if n - i - 2 >= 0: if i == 0 and d == 0: for j in xrange(i + 1, n - 1): res += 9 * (10**(n - j - 2)) * (n - j - 1) res += (v - 1) * (10**(n - i - 2)) * (n - i - 1) else: res += v * (10**(n - i - 2)) * (n - i - 1) if d < v: if d == 0 and i == 0: continue res += 10 ** (n - i - 1) if d == v: if i < n - 1: res += int("".join(map(str, A[i + 1:]))) + 1 else: res += 1 return res return count(high) - count(low - 1)
01a12e
4a2766
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).   Example 1: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) Example 2: Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: false Example 3: Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: true   Constraints: 1 <= sx, sy, tx, ty <= 10^9
class Solution(object): def reachingPoints(self, sx, sy, tx, ty): while tx!=ty and tx!=0 and ty!=0 and (tx>sx or ty>sy): if tx>ty: if ty!=sy: tx = tx%ty else: return (tx-sx)%ty == 0 else: if tx!=sx: ty = ty%tx else: return (ty-sy)%tx == 0 return (sx,sy)==(tx,ty) """ :type sx: int :type sy: int :type tx: int :type ty: int :rtype: bool """
effd1c
4a2766
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).   Example 1: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) Example 2: Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: false Example 3: Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: true   Constraints: 1 <= sx, sy, tx, ty <= 10^9
class Solution(object): def reachingPoints(self, sx, sy, tx, ty): """ :type sx: int :type sy: int :type tx: int :type ty: int :rtype: bool """ while (tx == sx and ty == sy) is False and (tx != 0 and ty != 0): if tx > ty: if (tx - sx) % ty == 0 and sy == ty and tx >= sx: return True else: tx = tx % ty else: if (ty - sy) % tx == 0 and sx == tx and ty >= sy: return True else: ty = ty % tx if tx != 0 and ty != 0: return True else: return False
584a33
c9d605
Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j]. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1,1,1], k = 10 Output: 1 Explanation: The only good subarray is the array nums itself. Example 2: Input: nums = [3,1,4,3,2,2,4], k = 2 Output: 4 Explanation: There are 4 different good subarrays: - [3,1,4,3,2,2] that has 2 pairs. - [3,1,4,3,2,2,4] that has 3 pairs. - [1,4,3,2,2,4] that has 2 pairs. - [4,3,2,2,4] that has 2 pairs.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 10^9
class Solution(object): def countGood(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ f, a, t, i = defaultdict(int), 0, 0, 0 for j in range(len(nums)): t, f[nums[j]] = t + f[nums[j]], f[nums[j]] + 1 while t >= k: f[nums[i]], t, i = f[nums[i]] - 1, t - f[nums[i]] + 1, i + 1 a += i return a
67503b
c9d605
Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j]. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1,1,1], k = 10 Output: 1 Explanation: The only good subarray is the array nums itself. Example 2: Input: nums = [3,1,4,3,2,2,4], k = 2 Output: 4 Explanation: There are 4 different good subarrays: - [3,1,4,3,2,2] that has 2 pairs. - [3,1,4,3,2,2,4] that has 3 pairs. - [1,4,3,2,2,4] that has 2 pairs. - [4,3,2,2,4] that has 2 pairs.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], k <= 10^9
from typing import List, Tuple, Optional from collections import defaultdict, Counter from sortedcontainers import SortedList MOD = int(1e9 + 7) INF = int(1e20) # 给你一个整数数组 nums 和一个整数 k ,请你返回 nums 中 好 子数组的数目。 # 一个子数组 arr 如果有 至少 k 对下标 (i, j) 满足 i < j 且 arr[i] == arr[j] ,那么称它是一个 好 子数组。 # 子数组 是原数组中一段连续 非空 的元素序列。 class Solution: def countGood(self, nums: List[int], k: int) -> int: res, left, n = 0, 0, len(nums) counter = Counter() curPair = 0 for right in range(n): counter[nums[right]] += 1 curPair += counter[nums[right]] - 1 while left <= right and curPair >= k: counter[nums[left]] -= 1 curPair -= counter[nums[left]] left += 1 res += left return res
5aec0c
3f8e8b
You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right. The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces. Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.   Example 1: Input: start = "_L__R__R_", target = "L______RR" Output: true Explanation: We can obtain the string target from start by doing the following moves: - Move the first piece one step to the left, start becomes equal to "L___R__R_". - Move the last piece one step to the right, start becomes equal to "L___R___R". - Move the second piece three steps to the right, start becomes equal to "L______RR". Since it is possible to get the string target from start, we return true. Example 2: Input: start = "R_L_", target = "__LR" Output: false Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_". After that, no pieces can move anymore, so it is impossible to obtain the string target from start. Example 3: Input: start = "_R", target = "R_" Output: false Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.   Constraints: n == start.length == target.length 1 <= n <= 100000 start and target consist of the characters 'L', 'R', and '_'.
class Solution: def canChange(self, s: str, t: str) -> bool: ls = [] rs = [] lt = [] rt = [] n = len(s) for i in range(n): if s[i] == 'L': ls.append(i) if s[i] == 'R': rs.append(i) if t[i] == 'L': lt.append(i) if t[i] == 'R': rt.append(i) if len(ls) != len(lt) or len(rs) != len(rt): return False if s.replace('_', '') != t.replace('_', ''): return False for i in range(len(ls)): if ls[i] < lt[i]: return False for i in range(len(rs)): if rs[i] > rt[i]: return False return True
dbb171
3f8e8b
You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right. The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces. Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.   Example 1: Input: start = "_L__R__R_", target = "L______RR" Output: true Explanation: We can obtain the string target from start by doing the following moves: - Move the first piece one step to the left, start becomes equal to "L___R__R_". - Move the last piece one step to the right, start becomes equal to "L___R___R". - Move the second piece three steps to the right, start becomes equal to "L______RR". Since it is possible to get the string target from start, we return true. Example 2: Input: start = "R_L_", target = "__LR" Output: false Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_". After that, no pieces can move anymore, so it is impossible to obtain the string target from start. Example 3: Input: start = "_R", target = "R_" Output: false Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.   Constraints: n == start.length == target.length 1 <= n <= 100000 start and target consist of the characters 'L', 'R', and '_'.
class Solution(object): def canChange(self, start, target): a = [] n = len(start) for i in range(n): if(start[i] == "L"): a.append(["L", i]) elif (start[i] == "R"): a.append(["R", i]) b = [] for i in range(n): if(target[i] == "L"): b.append(["L", i]) elif (target[i] == "R"): b.append(["R", i]) if(len(a) != len(b)): return False for i in range(len(a)): if(a[i][0] != b[i][0]): return False if(a[i][0] == "L"): if(a[i][1] < b[i][1]): return False elif a[i][0] == "R": if(a[i][1] > b[i][1]): return False return True
bc65a3
df8d5e
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string. A string is encrypted with the following process: For each character c in the string, we find the index i satisfying keys[i] == c in keys. Replace c with values[i] in the string. Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string "" is returned. A string is decrypted with the following process: For each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to. Replace s with keys[i] in the string. Implement the Encrypter class: Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary. String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string. int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.   Example 1: Input ["Encrypter", "encrypt", "decrypt"] [[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]] Output [null, "eizfeiam", 2] Explanation Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]); encrypter.encrypt("abcd"); // return "eizfeiam".   // 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am". encrypter.decrypt("eizfeiam"); // return 2. // "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'. // Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd". // 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.   Constraints: 1 <= keys.length == values.length <= 26 values[i].length == 2 1 <= dictionary.length <= 100 1 <= dictionary[i].length <= 100 All keys[i] and dictionary[i] are unique. 1 <= word1.length <= 2000 1 <= word2.length <= 200 All word1[i] appear in keys. word2.length is even. keys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters. At most 200 calls will be made to encrypt and decrypt in total.
class Encrypter: def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): self.d = defaultdict(int) self.m = {} for i, j in zip(keys, values): self.m[i] = j for i in dictionary: l = [] for x in i: l.append(self.m[x]) self.d[''.join(l)] += 1 def encrypt(self, word1: str) -> str: l = [] for x in word1: l.append(self.m[x]) return ''.join(l) def decrypt(self, word2: str) -> int: return self.d[word2] # Your Encrypter object will be instantiated and called as such: # obj = Encrypter(keys, values, dictionary) # param_1 = obj.encrypt(word1) # param_2 = obj.decrypt(word2)
cb9fd3
df8d5e
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string. A string is encrypted with the following process: For each character c in the string, we find the index i satisfying keys[i] == c in keys. Replace c with values[i] in the string. Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string "" is returned. A string is decrypted with the following process: For each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to. Replace s with keys[i] in the string. Implement the Encrypter class: Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary. String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string. int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.   Example 1: Input ["Encrypter", "encrypt", "decrypt"] [[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]] Output [null, "eizfeiam", 2] Explanation Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]); encrypter.encrypt("abcd"); // return "eizfeiam".   // 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am". encrypter.decrypt("eizfeiam"); // return 2. // "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'. // Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd". // 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.   Constraints: 1 <= keys.length == values.length <= 26 values[i].length == 2 1 <= dictionary.length <= 100 1 <= dictionary[i].length <= 100 All keys[i] and dictionary[i] are unique. 1 <= word1.length <= 2000 1 <= word2.length <= 200 All word1[i] appear in keys. word2.length is even. keys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters. At most 200 calls will be made to encrypt and decrypt in total.
class Encrypter(object): def __init__(self, keys, values, dictionary): """ :type keys: List[str] :type values: List[str] :type dictionary: List[str] """ self.keys = keys self.values = values self.key_index = dict() for i, k in enumerate(keys): self.key_index[k] = i self.cache = collections.defaultdict(int) for d in dictionary: self.cache[self.encrypt(d)]+=1 def encrypt(self, word1): """ :type word1: str :rtype: str """ ans = [] for w in word1: ans.append(self.values[self.key_index[w]]) return ''.join(ans) def decrypt(self, word2): """ :type word2: str :rtype: int """ return self.cache[word2] # Your Encrypter object will be instantiated and called as such: # obj = Encrypter(keys, values, dictionary) # param_1 = obj.encrypt(word1) # param_2 = obj.decrypt(word2)
9c18cb
607c62
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.   Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. Example 3: Input: n = 1000 Output: 262   Constraints: 1 <= n <= 10^9
class Solution(object): def numDupDigitsAtMostN(self, N): """ :type N: int :rtype: int """ def helper(n,used): if not used: if n == 0: return 0 if n == 1: return 9 res = 9 tmp = 9 while n > 1: res *= tmp n -= 1 tmp -= 1 return res else: N = 10-used res = 1 for _ in range(n): res *= N N -= 1 return res if N < 11: return 0 res = 0 l = len(str(N))-1 while l: res += helper(l,0) l -= 1 # print(res) lenN = len(str(N)) l = lenN-1 used = set() total = N flag = False while l: digit = N/(10**(l)) if digit in used: flag = True used.add(digit) # print(digit,l,used,res) if l == lenN-1: res += (digit-1)*helper(l,lenN-l) else: for i in range(digit): if i not in used: res += helper(l,lenN-l) if flag: break l -= 1 N %= (10**(l+1)) # print(res) used = set(str(total)[:-1]) if len(used) != len(str(total))-1: return total-res N = total/10*10 while N <= total: if str(N%10) not in used: res += 1 N += 1 return total-res
595c71
607c62
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.   Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. Example 3: Input: n = 1000 Output: 262   Constraints: 1 <= n <= 10^9
import functools class Solution: def numDupDigitsAtMostN(self, N: int) -> int: digits = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1] if N <= 10: return 0 str_N = list(map(int, str(N + 1))) n = len(str_N) ans = 0 # for i in range(1, n + 1): # ans += functools.reduce(operator.mul, digits[:i]) used = set() A = [[1] * 10 for i in range(10)] for i in range(1, 10): for j in range(i): A[i][j + 1] = A[i][j] * (i - j) for i in range(1, n): ans += 9 * A[9][i - 1] n = len(str_N) for i, d in enumerate(str_N): start = 0 if i > 0 else 1 for x in range(start, d): if x not in used: ans += A[9 - i][n - i - 1] if d in used: break used.add(d) return N - ans
f8bc0f
fd6b38
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.   Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= ai, bi <= n 1 <= t <= 50 1 <= target <= n
from functools import lru_cache from sys import setrecursionlimit as srl; srl(10**5) from fractions import Fraction class Solution(object): def frogPosition(self, n, edges, T, target): graph = [[] for _ in range(n)] for u, v in edges: u-=1;v-=1 graph[u].append(v) graph[v].append(u) # t seconds # start from 0 @lru_cache(None) def dfs(node, parent, steps): if steps == T: return +(node == target - 1) tot = ans = 0 for nei in graph[node]: if nei == parent: continue ans += dfs(nei, node, steps + 1) tot += 1 if tot == 0: return +(node == target - 1) return ans / float(tot) #return Fraction(ans, tot) ans= dfs(0, None, 0) return ans#float(ans)
e66c33
fd6b38
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.   Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= ai, bi <= n 1 <= t <= 50 1 <= target <= n
class Solution(object): def frogPosition(self, n, edges, t, target): """ :type n: int :type edges: List[List[int]] :type t: int :type target: int :rtype: float """ graph=collections.defaultdict(set) for x,y in edges: graph[x].add(y) graph[y].add(x) tree=collections.defaultdict(set) cur={1} seen={1} while cur: nxt=set() for idx in cur: for nidx in graph[idx]: if nidx not in seen: seen.add(nidx) nxt.add(nidx) tree[idx].add(nidx) cur=nxt def helper(st,ed,t): num=len(tree[st]) if t==0 or num==0: return st==ed f=1/float(num) ans=0 for nst in tree[st]: ans+=f*float(helper(nst,ed,t-1)) return ans return helper(1,target,t)
270d0a
d4b23e
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. All three parts have equal binary values. If it is not possible, return [-1, -1]. Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.   Example 1: Input: arr = [1,0,1,0,1] Output: [0,3] Example 2: Input: arr = [1,1,0,1,1] Output: [-1,-1] Example 3: Input: arr = [1,1,0,0,1] Output: [0,2]   Constraints: 3 <= arr.length <= 3 * 10000 arr[i] is 0 or 1
class Solution: def threeEqualParts(self, A): """ :type A: List[int] :rtype: List[int] """ a = A n = len(a) s = sum(a) if s % 3 != 0: return [-1, -1] if s == 0: return [0, 2] idx = [] for i in range(n): if a[i] == 1: idx.append(i) i = idx[0] j = idx[s // 3] k = idx[s // 3 + s // 3] while k < n: if not (a[i] == a[j] == a[k]): return [-1, -1] if i == idx[s // 3] or j == idx[s // 3 + s // 3]: return [-1, -1] i += 1 j += 1 k += 1 if i <= idx[s // 3 - 1] or j <= idx[s // 3 + s // 3 - 1]: return [-1, -1] return [i - 1, j]
1ccc69
d4b23e
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. All three parts have equal binary values. If it is not possible, return [-1, -1]. Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.   Example 1: Input: arr = [1,0,1,0,1] Output: [0,3] Example 2: Input: arr = [1,1,0,1,1] Output: [-1,-1] Example 3: Input: arr = [1,1,0,0,1] Output: [0,2]   Constraints: 3 <= arr.length <= 3 * 10000 arr[i] is 0 or 1
class Solution(object): def threeEqualParts(self, A): def strip_leading_zeroes(arr,start): for i in range(start,len(arr)): if arr[i]!=0: return i return len(arr) def compare_ind_eq(arr,start1,end1,start2,end2): if end1-start1!=end2-start2: return False for i,j in zip(range(start1,end1),range(start2,end2)): if arr[i]!=arr[j]: return False return True num_ones = sum(A) if num_ones==0: return [0,2] if num_ones%3!=0: return [-1,-1] segment_count = num_ones/3 ending_count = 0 for i in range(len(A)-1,-1,-1): if A[i]==0: ending_count+=1 else: break cur_count = 0 ind2 = None ind3 = None for j,i in enumerate(A): if i==1: cur_count+=1 if cur_count==segment_count: if ind2 is None: ind2 = j+1+ending_count else: ind3 = j+1+ending_count break cur_count = 0 orig_ind2 = ind2 orig_ind3 = ind3 ind1 = strip_leading_zeroes(A,0) ind2 = strip_leading_zeroes(A,ind2) ind3 = strip_leading_zeroes(A,ind3) if not compare_ind_eq(A,ind1,orig_ind2,ind2,orig_ind3): return [-1,-1] if not compare_ind_eq(A,ind2,orig_ind3,ind3,len(A)): return [-1,-1] return [orig_ind2-1,orig_ind3]
347715
f83561
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves. Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell. Return an integer denoting the maximum number of cells that can be visited.   Example 1: Input: mat = [[3,1],[3,4]] Output: 2 Explanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. Example 2: Input: mat = [[1,1],[1,1]] Output: 1 Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example. Example 3: Input: mat = [[3,1,6],[-9,5,7]] Output: 4 Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.   Constraints: m == mat.length  n == mat[i].length  1 <= m, n <= 105 1 <= m * n <= 105 -105 <= mat[i][j] <= 105
class Solution(object): def maxIncreasingCells(self, mat): """ :type mat: List[List[int]] :rtype: int """ v, q, r, a = [None] * (len(mat) * len(mat[0])), [deque([]) for _ in mat], [deque([]) for _ in mat[0]], 0 for i in range(len(mat)): for j in range(len(mat[0])): v[i * len(mat[0]) + j] = [mat[i][j], i, j] v.sort() for i in range(len(mat)): q[i].append([0, -float('inf')]) q[i].append([0, -float('inf')]) for j in range(len(mat[0])): r[j].append([0, -float('inf')]) r[j].append([0, -float('inf')]) for e, i, j in v: c, a = max(1 + q[i][-1][0] if q[i][-1][1] < e else 1 + q[i][0][0], 1 + r[j][-1][0] if r[j][-1][1] < e else 1 + r[j][0][0]), max(a, max(1 + q[i][-1][0] if q[i][-1][1] < e else 1 + q[i][0][0], 1 + r[j][-1][0] if r[j][-1][1] < e else 1 + r[j][0][0])) if q[i][-1][1] < e: q[i].append([c, e]) q[i].popleft() else: q[i][-1][0] = max(q[i][-1][0], c) if r[j][-1][1] < e: r[j].append([c, e]) r[j].popleft() else: r[j][-1][0] = max(r[j][-1][0], c) return a
1caa60
f83561
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves. Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell. Return an integer denoting the maximum number of cells that can be visited.   Example 1: Input: mat = [[3,1],[3,4]] Output: 2 Explanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. Example 2: Input: mat = [[1,1],[1,1]] Output: 1 Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example. Example 3: Input: mat = [[3,1,6],[-9,5,7]] Output: 4 Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.   Constraints: m == mat.length  n == mat[i].length  1 <= m, n <= 105 1 <= m * n <= 105 -105 <= mat[i][j] <= 105
class Solution: def maxIncreasingCells(self, mat: List[List[int]]) -> int: dic = defaultdict(list) m = len(mat) n = len(mat[0]) for row in range(m): for col in range(n): dic[mat[row][col]].append((row, col)) rows = [0] * m cols = [0] * n for _, arr in sorted(dic.items()): curr = [] for r, c in arr: curr.append(1 + max(rows[r], cols[c])) for i in range(len(arr)): r, c = arr[i] x = curr[i] rows[r] = max(rows[r], x) cols[c] = max(cols[c], x) return max(rows + cols)
c280f4
20f5ba
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.   Example 1: Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ] Example 2: Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] Output: [3.75000,0.40000,5.00000,0.20000] Example 3: Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]] Output: [0.50000,2.00000,-1.00000,-1.00000]   Constraints: 1 <= equations.length <= 20 equations[i].length == 2 1 <= Ai.length, Bi.length <= 5 values.length == equations.length 0.0 < values[i] <= 20.0 1 <= queries.length <= 20 queries[i].length == 2 1 <= Cj.length, Dj.length <= 5 Ai, Bi, Cj, Dj consist of lower case English letters and digits.
class Solution(object): def calcEquation(self, equations, values, query): """ :type equations: List[List[str]] :type values: List[float] :type query: List[List[str]] :rtype: List[float] """ g = {} for i, equa in enumerate(equations): a, b = equa if a not in g: g[a] = {a: 1.0} g[a][b] = values[i] if b not in g: g[b] = {b: 1.0} g[b][a] = 1.0 / values[i] def path(a0, b): if a0 not in g or b not in g: return -1.0 if b in g[a0]: return g[a0][b] q = [(a0, 1.0)] visited = set([a0]) for a, r in q: for c in g[a]: if c not in visited: visited.add(c) nr = r * g[a][c] if c == b: return nr g[a0][c] = nr q.append((c, nr)) return -1.0 result = [] for a, b in query: result.append(path(a, b)) return result
2e4965
18c82f
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: points = [[1,2],[2,1],[1,0],[0,1]] Output: 2.00000 Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2. Example 2: Input: points = [[0,1],[2,1],[1,1],[1,0],[2,0]] Output: 1.00000 Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1. Example 3: Input: points = [[0,3],[1,2],[3,1],[1,3],[2,1]] Output: 0 Explanation: There is no possible rectangle to form from these points.   Constraints: 1 <= points.length <= 50 points[i].length == 2 0 <= xi, yi <= 4 * 10000 All the given points are unique.
from math import sqrt class Solution: def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ output = flag = float('inf') ps = set((x, y) for x, y in points) N = len(points) for i in range(N): x1, y1 = points[i] for j in range(N): if i == j: continue x2, y2 = points[j] for k in range(j): if i == k: continue x3, y3 = points[k] if (x3-x1) * (x2-x1) + (y3-y1) * (y2-y1) != 0: continue x4 = x3 + (x2 - x1) y4 = y3 + (y2 - y1) if (x4, y4) in ps: area = sqrt((x2-x1) ** 2 + (y2-y1)**2) * sqrt((x3-x1)**2 + (y3-y1)**2) output = min(output, area) return output if output is not flag else 0
f53833
18c82f
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted.   Example 1: Input: points = [[1,2],[2,1],[1,0],[0,1]] Output: 2.00000 Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2. Example 2: Input: points = [[0,1],[2,1],[1,1],[1,0],[2,0]] Output: 1.00000 Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1. Example 3: Input: points = [[0,3],[1,2],[3,1],[1,3],[2,1]] Output: 0 Explanation: There is no possible rectangle to form from these points.   Constraints: 1 <= points.length <= 50 points[i].length == 2 0 <= xi, yi <= 4 * 10000 All the given points are unique.
from itertools import combinations class Solution(object): def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ d = {} r = float('inf') def d2(p1, p2): return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 def key(p1, p2): return (p1[0] + p2[0], p1[1] + p2[1], d2(p1, p2)) for p1, p2 in combinations(points, 2): d.setdefault(key(p1, p2), []).append([p1, p2]) for k, v in d.iteritems(): for (p1, p2), (p3, p4) in combinations(v, 2): r = min(r, d2(p1, p3) * d2(p2, p3)) return r ** 0.5 if r < float('inf') else 0
927a52
b9fc01
You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1|. There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road can take you from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. Return the minimum cost required to go from (startX, startY) to (targetX, targetY).   Example 1: Input: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]] Output: 5 Explanation: The optimal path from (1,1) to (4,5) is the following: - (1,1) -> (1,2). This move has a cost of |1 - 1| + |2 - 1| = 1. - (1,2) -> (3,3). This move uses the first special edge, the cost is 2. - (3,3) -> (3,4). This move has a cost of |3 - 3| + |4 - 3| = 1. - (3,4) -> (4,5). This move uses the second special edge, the cost is 1. So the total cost is 1 + 2 + 1 + 1 = 5. It can be shown that we cannot achieve a smaller total cost than 5. Example 2: Input: start = [3,2], target = [5,7], specialRoads = [[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] Output: 7 Explanation: It is optimal to not use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.   Constraints: start.length == target.length == 2 1 <= startX <= targetX <= 10^5 1 <= startY <= targetY <= 10^5 1 <= specialRoads.length <= 200 specialRoads[i].length == 5 startX <= x1i, x2i <= targetX startY <= y1i, y2i <= targetY 1 <= costi <= 10^5
class Solution(object): def minimumCost(self, start, target, specialRoads): """ :type start: List[int] :type target: List[int] :type specialRoads: List[List[int]] :rtype: int """ v, d, q = defaultdict(list), defaultdict(int), set() for x in specialRoads: v[(x[0], x[1])].append([x[2], x[3], min(x[4], abs(x[0] - x[2]) + abs(x[1] - x[3]))]) v[(start[0], start[1])].append([x[0], x[1], abs(x[0] - start[0]) + abs(x[1] - start[1])]) v[(x[2], x[3])].append([target[0], target[1], abs(x[2] - target[0]) + abs(x[3] - target[1])]) for y in specialRoads: v[(x[2], x[3])].append([y[0], y[1], abs(x[2] - y[0]) + abs(x[3] - y[1])]) v[(start[0], start[1])].append([target[0], target[1], abs(target[0] - start[0]) + abs(target[1] - start[1])]) q.add((0, start[0], start[1])) while q: c = list(q)[0] q.remove(c) for x in v[c[1], c[2]]: if not (x[0], x[1]) in d or d[(c[1], c[2])] + x[2] < d[(x[0], x[1])]: if (d[(x[0], x[1])], x[0], x[1]) in q: q.remove((d[(x[0], x[1])], x[0], x[1])) d[(x[0], x[1])] = d[(c[1], c[2])] + x[2] q.add((d[(x[0], x[1])], x[0], x[1])) return d[(target[0], target[1])]
d425d2
b9fc01
You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1|. There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road can take you from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. Return the minimum cost required to go from (startX, startY) to (targetX, targetY).   Example 1: Input: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]] Output: 5 Explanation: The optimal path from (1,1) to (4,5) is the following: - (1,1) -> (1,2). This move has a cost of |1 - 1| + |2 - 1| = 1. - (1,2) -> (3,3). This move uses the first special edge, the cost is 2. - (3,3) -> (3,4). This move has a cost of |3 - 3| + |4 - 3| = 1. - (3,4) -> (4,5). This move uses the second special edge, the cost is 1. So the total cost is 1 + 2 + 1 + 1 = 5. It can be shown that we cannot achieve a smaller total cost than 5. Example 2: Input: start = [3,2], target = [5,7], specialRoads = [[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] Output: 7 Explanation: It is optimal to not use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.   Constraints: start.length == target.length == 2 1 <= startX <= targetX <= 10^5 1 <= startY <= targetY <= 10^5 1 <= specialRoads.length <= 200 specialRoads[i].length == 5 startX <= x1i, x2i <= targetX startY <= y1i, y2i <= targetY 1 <= costi <= 10^5
class Solution: def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int: start = tuple(start) target = tuple(target) sx, sy = start tx, ty = target m = len(specialRoads) adj = defaultdict(list) for x1, y1, x2, y2, c in specialRoads: adj[(x1, y1)].append((x2, y2, c)) adj[(sx, sy)].append((x1, y1, abs(sx-x1) + abs(sy-y1))) adj[(x2, y2)].append((tx, ty, abs(tx-x2) + abs(ty-y2))) for i in range(m): for j in range(i + 1, m): i_x1, i_y1, i_x2, i_y2, i_c = specialRoads[i] j_x1, j_y1, j_x2, j_y2, j_c = specialRoads[j] adj[(i_x2, i_y2)].append((j_x1, j_y1, abs(i_x2-j_x1) + abs(i_y2-j_y1))) adj[(j_x2, j_y2)].append((i_x1, i_y1, abs(j_x2-i_x1) + abs(j_y2-i_y1))) adj[(sx, sy)].append((tx, ty, abs(sx-tx) + abs(sy-ty))) dist = {start:0} heap = [(0, start)] while len(heap) > 0: d, u = heapq.heappop(heap) if dist[u] != d: continue if u == target: return d for vx, vy, c in adj[u]: v = (vx, vy) if d + c < dist.get(v, float("inf")): dist[v] = d + c heapq.heappush(heap, (dist[v], v)) return -1
c108f4
0f37a6
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor. Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j. Return true if it is possible to traverse between all such pairs of indices, or false otherwise.   Example 1: Input: nums = [2,3,6] Output: true Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1. Example 2: Input: nums = [3,9,5] Output: false Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. Example 3: Input: nums = [4,3,12,8] Output: true Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
class PrimeTable: def __init__(self, n:int) -> None: self.n = n self.primes = [] self.max_div = list(range(n+1)) self.max_div[1] = 1 self.phi = list(range(n+1)) for i in range(2, n + 1): if self.max_div[i] == i: self.primes.append(i) for j in range(i, n+1, i): self.max_div[j] = i self.phi[j] = self.phi[j] // i * (i-1) def is_prime(self, x:int): if x < 2: return False if x <= self.n: return self.max_div[x] == x for p in self.primes: if p * p > x: break if x % i == 0: return False return True def prime_factorization(self, x:int): if x > self.n: for p in self.primes: if p * p > x: break if x <= self.n: break if x % p == 0: cnt = 0 while x % p == 0: cnt += 1; x //= p yield p, cnt while (1 < x and x <= self.n): p, cnt = self.max_div[x], 0 while x % p == 0: cnt += 1; x //= p yield p, cnt if x >= self.n and x > 1: yield x, 1 def get_factors(self, x:int): factors = [1] for p, b in self.prime_factorization(x): n = len(factors) for j in range(1, b+1): for d in factors[:n]: factors.append(d * (p ** j)) return factors class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, a): a = self.parent[a] acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] return a def merge(self, a, b): pa, pb = self.find(a), self.find(b) if pa == pb: return False self.parent[pb] = pa return True pt = PrimeTable(10 ** 5 + 1) class Solution: def canTraverseAllPairs(self, nums: List[int]) -> bool: primes = set() for num in nums: for p, c in pt.prime_factorization(num): primes.add(p) primes = sorted(primes) union = UnionFind(len(nums) + len(primes)) for i, v in enumerate(nums): for p, c in pt.prime_factorization(v): j = len(nums) + bisect.bisect_left(primes, p) union.merge(i, j) return len({union.find(i) for i in range(len(nums))}) == 1
af53c3
0f37a6
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor. Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j. Return true if it is possible to traverse between all such pairs of indices, or false otherwise.   Example 1: Input: nums = [2,3,6] Output: true Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1. Example 2: Input: nums = [3,9,5] Output: false Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. Example 3: Input: nums = [4,3,12,8] Output: true Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.   Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
pre=[i for i in range(10**5+1)] for i in range(2,10**5+1): if pre[i]!=i: continue for j in range(2*i,10**5+1,i): pre[j]=i class Solution(object): def canTraverseAllPairs(self, nums): """ :type nums: List[int] :rtype: bool """ n=len(nums) p=[i for i in range(n)] r=[0 for i in range(n)] def find(x): while p[x]!=x: x=p[x] return x def union(x,y): px=find(x) py=find(y) if px==py: return if r[px]<r[py]: p[px]=py elif r[px]>r[py]: p[py]=px else: p[py]=px r[px]+=1 d={} for i in range(n): x=nums[i] while x!=1: val=pre[x] y=d.get(val,-1) if y!=-1: union(i,y) d[val]=i x/=val d={} for i in range(n): px=find(i) d[px]=1 if len(d)==1: return 1 return 0
58376b
19ce97
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest.   Example 1: Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total. Example 2: Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total. Example 3: Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits.   Constraints: 1 <= fruits.length <= 100000 fruits[i].length == 2 0 <= startPos, positioni <= 2 * 100000 positioni-1 < positioni for any i > 0 (0-indexed) 1 <= amounti <= 10000 0 <= k <= 2 * 100000
class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: MAX = 2 * 100000 + 5 cumsum = [0] * (MAX) orig = [0] * (MAX) for pos, cnt in fruits: orig[pos] = cnt for i in range(MAX): if i == 0: cumsum[i]=orig[i] else: cumsum[i]=cumsum[i-1]+orig[i] ans = 0 for lft in range(0, k + 1): rt = k - lft if lft <= rt and lft <= startPos: ans = max(ans, cumsum[min(startPos-lft+rt,MAX-1)]-(cumsum[startPos-lft-1] if startPos-lft>0 else 0)) if lft <= rt and startPos + lft < MAX: ans = max(ans, cumsum[startPos+lft] - (cumsum[max(startPos+lft-rt,0)-1] if max(startPos+lft-rt,0) > 0 else 0)) return ans
f00c78
19ce97
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest.   Example 1: Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total. Example 2: Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total. Example 3: Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits.   Constraints: 1 <= fruits.length <= 100000 fruits[i].length == 2 0 <= startPos, positioni <= 2 * 100000 positioni-1 < positioni for any i > 0 (0-indexed) 1 <= amounti <= 10000 0 <= k <= 2 * 100000
class Solution(object): def maxTotalFruits(self, fruits, startPos, k): """ :type fruits: List[List[int]] :type startPos: int :type k: int :rtype: int """ x = startPos d = {i:v for i,v in fruits} s = sum(v for i,v in fruits if x-k <= i <= x) r = s j = x for lhs in xrange(k, -1, -1): rhs = max(k-2*lhs, (k-lhs)//2) while j < x+rhs: j += 1 s += d.get(j, 0) r = max(r, s) s -= d.get(x-lhs, 0) return r
5e9ac5
7fc14b
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. (An integer could be positive or negative.) A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr. An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2. A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2. For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names. Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.   Example 1: Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))" Output: 14 Explanation: In the expression (add x y), when checking for the value of the variable x, we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate. Since x = 3 is found first, the value of x is 3. Example 2: Input: expression = "(let x 3 x 2 x)" Output: 2 Explanation: Assignment in let statements is processed sequentially. Example 3: Input: expression = "(let x 1 y 2 x (add x y) (add x y))" Output: 5 Explanation: The first (add x y) evaluates as 3, and is assigned to x. The second (add x y) evaluates as 3+2 = 5.   Constraints: 1 <= expression.length <= 2000 There are no leading or trailing spaces in expression. All tokens are separated by a single space in expression. The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer. The expression is guaranteed to be legal and evaluate to an integer.
class Solution(object): def getNext(self, expression): levelCount = 0 for i in range(len(expression)): if expression[i] == " ": if levelCount == 0: newExp = expression[i+1:] this = expression[:i] return newExp.lstrip(" ").rstrip(" "), self.solve(this) elif expression[i] == "(": levelCount += 1 elif expression[i] == ")": levelCount -= 1 if levelCount == 0: newExp = expression[i+1:] this = expression[:i+1] return newExp.lstrip(" ").rstrip(" "), self.solve(this) return "", self.solve(expression) def getNextRaw(self, expression): levelCount = 0 for i in range(len(expression)): if expression[i] == " ": if levelCount == 0: newExp = expression[i+1:] this = expression[:i] return newExp.lstrip(" "), this elif expression[i] == "(": levelCount += 1 elif expression[i] == ")": levelCount -= 1 if levelCount == 0: newExp = expression[i+1:] this = expression[:i+1] return newExp.lstrip(" "), this return "", expression def solve(self, expression): # print expression # print self.d if type(expression) == int: return expression expression = expression.lstrip(' ').rstrip(' ') if expression[0] != "(": if ord("a")<=ord(expression[0])<=ord("z"): return self.d[expression] return int(expression) head = expression[1] expression = expression[expression.find(" ")+1:-1] if head == "a": expression, get1 = self.getNext(expression) expression, get2 = self.getNext(expression) return get1 + get2 elif head == "m": expression, get1 = self.getNext(expression) expression, get2 = self.getNext(expression) return get1 * get2 elif head == "l": # print expression cpdict = dict(self.d) while expression: expression, get1 = self.getNextRaw(expression) if expression: expression, get2 = self.getNext(expression) self.d[get1] = get2 else: rt = self.solve(get1) self.d = dict(cpdict) return rt else: print "unexpected" return 0 def evaluate(self, expression): """ :type expression: str :rtype: int """ self.d = {} return self.solve(expression)
d84717
7fc14b
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. (An integer could be positive or negative.) A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr. An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2. A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2. For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names. Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.   Example 1: Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))" Output: 14 Explanation: In the expression (add x y), when checking for the value of the variable x, we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate. Since x = 3 is found first, the value of x is 3. Example 2: Input: expression = "(let x 3 x 2 x)" Output: 2 Explanation: Assignment in let statements is processed sequentially. Example 3: Input: expression = "(let x 1 y 2 x (add x y) (add x y))" Output: 5 Explanation: The first (add x y) evaluates as 3, and is assigned to x. The second (add x y) evaluates as 3+2 = 5.   Constraints: 1 <= expression.length <= 2000 There are no leading or trailing spaces in expression. All tokens are separated by a single space in expression. The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer. The expression is guaranteed to be legal and evaluate to an integer.
from collections import ChainMap def find(s, i): while s[i] == " ": i += 1 start = i if s[i]=="(": i += 1 left = 1 while i < len(s): if s[i] == "(": left += 1 elif s[i] == ")": left -= 1 if left == 0: return s[start:i+1], i+1 i += 1 else: while i < len(s) and s[i] != " ": i += 1 return s[start:i], i class Solution: def evaluate(self, expression): """ :type expression: str :rtype: int """ m = ChainMap() def calc(exp, m): exp = exp.strip() if exp.startswith("(let"): exp = exp[1:-1] pos = 3 map = {} m.maps.insert(0, map) arr = [] while pos < len(exp)-1: s, pos = find(exp, pos) arr.append(s) for i in range(0, len(arr), 2): if i == len(arr) - 1: ret = calc(arr[i], m) else: map[arr[i]] = calc(arr[i+1], m) m.maps.pop(0) return ret elif exp.startswith("(add"): exp = exp[1:-1] exp1, pos = find(exp, 4) exp2, pos = find(exp, pos) x = calc(exp1, m) y = calc(exp2, m) return x+y elif exp.startswith("(mult"): exp = exp[1:-1] exp1, pos = find(exp, 5) exp2, pos = find(exp, pos) x = calc(exp1, m) y = calc(exp2, m) return x*y elif exp[0].islower(): return m[exp] else: return int(exp) return calc(expression, m)
683df0
59d165
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11". After concatenating them, we have "11011", which corresponds to the decimal value 27. Example 3: Input: n = 12 Output: 505379714 Explanation: The concatenation results in "1101110010111011110001001101010111100". The decimal value of that is 118505380540. After modulo 10^9 + 7, the result is 505379714.   Constraints: 1 <= n <= 100000
class Solution: def concatenatedBinary(self, n: int) -> int: ans = 0 mod = 10**9 + 7 for i in range(1, n + 1): b = bin(i)[2:] digs = len(b) ans *= (2**digs) ans += i ans %= mod return ans
d46f92
59d165
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11". After concatenating them, we have "11011", which corresponds to the decimal value 27. Example 3: Input: n = 12 Output: 505379714 Explanation: The concatenation results in "1101110010111011110001001101010111100". The decimal value of that is 118505380540. After modulo 10^9 + 7, the result is 505379714.   Constraints: 1 <= n <= 100000
class Solution(object): def concatenatedBinary(self, n): res = 1 mod = 10**9+7 for t in xrange(2, n+1): res = (res*(1<<len(bin(t))-2)+t) % mod return res """ :type n: int :rtype: int """
391b9b
63b617
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Constraints: 2 <= x <= 100 1 <= target <= 2 * 10^8
from functools import lru_cache class Solution: def leastOpsExpressTarget(self, x, target): """ :type x: int :type target: int :rtype: int """ @lru_cache(None) def dfs(target, power): if power == 0: return 2 * abs(target) y = x ** power d = target // y return min(dfs(target - y * d, power-1) + power * abs(d), dfs(target - y * (d+1), power-1) + power * abs(d+1)) power = 0 c = target while c: c //= x power += 1 print(target, power) return dfs(target, power) - 1
9cddde
63b617
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Constraints: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution(object): def leastOpsExpressTarget(self, x, target): """ :type x: int :type target: int :rtype: int """ c = [(2,1)] d, v = 1, x while v < target * x: c.append((d, v)) v *= x d += 1 cache = {} def best(t, p): if t == 0: return 0 if p == 0: return c[0][0] * t if (t,p) in cache: return cache[(t,p)] d, v = c[p] q, r = t//v, t%v cache[(t,p)] = min(d*q+best(r,p-1), d*(q+1)+best(v-r,p-1)) return cache[(t,p)] return best(target, len(c)-1) - 1
a4a926
53c0ca
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag. If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j]. The score after distributing the marbles is the sum of the costs of all the k bags. Return the difference between the maximum and minimum scores among marble distributions.   Example 1: Input: weights = [1,3,5,1], k = 2 Output: 4 Explanation: The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. Example 2: Input: weights = [1, 3], k = 2 Output: 0 Explanation: The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0.   Constraints: 1 <= k <= weights.length <= 100000 1 <= weights[i] <= 10^9
class Solution(object): def putMarbles(self, weights, k): """ :type weights: List[int] :type k: int :rtype: int """ v, d = [0] * (len(weights) - 1), 0 for i in range(len(weights) - 1): v[i] = weights[i] + weights[i + 1] v.sort() for i in range(k - 1): d += v[len(weights) - 2 - i] - v[i] return d
cd7f01
53c0ca
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag. If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j]. The score after distributing the marbles is the sum of the costs of all the k bags. Return the difference between the maximum and minimum scores among marble distributions.   Example 1: Input: weights = [1,3,5,1], k = 2 Output: 4 Explanation: The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. Example 2: Input: weights = [1, 3], k = 2 Output: 0 Explanation: The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0.   Constraints: 1 <= k <= weights.length <= 100000 1 <= weights[i] <= 10^9
class Solution: def putMarbles(self, weights: List[int], k: int) -> int: tmp = [] for i in range(len(weights)-1): tmp.append(weights[i] + weights[i+1]) return - sum(nsmallest(k-1, tmp)) + sum(nlargest(k-1, tmp))
0b2b01
e4baca
Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.   Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1   Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters.
class Solution(object): def numberOfSubstrings(self, s): """ :type s: str :rtype: int """ a, b, c = -1, -1, -1 ans = 0 for i, x in enumerate(s): if x == 'a': a = i elif x == 'b': b = i elif x == 'c': c = i if min(a, b, c) >= 0: ans += min(a, b, c) + 1 return ans
d1b1b3
e4baca
Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.   Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1   Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters.
class Solution: def numberOfSubstrings(self, s: str) -> int: prev = {'a': -1, 'b': -1, 'c': -1} res = 0 for pos, let in enumerate(s): prev[let] = pos start = min(prev.values()) if start >= 0: res += (start + 1) return res
e8caeb
4d931a
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] Output: 1 Example 3: Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length < n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
class Solution: def dfs(self, x): if self.mark[x] == True: return 0 ret = 1 self.mark[x] = True for neigh in self.edge[x]: ret += self.dfs(neigh) return ret def minMalwareSpread(self, graph, initial): """ :type graph: List[List[int]] :type initial: List[int] :rtype: int """ self.n = len(graph) self.g = graph self.edge = [[] for _ in range(self.n)] for i in range(self.n): for j in range(self.n): if graph[i][j] == 1 and i != j: self.edge[i].append(j) # print(self.edge) iset = set(initial) best = None ans = None for remove in sorted(initial): self.mark = [False for _ in range(self.n)] self.mark[remove] = True cur = 0 for i in range(self.n): if i in iset and self.mark[i] == False: cur += self.dfs(i) if best is None or best > cur: best = cur ans = remove return ans
ec0f74
4d931a
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] Output: 1 Example 3: Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length < n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
class Solution(object): def minMalwareSpread(self, graph, initial): def fill_with_removed_node(edges,removed,sources): filled = [False]*len(edges) q = sources new_q = [] for source in sources: if source!=removed: new_q.append(source) filled[source] = True q = new_q while len(q)>0: node = q.pop() filled[node] = True for neighbor in edges[node]: if not filled[neighbor] and neighbor!=removed: q.append(neighbor) return sum(filled) initial = sorted(initial) comps = [] labels = [-1]*len(graph) cur = 0 edges = [[] for i in range(len(graph))] for i in range(len(graph)): for j in range(i): if graph[i][j]==1: edges[i].append(j) edges[j].append(i) for i in range(len(graph)): if labels[i]==-1: q = [i] while len(q)>0: node = q.pop() labels[node] = cur for neighbor in edges[node]: if labels[neighbor]==-1: q.append(neighbor) cur+=1 label_lookup = [[] for i in range(cur)] for i,label in enumerate(labels): label_lookup[label].append(i) labels_of_initial = [[] for i in range(cur)] for node in initial: labels_of_initial[labels[node]].append(node) best = initial[0] best_size = 0 for i,label in enumerate(labels_of_initial): if len(label)==1: n = len(label_lookup[i]) if n>best_size or (n==best_size and label[0]<best): best_size = n best = label[0] elif len(label)>1: for candidate in label: n = len(label_lookup[i])-fill_with_removed_node(edges,candidate,label) if n>best_size or (n==best_size and candidate<best): best_size = n best = candidate return best
cfa4b6
a687d9
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei. The system should support the following functions: Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned. Rent: Rents an unrented copy of a given movie from a given shop. Drop: Drops off a previously rented copy of a given movie at a given shop. Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned. Implement the MovieRentingSystem class: MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries. List<Integer> search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above. void rent(int shop, int movie) Rents the given movie from the given shop. void drop(int shop, int movie) Drops off a previously rented movie at the given shop. List<List<Integer>> report() Returns a list of cheapest rented movies as described above. Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.   Example 1: Input ["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"] [[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]] Output [null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]] Explanation MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]); movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number. movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3]. movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1]. movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1. movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2]. movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.   Constraints: 1 <= n <= 3 * 100000 1 <= entries.length <= 100000 0 <= shopi < n 1 <= moviei, pricei <= 10000 Each shop carries at most one copy of a movie moviei. At most 100000 calls in total will be made to search, rent, drop and report.
from sortedcontainers import SortedList class MovieRentingSystem: def __init__(self, n: int, entries: List[List[int]]): self.movies = collections.defaultdict(SortedList) self.rented = SortedList() self.map = {} for s, m, p in entries: self.movies[m].add((p, s)) self.map[(s, m)] = p def search(self, movie: int) -> List[int]: return [s for p, s in self.movies[movie][:5]] def rent(self, shop: int, movie: int) -> None: price = self.map[(shop, movie)] self.movies[movie].remove((price, shop)) self.rented.add((price, shop, movie)) def drop(self, shop: int, movie: int) -> None: price = self.map[(shop, movie)] self.movies[movie].add((price, shop)) self.rented.remove((price, shop, movie)) def report(self) -> List[List[int]]: return [[s, m] for p, s, m in self.rented[:5]] # Your MovieRentingSystem object will be instantiated and called as such: # obj = MovieRentingSystem(n, entries) # param_1 = obj.search(movie) # obj.rent(shop,movie) # obj.drop(shop,movie) # param_4 = obj.report()
5e1c35
a687d9
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei. The system should support the following functions: Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned. Rent: Rents an unrented copy of a given movie from a given shop. Drop: Drops off a previously rented copy of a given movie at a given shop. Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned. Implement the MovieRentingSystem class: MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries. List<Integer> search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above. void rent(int shop, int movie) Rents the given movie from the given shop. void drop(int shop, int movie) Drops off a previously rented movie at the given shop. List<List<Integer>> report() Returns a list of cheapest rented movies as described above. Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.   Example 1: Input ["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"] [[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]] Output [null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]] Explanation MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]); movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number. movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3]. movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1]. movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1. movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2]. movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.   Constraints: 1 <= n <= 3 * 100000 1 <= entries.length <= 100000 0 <= shopi < n 1 <= moviei, pricei <= 10000 Each shop carries at most one copy of a movie moviei. At most 100000 calls in total will be made to search, rent, drop and report.
from sortedcontainers import SortedDict class MovieRentingSystem(object): def __init__(self, n, entries): """ :type n: int :type entries: List[List[int]] """ self.Query = dict() self.Rent = SortedDict() self.Movie = dict() for shop, movie, price in entries: if not movie in self.Movie: self.Movie[movie] = SortedDict() self.Query[(movie, shop)] = price self.Movie[movie][(price, shop)] = 1 def search(self, movie): """ :type movie: int :rtype: List[int] """ if not movie in self.Movie: return [] t = self.Movie[movie].keys()[:5] ans = [] for p, s in t: ans.append(s) return ans def rent(self, shop, movie): """ :type shop: int :type movie: int :rtype: None """ price = self.Query[(movie, shop)] self.Movie[movie].pop((price, shop)) self.Rent[(price, shop, movie)] = 1 def drop(self, shop, movie): """ :type shop: int :type movie: int :rtype: None """ price = self.Query[(movie, shop)] self.Rent.pop((price, shop, movie)) self.Movie[movie][(price, shop)] = 1 def report(self): """ :rtype: List[List[int]] """ t = self.Rent.keys()[:5] ans = [] for p, s, m in t: ans.append([s, m]) return ans # Your MovieRentingSystem object will be instantiated and called as such: # obj = MovieRentingSystem(n, entries) # param_1 = obj.search(movie) # obj.rent(shop,movie) # obj.drop(shop,movie) # param_4 = obj.report()
d15921
96db85
You are given an array nums consisting of positive integers. We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0. Return the length of the longest nice subarray. A subarray is a contiguous part of an array. Note that subarrays of length 1 are always considered nice.   Example 1: Input: nums = [1,3,8,48,10] Output: 3 Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions: - 3 AND 8 = 0. - 3 AND 48 = 0. - 8 AND 48 = 0. It can be proven that no longer nice subarray can be obtained, so we return 3. Example 2: Input: nums = [3,1,5,11,13] Output: 1 Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: n = len(nums) l, r = 0, 0 def check(l, r): for i in range(l, r): for j in range(i + 1, r + 1): if nums[i] & nums[j] != 0: return False return True res = 0 while r < n: if check(l, r): res = max(r - l + 1, res) r += 1 else: l += 1 return res
526ec3
96db85
You are given an array nums consisting of positive integers. We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0. Return the length of the longest nice subarray. A subarray is a contiguous part of an array. Note that subarrays of length 1 are always considered nice.   Example 1: Input: nums = [1,3,8,48,10] Output: 3 Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions: - 3 AND 8 = 0. - 3 AND 48 = 0. - 8 AND 48 = 0. It can be proven that no longer nice subarray can be obtained, so we return 3. Example 2: Input: nums = [3,1,5,11,13] Output: 1 Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution(object): def longestNiceSubarray(self, nums): """ :type nums: List[int] :rtype: int """ cs = [0]*32 r = 1 n = len(nums) i, j = 0, 0 while i<n: v = nums[i] for k in range(31): if v&(1<<k): cs[k]+=1 while True: fit=True for k in range(31): if cs[k]>1: fit=False break if fit: break v = nums[j] j+=1 for k in range(31): if v&(1<<k): cs[k]-=1 r = max(r, i-j+1) i+=1 return r
488a91
d6bfbe
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.   Example 1: Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. Example 2: Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4]   Constraints: 1 <= nums.length <= 10000 -10^9 <= nums[i] <= 10^9
class Solution(object): def nextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ n2=len(nums) if n2==0: return [] n = [(nums[a] if a < n2 else nums[a-n2]) for a in range(n2*2)] g = [n[-1]] ans=[] for a in range(len(n)-2, -1, -1): while len(g) >0: if g[-1] > n[a]: break g.pop() if a < n2: if len(g) == 0: ans.append(-1) else: ans.append(g[-1]) g.append(n[a]) ans.reverse() return ans