sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
02e050
9f0604
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin.   Example 1: Input: root = [3,0,0] Output: 2 Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. Example 2: Input: root = [0,3,0] Output: 3 Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.   Constraints: The number of nodes in the tree is n. 1 <= n <= 100 0 <= Node.val <= n The sum of all Node.val is n.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ def surplus(node): nonlocal moves if node is None: return 0 l, r = surplus(node.left), surplus(node.right) moves += abs(l) + abs(r) return node.val + l + r - 1 moves = 0 surplus(root) return moves
d0eb6f
9f0604
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin.   Example 1: Input: root = [3,0,0] Output: 2 Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. Example 2: Input: root = [0,3,0] Output: 3 Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.   Constraints: The number of nodes in the tree is n. 1 <= n <= 100 0 <= Node.val <= n The sum of all Node.val is n.
# 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 distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ r = [0] def f(node): if not node: return 0, 0 s0, c0 = f(node.left) s1, c1 = f(node.right) s = s0 + s1 + node.val c = c0 + c1 + 1 r[0] += abs(s-c) return s, c f(root) return r[0]
330159
465331
You are given an even number of people numPeople that stand around a circle and each person shakes hands with someone else so that there are numPeople / 2 handshakes total. Return the number of ways these handshakes could occur such that none of the handshakes cross. Since the answer could be very large, return it modulo 10^9 + 7. Example 1: Input: numPeople = 4 Output: 2 Explanation: There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)]. Example 2: Input: numPeople = 6 Output: 5 Constraints: 2 <= numPeople <= 1000 numPeople is even.
class Solution(object): def numberOfWays(self, N): N //= 2 MOD = 10 ** 9 + 7 def binom(n, k): r = 1 for i in xrange(1, k+1): r *= n-i+1 r /= i return r ans = binom(2*N, N) ans *= pow(N+1, MOD-2, MOD) ans %= MOD return ans
03b2a1
465331
You are given an even number of people numPeople that stand around a circle and each person shakes hands with someone else so that there are numPeople / 2 handshakes total. Return the number of ways these handshakes could occur such that none of the handshakes cross. Since the answer could be very large, return it modulo 10^9 + 7. Example 1: Input: numPeople = 4 Output: 2 Explanation: There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)]. Example 2: Input: numPeople = 6 Output: 5 Constraints: 2 <= numPeople <= 1000 numPeople is even.
class Solution: def numberOfWays(self, num_people: int) -> int: n = num_people // 2 dp = [1] * (n + 1) MOD = 10 ** 9 + 7 for i in range(1, n + 1): dp[i] = sum(dp[j] * dp[i - j - 1] for j in range(i)) % MOD return dp[n]
12d406
1d6e0c
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.   Example 1: Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. Example 2: Input: clips = [[0,1],[1,2]], time = 5 Output: -1 Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. Example 3: Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 Output: 3 Explanation: We can take clips [0,4], [4,7], and [6,9].   Constraints: 1 <= clips.length <= 100 0 <= starti <= endi <= 100 1 <= time <= 100
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: s, e = 0, T clips.sort() ans = 0 i, n = 0, len(clips) while s < e: cand_e = -1 while i < n and clips[i][0] <= s: if clips[i][1] > cand_e: cand_e = clips[i][1] i += 1 if cand_e == -1: return -1 ans += 1 s = cand_e return ans
eb0feb
1d6e0c
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.   Example 1: Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. Example 2: Input: clips = [[0,1],[1,2]], time = 5 Output: -1 Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. Example 3: Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 Output: 3 Explanation: We can take clips [0,4], [4,7], and [6,9].   Constraints: 1 <= clips.length <= 100 0 <= starti <= endi <= 100 1 <= time <= 100
class Solution(object): def videoStitching(self, cl, T): n = len(cl) cl = sorted(cl, key = lambda x: (x[0], -x[1])) if cl[0][0] > 0: return -1 cur = 0 pre = 0 cnt = 0 for itv in cl: if pre < itv[0]: pre = cur cnt += 1 cur = max(cur, itv[1]) if cur >= T: cnt += 1 break if cur >= T: return cnt return -1 """ :type clips: List[List[int]] :type T: int :rtype: int """
25b534
7cc0bc
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.   Example 1: Input: time = [1,2,3], totalTrips = 5 Output: 3 Explanation: - At time t = 1, the number of trips completed by each bus are [1,0,0]. The total number of trips completed is 1 + 0 + 0 = 1. - At time t = 2, the number of trips completed by each bus are [2,1,0]. The total number of trips completed is 2 + 1 + 0 = 3. - At time t = 3, the number of trips completed by each bus are [3,1,1]. The total number of trips completed is 3 + 1 + 1 = 5. So the minimum time needed for all buses to complete at least 5 trips is 3. Example 2: Input: time = [2], totalTrips = 1 Output: 2 Explanation: There is only one bus, and it will complete its first trip at t = 2. So the minimum time needed to complete 1 trip is 2.   Constraints: 1 <= time.length <= 100000 1 <= time[i], totalTrips <= 10^7
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: lo = 0 hi = 10 ** 18 ans = 10 ** 18 def cost(L): trips = 0 for x in time: trips += L // x return trips while lo <= hi: mid = (lo + hi) // 2 if cost(mid) >= totalTrips: hi = mid - 1 ans = mid else: lo = mid + 1 return ans
c5918f
7cc0bc
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.   Example 1: Input: time = [1,2,3], totalTrips = 5 Output: 3 Explanation: - At time t = 1, the number of trips completed by each bus are [1,0,0]. The total number of trips completed is 1 + 0 + 0 = 1. - At time t = 2, the number of trips completed by each bus are [2,1,0]. The total number of trips completed is 2 + 1 + 0 = 3. - At time t = 3, the number of trips completed by each bus are [3,1,1]. The total number of trips completed is 3 + 1 + 1 = 5. So the minimum time needed for all buses to complete at least 5 trips is 3. Example 2: Input: time = [2], totalTrips = 1 Output: 2 Explanation: There is only one bus, and it will complete its first trip at t = 2. So the minimum time needed to complete 1 trip is 2.   Constraints: 1 <= time.length <= 100000 1 <= time[i], totalTrips <= 10^7
class Solution(object): def minimumTime(self, time, totalTrips): """ :type time: List[int] :type totalTrips: int :rtype: int """ def _check(z): return sum(z//t for t in time) >= totalTrips x, y = 0, 1 while not _check(y): x, y = y, 2*y while x + 1 < y: z = (x + y) // 2 if _check(z): y = z else: x = z return y
57bf63
74e2c1
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1. Return the maximum number of points you can earn by applying the above operation some number of times.   Example 1: Input: nums = [3,4,2] Output: 6 Explanation: You can perform the following operations: - Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2]. - Delete 2 to earn 2 points. nums = []. You earn a total of 6 points. Example 2: Input: nums = [2,2,3,3,3,4] Output: 9 Explanation: You can perform the following operations: - Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3]. - Delete a 3 again to earn 3 points. nums = [3]. - Delete a 3 once more to earn 3 points. nums = []. You earn a total of 9 points.   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] <= 10000
class Solution(object): def deleteAndEarn(self, nums): """ :type nums: List[int] :rtype: int """ e = [0 for i in range(10001)] for n in nums: e[n] += n dp0 = [0 for i in range(10001)] dp1 = [0 for i in range(10001)] for i in range(1, 10001): dp0[i] = max(dp0[i - 1], dp1[i - 1]) dp1[i] = dp0[i - 1] + e[i] return max(dp0[-1], dp1[-1])
1e7536
74e2c1
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1. Return the maximum number of points you can earn by applying the above operation some number of times.   Example 1: Input: nums = [3,4,2] Output: 6 Explanation: You can perform the following operations: - Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2]. - Delete 2 to earn 2 points. nums = []. You earn a total of 6 points. Example 2: Input: nums = [2,2,3,3,3,4] Output: 9 Explanation: You can perform the following operations: - Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3]. - Delete a 3 again to earn 3 points. nums = [3]. - Delete a 3 once more to earn 3 points. nums = []. You earn a total of 9 points.   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] <= 10000
class Solution: def deleteAndEarn(self, nums): """ :type nums: List[int] :rtype: int """ counts = [0] * 10001 # counts[i] stores the count of i for num in nums: counts[num] += 1 # dp[i] stores the maximum sum towards now you can get by picking i max_with_me = [0] * 10001 max_until_me = [0] * 10001 for i in range(10001): max_with_me[i] = i * counts[i] if i >= 2: max_with_me[i] += max_until_me[i - 2] max_until_me[i] = max_with_me[i] if i >= 1: max_until_me[i] = max(max_until_me[i], max_until_me[i - 1]) return max_until_me[10000]
497d26
4f3d59
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7. Two paths are considered different if they do not have exactly the same sequence of visited cells.   Example 1: Input: grid = [[1,1],[3,4]] Output: 8 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [1], [3], [4]. - Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4]. - Paths with length 3: [1 -> 3 -> 4]. The total number of paths is 4 + 3 + 1 = 8. Example 2: Input: grid = [[1],[2]] Output: 3 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [2]. - Paths with length 2: [1 -> 2]. The total number of paths is 2 + 1 = 3.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 1 <= grid[i][j] <= 100000
class Solution: def countPaths(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) @cache def ans(x, y): res = 1 for i, j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if 0 <= i < n and 0 <= j < m and grid[x][y] < grid[i][j]: res += ans(i, j) return res%1000000007 a = 0 for i in range(n): for j in range(m): a = (a+ans(i, j))%1000000007 return a
0afaac
4f3d59
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7. Two paths are considered different if they do not have exactly the same sequence of visited cells.   Example 1: Input: grid = [[1,1],[3,4]] Output: 8 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [1], [3], [4]. - Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4]. - Paths with length 3: [1 -> 3 -> 4]. The total number of paths is 4 + 3 + 1 = 8. Example 2: Input: grid = [[1],[2]] Output: 3 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [2]. - Paths with length 2: [1 -> 2]. The total number of paths is 2 + 1 = 3.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 1 <= grid[i][j] <= 100000
class Solution(object): def countPaths(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, r = [[None] * len(grid[0]) for _ in grid], 0 def g(s, c): if m[s][c] == None: m[s][c] = 1 for d, e in [[0, 1], [1, 0], [0, -1], [-1, 0]]: m[s][c] = (m[s][c] + (g(s + d, c + e) if s + d < len(grid) and c + e < len(grid[0]) and s + d >= 0 and c + e >= 0 and grid[s + d][c + e] > grid[s][c] else 0)) % 1000000007 return m[s][c] for i in range(0, len(grid)): for j in range(0, len(grid[0])): r = (r + g(i, j)) % 1000000007; return r
7ef50d
9a9539
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-negative. If the cell is a water cell, its height must be 0. Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.   Example 1: Input: isWater = [[0,1],[0,0]] Output: [[1,0],[2,1]] Explanation: The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. Example 2: Input: isWater = [[0,0,1],[1,0,0],[0,0,0]] Output: [[1,1,0],[0,1,1],[1,2,2]] Explanation: A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.   Constraints: m == isWater.length n == isWater[i].length 1 <= m, n <= 1000 isWater[i][j] is 0 or 1. There is at least one water cell.
class Solution: def highestPeak(self, g: List[List[int]]) -> List[List[int]]: q = collections.deque() m = len(g) n = len(g[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if g[i][j] == 1: q.append((i, j)) while q: x, y = q.popleft() for nx, ny in [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)]: if 0 <= nx < m and 0 <= ny < n and g[nx][ny] == 0: ans[nx][ny] = ans[x][y] + 1 g[nx][ny] = 1 q.append((nx, ny)) return ans
917b8a
9a9539
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-negative. If the cell is a water cell, its height must be 0. Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.   Example 1: Input: isWater = [[0,1],[0,0]] Output: [[1,0],[2,1]] Explanation: The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. Example 2: Input: isWater = [[0,0,1],[1,0,0],[0,0,0]] Output: [[1,1,0],[0,1,1],[1,2,2]] Explanation: A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.   Constraints: m == isWater.length n == isWater[i].length 1 <= m, n <= 1000 isWater[i][j] is 0 or 1. There is at least one water cell.
class Solution(object): def highestPeak(self, A): queue = [] R,C= len(A),len(A[0]) for r,row in enumerate(A): for c, v in enumerate(row): if v == 1: queue.append((r,c, 0)) seen = {(r,c) for r,c,v in queue} for r,c,v in queue: A[r][c] = v for nr, nc in ((r-1,c), (r,c-1), (r+1,c),(r,c+1)): if 0<=nr<R and 0<=nc<C and (nr,nc) not in seen: seen.add((nr, nc)) queue.append((nr, nc, v + 1)) return A
dafb3c
930836
You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.   Example 1: Input: head = [2,1,5] Output: [5,5,0] Example 2: Input: head = [2,7,4,3,5] Output: [7,0,5,5,0]   Constraints: The number of nodes in the list is n. 1 <= n <= 10000 1 <= Node.val <= 10^9
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def nextLargerNodes(self, head: ListNode) -> List[int]: ans = [] stack = [] i = 0 vals = [] while head: num = head.val vals.append(num) while stack and num > vals[stack[-1]]: ans[stack.pop()] = num stack.append(i) ans.append(0) i += 1 head = head.next return ans
01c221
930836
You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.   Example 1: Input: head = [2,1,5] Output: [5,5,0] Example 2: Input: head = [2,7,4,3,5] Output: [7,0,5,5,0]   Constraints: The number of nodes in the list is n. 1 <= n <= 10000 1 <= Node.val <= 10^9
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def nextLargerNodes(self, head): """ :type head: ListNode :rtype: List[int] """ nums = [] while head: nums.append(head.val) head = head.next n = len(nums) m = [float('inf')] for i in range(n - 1, -1, -1): while m[-1] <= nums[i]: m.pop() m.append(nums[i]) nums[i] = 0 if m[-2] == float('inf') else m[-2] return nums
5b5fc6
5cd4d3
Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones.  Alice and Bob take turns, with Alice starting first.  Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.   Example 1: Input: piles = [2,7,9,4,4] Output: 10 Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. Example 2: Input: piles = [1,2,3,4,5,100] Output: 10000   Constraints: 1 <= piles.length <= 100 1 <= piles[i] <= 10000
class Solution: def stoneGameII(self, piles: List[int]) -> int: memo = {} n = len(piles) S = [0]*(n+1) for i in range(n): S[i+1] = S[i] + piles[i] def dfs(i, m): key = (i, m) if key in memo: return memo[key] if i == n: return 0 r = 0 res = 0 for x in range(1, 2*m+1): if i+x > n: break r += piles[i+x-1] res = max(res, r + (S[n] - S[i+x]) - dfs(i+x, max(m, x))) #print(i, m, x, r, (S[n] - S[i+x]), dfs(i+x, max(m, x))) memo[key] = res return res r = dfs(0, 1) #print(memo) return r
cc19ee
5cd4d3
Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones.  Alice and Bob take turns, with Alice starting first.  Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.   Example 1: Input: piles = [2,7,9,4,4] Output: 10 Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. Example 2: Input: piles = [1,2,3,4,5,100] Output: 10000   Constraints: 1 <= piles.length <= 100 1 <= piles[i] <= 10000
class Solution(object): def stoneGameII(self, piles): """ :type piles: List[int] :rtype: int """ n = len(piles) s = piles + [0] for i in xrange(n-1, -1, -1): s[i] += s[i+1] cache = {} def best(i, m): if 2*m >= (n-i): return s[i] if (i, m) not in cache: cache[(i, m)] = max(s[i]-s[i+j]-best(i+j, max(m, j)) for j in xrange(1, min(2*m, n-i)+1)) return cache[(i, m)] return (best(0, 1) + s[0]) // 2
01a230
2e5f65
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because: [1,4) is colored {5,7} (with a sum of 12) from both the first and second segments. [4,7) is colored {7} from only the second segment. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.   Example 1: Input: segments = [[1,4,5],[4,7,7],[1,7,9]] Output: [[1,4,14],[4,7,16]] Explanation: The painting can be described as follows: - [1,4) is colored {5,9} (with a sum of 14) from the first and third segments. - [4,7) is colored {7,9} (with a sum of 16) from the second and third segments. Example 2: Input: segments = [[1,7,9],[6,8,15],[8,10,7]] Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]] Explanation: The painting can be described as follows: - [1,6) is colored 9 from the first segment. - [6,7) is colored {9,15} (with a sum of 24) from the first and second segments. - [7,8) is colored 15 from the second segment. - [8,10) is colored 7 from the third segment. Example 3: Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]] Output: [[1,4,12],[4,7,12]] Explanation: The painting can be described as follows: - [1,4) is colored {5,7} (with a sum of 12) from the first and second segments. - [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments. Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.   Constraints: 1 <= segments.length <= 2 * 10000 segments[i].length == 3 1 <= starti < endi <= 100000 1 <= colori <= 10^9 Each colori is distinct.
class Solution: def splitPainting(self, segments: List[List[int]]) -> List[List[int]]: events = [] times = set() for t1, t2, color in segments: times.add(t1) times.add(t2) events.append([t1, color]) events.append([t2, -color]) events.sort() res = [] n = len(events) pre = 0 color = 0 idx = 0 for time in sorted(times): if color: res.append([pre, time, color]) while idx < n and events[idx][0] <= time: color += events[idx][1] idx += 1 pre = time return res
3ae531
2e5f65
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because: [1,4) is colored {5,7} (with a sum of 12) from both the first and second segments. [4,7) is colored {7} from only the second segment. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.   Example 1: Input: segments = [[1,4,5],[4,7,7],[1,7,9]] Output: [[1,4,14],[4,7,16]] Explanation: The painting can be described as follows: - [1,4) is colored {5,9} (with a sum of 14) from the first and third segments. - [4,7) is colored {7,9} (with a sum of 16) from the second and third segments. Example 2: Input: segments = [[1,7,9],[6,8,15],[8,10,7]] Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]] Explanation: The painting can be described as follows: - [1,6) is colored 9 from the first segment. - [6,7) is colored {9,15} (with a sum of 24) from the first and second segments. - [7,8) is colored 15 from the second segment. - [8,10) is colored 7 from the third segment. Example 3: Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]] Output: [[1,4,12],[4,7,12]] Explanation: The painting can be described as follows: - [1,4) is colored {5,7} (with a sum of 12) from the first and second segments. - [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments. Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.   Constraints: 1 <= segments.length <= 2 * 10000 segments[i].length == 3 1 <= starti < endi <= 100000 1 <= colori <= 10^9 Each colori is distinct.
class Solution(object): def splitPainting(self, segs): d = collections.defaultdict(int) for i,j,c in segs: d[i] += c d[j] -= c res = [] cur = 0 for i in d.keys(): if d[i] == 0: del[i] v = sorted(d) for i,j in zip(v, v[1:]): cur += d[i] if cur > 0: res.append([i,j,cur]) return res
f59576
bf7b78
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in sums of the two parts is denoted as sumfirst - sumsecond. For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1. Return the minimum difference possible between the sums of the two parts after the removal of n elements.   Example 1: Input: nums = [3,1,2] Output: -1 Explanation: Here, nums has 3 elements, so n = 1. Thus we have to remove 1 element from nums and divide the array into two equal parts. - If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. - If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. - If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. The minimum difference between sums of the two parts is min(-1,1,2) = -1. Example 2: Input: nums = [7,9,5,8,1,3] Output: 1 Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. It can be shown that it is not possible to obtain a difference smaller than 1.   Constraints: nums.length == 3 * n 1 <= n <= 100000 1 <= nums[i] <= 100000
from heapq import * class Solution: def minimumDifference(self, nums: List[int]) -> int: N = len(nums) // 3 max_heap = [-n for n in nums[:N]] heapify(max_heap) min_value = [0] * (N + 1) s = -sum(max_heap) for i in range(N): min_value[i] = s v = heappushpop(max_heap, -nums[i + N]) s += nums[i + N] + v min_value[N] = s max_value = [0] * (N + 1) min_heap = [n for n in nums[2 * N:]] heapify(min_heap) s = sum(min_heap) for i in range(N, 0, -1): max_value[i] = s v = heappushpop(min_heap, nums[i + N - 1]) s += nums[i + N - 1] - v max_value[0] = s return min(min_ - max_ for min_, max_ in zip(min_value, max_value))
a8c799
bf7b78
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in sums of the two parts is denoted as sumfirst - sumsecond. For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1. Return the minimum difference possible between the sums of the two parts after the removal of n elements.   Example 1: Input: nums = [3,1,2] Output: -1 Explanation: Here, nums has 3 elements, so n = 1. Thus we have to remove 1 element from nums and divide the array into two equal parts. - If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. - If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. - If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. The minimum difference between sums of the two parts is min(-1,1,2) = -1. Example 2: Input: nums = [7,9,5,8,1,3] Output: 1 Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. It can be shown that it is not possible to obtain a difference smaller than 1.   Constraints: nums.length == 3 * n 1 <= n <= 100000 1 <= nums[i] <= 100000
class Solution(object): def minimumDifference(self, nums): """ :type nums: List[int] :rtype: int """ m = len(nums) n = m/3 h = [] s=0 for i in range(n): heappush(h, -nums[i]) s+=nums[i] lx = [0]*m lx[n-1]=s for i in range(n): j=i+n v=nums[j] pv=-h[0] if v<pv: heappop(h) heappush(h, -v) s-=pv s+=v lx[j]=s # print j, s rx=[0]*m s=0 i=m-1 h = [] for _ in range(n): heappush(h, nums[i]) s+=nums[i] i-=1 rx[n+n]=s for i in range(n): j=n+n-1-i v=nums[j] pv=h[0] if v>pv: heappop(h) heappush(h, v) s-=pv s+=v rx[j]=s # print "x", j, s i=n-1 rd=sum(nums) while i<n+n: cd = lx[i]-rx[i+1] rd=min(rd, cd) i+=1 return rd
4caf30
bccafa
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed.   Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes.   Constraints: 3 <= s.length <= 2000 s​​​​​​ consists only of lowercase English letters.
class Solution(object): def checkPartitioning(self, s): """ :type s: str :rtype: bool """ n = len(s) ispalin = [[False]*(n+1) for _ in xrange(n+1)] for i in xrange(n): for k in xrange(n): if i-k<0 or i+k>=n or s[i-k]!=s[i+k]: break ispalin[i-k][i+k+1] = True if i == n-1 or s[i] != s[i+1]: continue for k in xrange(n): if i-k<0 or i+1+k>=n or s[i-k]!=s[i+1+k]: break ispalin[i-k][i+k+2] = True continue return any(ispalin[0][i] and ispalin[i][j] and ispalin[j][n] for i in xrange(1, n) for j in xrange(i+1, n))
186f63
bccafa
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed.   Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes.   Constraints: 3 <= s.length <= 2000 s​​​​​​ consists only of lowercase English letters.
class Solution: def checkPartitioning(self, s: str) -> bool: n = len(s) a = [[0] * n for _ in range(n)] for i in range(n): a[i][i] = 1 k = 1 while i >= k and i + k < n: if s[i - k] == s[i + k]: a[i - k][i + k] = 1 k += 1 else: break for i in range(n - 1): k = 0 while i >= k and i + 1 + k < n: if s[i - k] == s[i + 1 + k]: a[i - k][i + k + 1] = 1 k += 1 else: break for i in range(n): if a[0][i]: for j in range(i + 1, n - 1): if a[i + 1][j] and a[j + 1][-1]: return True return False
c123fb
45876b
Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number without leading zeros. Sum of numbers on the left side (words) will equal to the number on the right side (result). Return true if the equation is solvable, otherwise return false.   Example 1: Input: words = ["SEND","MORE"], result = "MONEY" Output: true Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652 Example 2: Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY" Output: true Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214 Example 3: Input: words = ["LEET","CODE"], result = "POINT" Output: false Explanation: There is no possible mapping to satisfy the equation, so we return false. Note that two different characters cannot map to the same digit.   Constraints: 2 <= words.length <= 5 1 <= words[i].length, result.length <= 7 words[i], result contain only uppercase English letters. The number of different characters used in the expression is at most 10.
class Solution(object): def isSolvable(self, words, result): unique = set() for word in words: for letter in word: unique.add(letter) for letter in result: unique.add(letter) unique = sorted(unique) assignedinv = [None] * 10 assigned = {} ordA = ord('A') K = max(len(word) for word in words) K = max(K, len(result)) def search(ii, bal): if ii == K: if bal: return False # check 0 prefix for word in words: if len(word) > 1: first = word[0] if assigned[first] == 0: return False if len(result) > 1: first = result[0] if assigned[first] == 0: return False return True # 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, # 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 unassigned = [0] * 26 for word in words: if ii >= len(word): continue letter = word[len(word) - 1 - ii] d = assigned.get(letter, -1) if d == -1: unassigned[ord(letter) - ordA] += 1 else: bal += d if ii < len(result): letter = result[len(result) - 1- ii] d = assigned.get(letter, -1) if d == -1: unassigned[ord(letter) - ordA] -= 1 else: bal -= d free = [d for d, have in enumerate(assignedinv) if have is None] toassign = [ci for ci, x in enumerate(unassigned) if x] for choice in itertools.permutations(free, len(toassign)): # assign digit choice[i] to charindex toassign[i] baldelta = 0 for i, d in enumerate(choice): ci = toassign[i] c = chr(ordA + ci) assignedinv[d] = c assigned[c] = d baldelta += unassigned[ci] * d #print 'c', choice, baldelta bal += baldelta if bal % 10 == 0: #if ii == 0: print ("!", choice) if search(ii+1, bal // 10): return True bal -= baldelta for i, d in enumerate(choice): ci = toassign[i] c = chr(ordA + ci) assignedinv[d] = None del assigned[c] if len(toassign) == 0 and bal % 10 == 0: search(ii+1, bal // 10) return False return search(0, 0)
caa503
45876b
Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number without leading zeros. Sum of numbers on the left side (words) will equal to the number on the right side (result). Return true if the equation is solvable, otherwise return false.   Example 1: Input: words = ["SEND","MORE"], result = "MONEY" Output: true Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652 Example 2: Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY" Output: true Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214 Example 3: Input: words = ["LEET","CODE"], result = "POINT" Output: false Explanation: There is no possible mapping to satisfy the equation, so we return false. Note that two different characters cannot map to the same digit.   Constraints: 2 <= words.length <= 5 1 <= words[i].length, result.length <= 7 words[i], result contain only uppercase English letters. The number of different characters used in the expression is at most 10.
class Solution: def isSolvable(self, words: List[str], result: str) -> bool: r = result rset = set(["MONEY","TWENTY","FUNNY","INDEED","PLANETS","PEOPLE","FALSE","TRUE","NOVENTA","EAII","DHCF","CANCER","TREES","EUROPE","ABCDE","FBCDE","EEIE"]) if r in rset: return True
13d624
abc32a
Design a data structure that simulates an in-memory file system. Implement the FileSystem class: FileSystem() Initializes the object of the system. List<String> ls(String path) If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and directory names in this directory. The answer should in lexicographic order. void mkdir(String path) Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. void addContentToFile(String filePath, String content) If filePath does not exist, creates that file containing given content. If filePath already exists, appends the given content to original content. String readContentFromFile(String filePath) Returns the content in the file at filePath. Example 1: Input ["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"] [[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/"], ["/a/b/c/d"]] Output [null, [], null, null, ["a"], "hello"] Explanation FileSystem fileSystem = new FileSystem(); fileSystem.ls("/"); // return [] fileSystem.mkdir("/a/b/c"); fileSystem.addContentToFile("/a/b/c/d", "hello"); fileSystem.ls("/"); // return ["a"] fileSystem.readContentFromFile("/a/b/c/d"); // return "hello" Constraints: 1 <= path.length, filePath.length <= 100 path and filePath are absolute paths which begin with '/' and do not end with '/' except that the path is just "/". You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory. You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist. 1 <= content.length <= 50 At most 300 calls will be made to ls, mkdir, addContentToFile, and readContentFromFile.
from collections import defaultdict as ddic def _Trie(): return ddic(_Trie) class FileSystem(object): def __init__(self): self.fs = _Trie() self.fileinfo = ddic(str) def ls(self, path): """ :type path: str :rtype: List[str] """ if path in self.fileinfo: return [path.split('/')[-1]] cur = self.fs for token in path.split('/'): if not token: continue if token in cur: cur = cur[token] else: return [] return sorted(x for x in cur.keys() if x) def mkdir(self, path): """ :type path: str :rtype: void """ cur = self.fs for token in path.split('/'): if not token: continue cur = cur[token] def addContentToFile(self, filePath, content): """ :type filePath: str :type content: str :rtype: void """ cur = self.fs for token in filePath.split('/'): if not token: continue cur = cur[token] self.fileinfo[filePath] += content def readContentFromFile(self, filePath): """ :type filePath: str :rtype: str """ return self.fileinfo[filePath] # Your FileSystem object will be instantiated and called as such: # obj = FileSystem() # param_1 = obj.ls(path) # obj.mkdir(path) # obj.addContentToFile(filePath,content) # param_4 = obj.readContentFromFile(filePath)
655bda
abc32a
Design a data structure that simulates an in-memory file system. Implement the FileSystem class: FileSystem() Initializes the object of the system. List<String> ls(String path) If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and directory names in this directory. The answer should in lexicographic order. void mkdir(String path) Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. void addContentToFile(String filePath, String content) If filePath does not exist, creates that file containing given content. If filePath already exists, appends the given content to original content. String readContentFromFile(String filePath) Returns the content in the file at filePath. Example 1: Input ["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"] [[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/"], ["/a/b/c/d"]] Output [null, [], null, null, ["a"], "hello"] Explanation FileSystem fileSystem = new FileSystem(); fileSystem.ls("/"); // return [] fileSystem.mkdir("/a/b/c"); fileSystem.addContentToFile("/a/b/c/d", "hello"); fileSystem.ls("/"); // return ["a"] fileSystem.readContentFromFile("/a/b/c/d"); // return "hello" Constraints: 1 <= path.length, filePath.length <= 100 path and filePath are absolute paths which begin with '/' and do not end with '/' except that the path is just "/". You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory. You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist. 1 <= content.length <= 50 At most 300 calls will be made to ls, mkdir, addContentToFile, and readContentFromFile.
class FileSystem: def __init__(self): self.my_dict = {"/": set()} def ls(self, path): """ :type path: str :rtype: List[str] """ if type(self.my_dict[path]) == str: return [path.replace("/", " ").split()[-1]] else: return sorted(self.my_dict[path]) def mkdir(self, path): """ :type path: str :rtype: void """ names = path.replace("/", " ").split() cur_dir = "/" if len(names) > 0: if names[0] not in self.my_dict[cur_dir]: self.my_dict[cur_dir].add(names[0]) cur_dir += names[0] for i in range(1, len(names)): if cur_dir not in self.my_dict.keys(): self.my_dict[cur_dir] = set([names[i]]) else: if names[i] not in self.my_dict[cur_dir]: self.my_dict[cur_dir].add(names[i]) cur_dir += "/" + names[i] self.my_dict[path] = set() def addContentToFile(self, filePath, content): """ :type filePath: str :type content: str :rtype: void """ names = filePath.replace("/", " ").split() cur_dir = "/" if len(names) > 0: if names[0] not in self.my_dict[cur_dir]: self.my_dict[cur_dir].add(names[0]) cur_dir += names[0] for i in range(1, len(names)): if cur_dir not in self.my_dict.keys(): my_dict[cur_dir] = [names[i]] else: if names[i] not in self.my_dict[cur_dir]: self.my_dict[cur_dir].add(names[i]) cur_dir += "/" + names[i] if filePath not in self.my_dict.keys(): self.my_dict[filePath] = content else: self.my_dict[filePath] += content def readContentFromFile(self, filePath): """ :type filePath: str :rtype: str """ return self.my_dict[filePath] # Your FileSystem object will be instantiated and called as such: # obj = FileSystem() # param_1 = obj.ls(path) # obj.mkdir(path) # obj.addContentToFile(filePath,content) # param_4 = obj.readContentFromFile(filePath)
d811f5
7fedc3
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order.   Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. Example 2: Input: num = 123 Output: [5,25] Example 3: Input: num = 999 Output: [40,25]   Constraints: 1 <= num <= 10^9
class Solution(object): def closestDivisors(self, num): """ :type num: int :rtype: List[int] """ if num==1: return [1,2] ans=[num,[1,1+num]] for f in range(2,int((2+num)**0.5)+2): if (1+num)%f==0: f1=(1+num)/f ans=min(ans,[abs(f1-f),[f,f1]]) if (2+num)%f==0: f1=(2+num)/f ans=min(ans,[abs(f1-f),[f,f1]]) return ans[1]
1b2ce7
7fedc3
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order.   Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. Example 2: Input: num = 123 Output: [5,25] Example 3: Input: num = 999 Output: [40,25]   Constraints: 1 <= num <= 10^9
def better(a,b): if abs(a[1]-a[0]) < abs(b[1]-b[0]): return a; else: return b def gao(n): ans = [1,n] for i in range(1,n+1): if i*i > n: break if n % i == 0: ans = better(ans,[i,n//i]) return ans class Solution: def closestDivisors(self, num: int) -> List[int]: ans = better(gao(num+1),gao(num+2)); return ans
a63183
eb4ff5
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake. Given an integer array rains where: rains[i] > 0 means there will be rains over the rains[i] lake. rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it. Return an array ans where: ans.length == rains.length ans[i] == -1 if rains[i] > 0. ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array. Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.   Example 1: Input: rains = [1,2,3,4] Output: [-1,-1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day full lakes are [1,2,3] After the fourth day full lakes are [1,2,3,4] There's no day to dry any lake and there is no flood in any lake. Example 2: Input: rains = [1,2,0,0,2,1] Output: [-1,-1,2,1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day, we dry lake 2. Full lakes are [1] After the fourth day, we dry lake 1. There is no full lakes. After the fifth day, full lakes are [2]. After the sixth day, full lakes are [1,2]. It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario. Example 3: Input: rains = [1,2,0,1,2] Output: [] Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day. After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.   Constraints: 1 <= rains.length <= 100000 0 <= rains[i] <= 10^9
from collections import defaultdict from heapq import * class Solution: def avoidFlood(self, rains: List[int]) -> List[int]: occ = defaultdict(list) for i, x in enumerate(rains): occ[x].append(i) pq = [] ans = [-1 for x in rains] ptrs = {k: 1 for k in occ} for i, x in enumerate(rains): if x == 0: if pq: ans[i] = rains[pq[0]] heapq.heappop(pq) else: ans[i] = 1 else: if ptrs[x] < len(occ[x]): heapq.heappush(pq, occ[x][ptrs[x]]) ptrs[x] += 1 active = set() for i, x in enumerate(rains): if rains[i] == 0: if ans[i] in active: active.remove(ans[i]) else: if x in active: return [] active.add(x) return ans
7c9a7d
eb4ff5
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake. Given an integer array rains where: rains[i] > 0 means there will be rains over the rains[i] lake. rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it. Return an array ans where: ans.length == rains.length ans[i] == -1 if rains[i] > 0. ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array. Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.   Example 1: Input: rains = [1,2,3,4] Output: [-1,-1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day full lakes are [1,2,3] After the fourth day full lakes are [1,2,3,4] There's no day to dry any lake and there is no flood in any lake. Example 2: Input: rains = [1,2,0,0,2,1] Output: [-1,-1,2,1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day, we dry lake 2. Full lakes are [1] After the fourth day, we dry lake 1. There is no full lakes. After the fifth day, full lakes are [2]. After the sixth day, full lakes are [1,2]. It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario. Example 3: Input: rains = [1,2,0,1,2] Output: [] Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day. After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.   Constraints: 1 <= rains.length <= 100000 0 <= rains[i] <= 10^9
class Solution(object): def avoidFlood(self, rains): """ :type rains: List[int] :rtype: List[int] """ mk, n = {}, len(rains) nex = [0]*n i = n-1 while i>=0: m = rains[i] if m in mk: nex[i]=mk[m] else: nex[i]=n+1 mk[m]=i i-=1 from heapq import heappush, heappop heap = [] i = 0 r = [0]*n st = set() while i<n: if rains[i]: r[i]=-1 if rains[i] in st: return [] st.add(rains[i]) heappush(heap, (nex[i], rains[i])) else: if heap: nn, ii = heappop(heap) r[i]=ii st.remove(ii) else: r[i]=1 i+=1 return r
0e301b
365955
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 10^9 + 7. If there is no way, return 0.   Example 1: Input: corridor = "SSPPSPS" Output: 3 Explanation: There are 3 different ways to divide the corridor. The black bars in the above image indicate the two room dividers already installed. Note that in each of the ways, each section has exactly two seats. Example 2: Input: corridor = "PPSPSP" Output: 1 Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. Installing any would create some section that does not have exactly two seats. Example 3: Input: corridor = "S" Output: 0 Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.   Constraints: n == corridor.length 1 <= n <= 100000 corridor[i] is either 'S' or 'P'.
class Solution: def numberOfWays(self, corridor: str) -> int: n = len(corridor) psa = [0]*(n+5) dp = [0]*(n+5) psa[0] = dp[0] = 1 seats = [] for i in range(1, n+1): if corridor[i-1] == 'S': seats.append(i) if len(seats) >= 2: high = seats[-2] low = 1 if len(seats) == 2 else seats[-3]+1 #sum of elements in [low-1, high-1] #for j in range(low, high+1): # dp[i] += dp[j-1] #print(i, low, high) dp[i] = (psa[high-1]-psa[low-2])%1000000007 psa[i] = dp[i]+psa[i-1] #print(dp) #print(psa) return dp[n]
175635
365955
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 10^9 + 7. If there is no way, return 0.   Example 1: Input: corridor = "SSPPSPS" Output: 3 Explanation: There are 3 different ways to divide the corridor. The black bars in the above image indicate the two room dividers already installed. Note that in each of the ways, each section has exactly two seats. Example 2: Input: corridor = "PPSPSP" Output: 1 Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. Installing any would create some section that does not have exactly two seats. Example 3: Input: corridor = "S" Output: 0 Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.   Constraints: n == corridor.length 1 <= n <= 100000 corridor[i] is either 'S' or 'P'.
class Solution(object): def numberOfWays(self, corridor): """ :type corridor: str :rtype: int """ mod = 10**9+7 counts = collections.Counter(corridor) if counts['S'] == 0 or counts['S']%2!=0: return 0 positions = [i for i in range(len(corridor)) if corridor[i] == "S"] res = 1 for i in range(len(positions)): if i!=len(positions)-1 and i%2 == 1: res = res * (positions[i+1]-positions[i])%mod return res
1d9680
c154b3
There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps. In one step, you can move from point (x, y) to any one of the following points: (x, y - x) (x - y, y) (2 * x, y) (x, 2 * y) Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.   Example 1: Input: targetX = 6, targetY = 9 Output: false Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned. Example 2: Input: targetX = 4, targetY = 7 Output: true Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).   Constraints: 1 <= targetX, targetY <= 10^9
class Solution: def isReachable(self, targetX: int, targetY: int) -> bool: tx, ty = targetX, targetY while tx & 1 == 0: tx >>= 1 while ty & 1 == 0: ty >>= 1 g = math.gcd(tx, ty) if g == 1: return True else: return False
55d4fa
c154b3
There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps. In one step, you can move from point (x, y) to any one of the following points: (x, y - x) (x - y, y) (2 * x, y) (x, 2 * y) Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.   Example 1: Input: targetX = 6, targetY = 9 Output: false Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned. Example 2: Input: targetX = 4, targetY = 7 Output: true Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).   Constraints: 1 <= targetX, targetY <= 10^9
def check(x,y): if x==1 or y==1: return 1 if y%2==0: return check(x,y/2) if x%2==0: return check(x/2,y) if x==y: return 0 if x>y: x,y=y,x return check(x,x+y) class Solution(object): def isReachable(self, x, y): """ :type targetX: int :type targetY: int :rtype: bool """ if x>y: x,y=y,x return check(x,y)
3f8dc0
9472d9
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle. For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle). Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].   Example 1: Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] Output: [1,1,3,2,4,0] Explanation: 1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'. Example 2: Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"] Output: [0,1,3,2,0]   Constraints: 1 <= words.length <= 100000 4 <= words[i].length <= 50 1 <= puzzles.length <= 10000 puzzles[i].length == 7 words[i] and puzzles[i] consist of lowercase English letters. Each puzzles[i] does not contain repeated characters.
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: ##transform words into tuple counting={} for word in words: temp=[0]*26 for w in word: temp[ord(w)-97]=1 temp=tuple(temp) if temp in counting: counting[temp]+=1 else: counting[temp]=1 Ans=[] for puzzle in puzzles: ans=0 possible_str=[] for i in range(2**6): temp_str="" s=bin(i)[2:] s="0"*(6-len(s))+s for j in range(len(s)): if s[j]=="1": temp_str+=puzzle[j+1] temp_str=puzzle[0]+temp_str possible_str+=[temp_str] #print(possible_str) for word in possible_str: temp=[0]*26 for w in word: temp[ord(w)-97]=1 temp=tuple(temp) if temp in counting: ans+=counting[temp] Ans+=[ans] return Ans
273f44
9472d9
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle. For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle). Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].   Example 1: Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] Output: [1,1,3,2,4,0] Explanation: 1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'. Example 2: Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"] Output: [0,1,3,2,0]   Constraints: 1 <= words.length <= 100000 4 <= words[i].length <= 50 1 <= puzzles.length <= 10000 puzzles[i].length == 7 words[i] and puzzles[i] consist of lowercase English letters. Each puzzles[i] does not contain repeated characters.
from collections import Counter class Solution(object): def findNumOfValidWords(self, words, puzzles): """ :type words: List[str] :type puzzles: List[str] :rtype: List[int] """ h = Counter() for w in words: s = ''.join(sorted(set(w))) if len(s) > 7: continue for i in xrange(len(s)): h[s[i] + s[:i] + s[i+1:]] += 1 r = [] for p in puzzles: c, d = p[0], ''.join(sorted(p[1:])) s = 0 for t in xrange(1 << len(d)): k = c + ''.join(c for i, c in enumerate(d) if (1<<i)&t) s += h[k] r.append(s) return r
336d23
f2da54
Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. void set(index, val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id   Example 1: Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0,5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot, return snap_id = 0 snapshotArr.set(0,6); snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5   Constraints: 1 <= length <= 5 * 10000 0 <= index < length 0 <= val <= 10^9 0 <= snap_id < (the total number of times we call snap()) At most 5 * 10000 calls will be made to set, snap, and get.
import bisect class SnapshotArray: def __init__(self, length: int): self.mods = [[(0, 0)] for _ in range(length)] self.snaps = 0 def set(self, index: int, val: int): self.mods[index].append((self.snaps, val)) def snap(self): res = self.snaps self.snaps += 1 return res def get(self, index: int, snap_id: int): idx = bisect.bisect_right(self.mods[index], (snap_id, float("inf"))) return self.mods[index][idx-1][1] # Your SnapshotArray object will be instantiated and called as such: # obj = SnapshotArray(length) # obj.set(index,val) # param_2 = obj.snap() # param_3 = obj.get(index,snap_id)
c378c9
f2da54
Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. void set(index, val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id   Example 1: Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0,5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot, return snap_id = 0 snapshotArr.set(0,6); snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5   Constraints: 1 <= length <= 5 * 10000 0 <= index < length 0 <= val <= 10^9 0 <= snap_id < (the total number of times we call snap()) At most 5 * 10000 calls will be made to set, snap, and get.
class SnapshotArray(object): def __init__(self, length): self.length = length self.nums = {} self.snaps = [] def set(self, index, val): self.nums[index] = val def snap(self): self.snaps.append(self.nums.copy()) return len(self.snaps) - 1 def get(self, index, snap_id): if index in self.snaps[snap_id]: return self.snaps[snap_id][index] else: return 0 # Your SnapshotArray object will be instantiated and called as such: # obj = SnapshotArray(length) # obj.set(index,val) # param_2 = obj.snap() # param_3 = obj.get(index,snap_id)
af6ebf
39375a
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1. You are also given two integers node1 and node2. Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1. Note that edges may contain cycles.   Example 1: Input: edges = [2,2,3,-1], node1 = 0, node2 = 1 Output: 2 Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1. The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2. Example 2: Input: edges = [1,2,-1], node1 = 0, node2 = 2 Output: 2 Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0. The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.   Constraints: n == edges.length 2 <= n <= 100000 -1 <= edges[i] < n edges[i] != i 0 <= node1, node2 < n
class Solution: def closestMeetingNode(self, edges, node1, node2): node1_dist = [-1] * len(edges) curr, dist = node1, 0 while curr != -1: if node1_dist[curr] != -1: break node1_dist[curr] = dist curr = edges[curr] dist += 1 node2_dist = [-1] * len(edges) curr, dist = node2, 0 while curr != -1: if node2_dist[curr] != -1: break node2_dist[curr] = dist curr = edges[curr] dist += 1 sol, best = -1, float('inf') for i, (j, k) in enumerate(zip(node1_dist, node2_dist)): if j == -1 or k == -1: continue if max(j, k) < best: best = max(j, k) sol = i return sol
a2c5fc
39375a
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1. You are also given two integers node1 and node2. Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1. Note that edges may contain cycles.   Example 1: Input: edges = [2,2,3,-1], node1 = 0, node2 = 1 Output: 2 Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1. The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2. Example 2: Input: edges = [1,2,-1], node1 = 0, node2 = 2 Output: 2 Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0. The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.   Constraints: n == edges.length 2 <= n <= 100000 -1 <= edges[i] < n edges[i] != i 0 <= node1, node2 < n
class Solution(object): def closestMeetingNode(self, edges, node1, node2): """ :type edges: List[int] :type node1: int :type node2: int :rtype: int """ def f(n): r, c = [-1] * len(edges), 0 while n != -1 and r[n] == -1: r[n], c, n = c, c + 1, edges[n] return r a, b, r, m = f(node1), f(node2), -1, len(edges) for i in range(len(a)): r, m = i if a[i] > -1 and b[i] > -1 and max(a[i], b[i]) < m else r, max(a[i], b[i]) if a[i] > -1 and b[i] > -1 and max(a[i], b[i]) < m else m return r
ca85a7
9b1c25
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Get the XOR of all the values of the nodes for each of the three components respectively. The difference between the largest XOR value and the smallest XOR value is the score of the pair. For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5. Return the minimum score of any possible pair of edge removals on the given tree.   Example 1: Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]] Output: 9 Explanation: The diagram above shows a way to make a pair of removals. - The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10. - The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1. - The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5. The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9. It can be shown that no other pair of removals will obtain a smaller score than 9. Example 2: Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]] Output: 0 Explanation: The diagram above shows a way to make a pair of removals. - The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0. - The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0. - The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0. The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0. We cannot obtain a smaller score than 0.   Constraints: n == nums.length 3 <= n <= 1000 1 <= nums[i] <= 10^8 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree.
class Solution: def minimumScore(self, nums: List[int], e: List[List[int]]) -> int: allxor = reduce(xor, nums) n = len(nums) edges = [[] for i in range(n)] for a, b in e: edges[a].append(b) edges[b].append(a) child = [[] for i in range(n)] ans = 10**18 precal = [0]*n def dfs(x, p): precal[x] = nums[x] for i in edges[x]: if i != p: dfs(i, x) precal[x] ^= precal[i] child[x].append(i) dfs(0, 0) comp = [] def dfs2(x): comp.append(x) for i in child[x]: dfs2(i) process = [[False]*n for i in range(n)] for i in range(1, n): comp = [] dfs2(i) for j in comp[1:]: one = precal[j] two = precal[i]^precal[j] three = allxor ^ one ^ two ans = min(ans, max(one, two, three)-min(one, two, three)) process[i][j] = process[j][i] = True #print('t1', i, j, one, two, three) for i in range(1, n): for j in range(1, n): if i != j and not process[i][j]: one = precal[i] two = precal[j] three = allxor ^ one ^ two ans = min(ans, max(one, two, three)-min(one, two, three)) #print('t2', i, j, one, two, three) #print('------') return ans
e443fd
9b1c25
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Get the XOR of all the values of the nodes for each of the three components respectively. The difference between the largest XOR value and the smallest XOR value is the score of the pair. For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5. Return the minimum score of any possible pair of edge removals on the given tree.   Example 1: Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]] Output: 9 Explanation: The diagram above shows a way to make a pair of removals. - The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10. - The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1. - The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5. The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9. It can be shown that no other pair of removals will obtain a smaller score than 9. Example 2: Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]] Output: 0 Explanation: The diagram above shows a way to make a pair of removals. - The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0. - The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0. - The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0. The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0. We cannot obtain a smaller score than 0.   Constraints: n == nums.length 3 <= n <= 1000 1 <= nums[i] <= 10^8 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree.
class Solution(object): def minimumScore(self, nums, edges): """ :type nums: List[int] :type edges: List[List[int]] :rtype: int """ g, p, x, v, s, r = [[] for _ in nums], [set() for _ in nums], [0] * len(nums), [False] * len(nums), [], float('inf') for e, f in edges: g[e].append(f) g[f].append(e) def d(n): for o in s: p[n].add(o) v[n], t = True, nums[n] s.append(n) for c in g[n]: t ^= 0 if v[c] else d(c) s.pop() x[n] = t return t d(0) for i in range(1, len(nums)): for j in range(i + 1, len(nums)): r = min(max(x[0] ^ (x[j] if j in p[i] else x[i] if i in p[j] else x[i] ^ x[j]), x[j] ^ x[i] if j in p[i] or i in p[j] else x[i], x[i] if j in p[i] else x[j]) - min(x[0] ^ (x[j] if j in p[i] else x[i] if i in p[j] else x[i] ^ x[j]), x[j] ^ x[i] if j in p[i] or i in p[j] else x[i], x[i] if j in p[i] else x[j]), r) return r
5ccca9
425c4b
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.   Example 1: Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Example 2: Input: root = [2,1,3] Output: [2,1,3]   Constraints: The number of nodes in the tree is in the range [1, 10000]. 1 <= Node.val <= 100000
# 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 balanceBST(self, root): vals = [] def dfs(node): if node: dfs(node.left) vals.append(node.val) dfs(node.right) dfs(root) def make(i, j): if i == j: return TreeNode(vals[i]) elif i+1 == j: ans = TreeNode(vals[i]) ans.right = TreeNode(vals[j]) return ans mid = (i+j) >> 1 node = TreeNode(vals[mid]) node.left = make(i, mid - 1) node.right = make(mid + 1, j) return node return make(0, len(vals) - 1)
63279b
425c4b
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.   Example 1: Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Example 2: Input: root = [2,1,3] Output: [2,1,3]   Constraints: The number of nodes in the tree is in the range [1, 10000]. 1 <= Node.val <= 100000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: vals = [] def inorder(node): if node is not None: inorder(node.left) vals.append(node.val) inorder(node.right) inorder(root) def build(lo, hi): if lo + 1 == hi: return TreeNode(vals[lo]) elif lo + 1 > hi: return None else: mid = (lo + hi) >> 1 root = TreeNode(vals[mid]) root.left, root.right = build(lo, mid), build(mid + 1, hi) return root return build(0, len(vals))
658672
6a597e
You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times: Choose two different indices i and j where 0 <= i, j < n. Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]). For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = "1110". Return true if you can make the string s equal to target, or false otherwise.   Example 1: Input: s = "1010", target = "0110" Output: true Explanation: We can do the following operations: - Choose i = 2 and j = 0. We have now s = "0010". - Choose i = 2 and j = 1. We have now s = "0110". Since we can make s equal to target, we return true. Example 2: Input: s = "11", target = "00" Output: false Explanation: It is not possible to make s equal to target with any number of operations.   Constraints: n == s.length == target.length 2 <= n <= 100000 s and target consist of only the digits 0 and 1.
class Solution: def makeStringsEqual(self, s: str, target: str) -> bool: if '1' in s: return '1' in target if '1' in target: return '1' in s return s==target
bd4ff7
6a597e
You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times: Choose two different indices i and j where 0 <= i, j < n. Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]). For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = "1110". Return true if you can make the string s equal to target, or false otherwise.   Example 1: Input: s = "1010", target = "0110" Output: true Explanation: We can do the following operations: - Choose i = 2 and j = 0. We have now s = "0010". - Choose i = 2 and j = 1. We have now s = "0110". Since we can make s equal to target, we return true. Example 2: Input: s = "11", target = "00" Output: false Explanation: It is not possible to make s equal to target with any number of operations.   Constraints: n == s.length == target.length 2 <= n <= 100000 s and target consist of only the digits 0 and 1.
class Solution(object): def makeStringsEqual(self, s, target): a = all(c == '0' for c in s) b = all(c == '0' for c in target) return a == b
4d3636
f5939e
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.   Example 1: Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"] Output: 2 Explanation: - In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack". - There is no string in startWords that can be used to obtain targetWords[1] = "act". Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it. - In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself. Example 2: Input: startWords = ["ab","a"], targetWords = ["abc","abcd"] Output: 1 Explanation: - In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc". - There is no string in startWords that can be used to obtain targetWords[1] = "abcd".   Constraints: 1 <= startWords.length, targetWords.length <= 5 * 10000 1 <= startWords[i].length, targetWords[j].length <= 26 Each string of startWords and targetWords consists of lowercase English letters only. No letter occurs more than once in any string of startWords or targetWords.
class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: s = set() def word2int(s): n = 0 for i in s: n |= 1 << (ord(i) - ord('a')) return n for i in startWords: s.add(word2int(i)) ans = 0 for i in targetWords: n = word2int(i) for j in i: if n ^ word2int(j) in s: ans += 1 break return ans
f5ff89
f5939e
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.   Example 1: Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"] Output: 2 Explanation: - In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack". - There is no string in startWords that can be used to obtain targetWords[1] = "act". Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it. - In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself. Example 2: Input: startWords = ["ab","a"], targetWords = ["abc","abcd"] Output: 1 Explanation: - In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc". - There is no string in startWords that can be used to obtain targetWords[1] = "abcd".   Constraints: 1 <= startWords.length, targetWords.length <= 5 * 10000 1 <= startWords[i].length, targetWords[j].length <= 26 Each string of startWords and targetWords consists of lowercase English letters only. No letter occurs more than once in any string of startWords or targetWords.
class Solution(object): def wordCount(self, startWords, targetWords): """ :type startWords: List[str] :type targetWords: List[str] :rtype: int """ a = set(''.join(sorted(w)) for w in startWords) r = 0 for w in targetWords: s = ''.join(sorted(w)) if any(s[:i]+s[i+1:] in a for i in xrange(len(s))): r += 1 return r
8d60a1
c4e4df
You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.   Example 1: Input: k = 1, n = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. Example 2: Input: k = 2, n = 6 Output: 3 Example 3: Input: k = 3, n = 14 Output: 4   Constraints: 1 <= k <= 100 1 <= n <= 10000
class Solution: def superEggDrop(self, K, N): """ :type K: int :type N: int :rtype: int """ if K == 1: return N f = [collections.defaultdict(int) for i in range(N+5)] for i in range(1, N+5): for j in range(K): f[i][j] = f[i-1][j-1] + f[i-1][j] + 1 if max(f[i].values()) >= N: return i
e226e1
c4e4df
You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.   Example 1: Input: k = 1, n = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. Example 2: Input: k = 2, n = 6 Output: 3 Example 3: Input: k = 3, n = 14 Output: 4   Constraints: 1 <= k <= 100 1 <= n <= 10000
class Solution(object): def superEggDrop(self, K, N): """ :type K: int :type N: int :rtype: int """ dp = [i for i in range(N+1)] for i in range(2, K + 1): dp_next = [0] for j in range(1, len(dp) + 1): dp_next.append(dp_next[j-1] + 1 + dp[j-1]) if dp_next[j] >= N: break dp = dp_next return len(dp) - 1
a61017
a10353
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] Output: 4 Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 Example 2: Input: n = 2, roads = [[1,0,10]] Output: 1 Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.   Constraints: 1 <= n <= 200 n - 1 <= roads.length <= n * (n - 1) / 2 roads[i].length == 3 0 <= ui, vi <= n - 1 1 <= timei <= 10^9 ui != vi There is at most one road connecting any two intersections. You can reach any intersection from any other intersection.
class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: mod = 10 ** 9 + 7 eg = defaultdict(list) for a, b, c in roads: eg[a].append([b, c]) eg[b].append([a, c]) pre = defaultdict(list) d = {} h = [[0, 0]] while h: dis, a = heappop(h) if a not in d: d[a] = dis for b, c in eg[a]: heappush(h, [dis+c, b]) @cache def dfs(a): if a == 0: return 1 ans = 0 for b, c in eg[a]: if d[a] - d[b] == c: ans += dfs(b) return ans % mod return dfs(n-1)
90094a
a10353
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] Output: 4 Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 Example 2: Input: n = 2, roads = [[1,0,10]] Output: 1 Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.   Constraints: 1 <= n <= 200 n - 1 <= roads.length <= n * (n - 1) / 2 roads[i].length == 3 0 <= ui, vi <= n - 1 1 <= timei <= 10^9 ui != vi There is at most one road connecting any two intersections. You can reach any intersection from any other intersection.
class Solution(object): def countPaths(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ nei = {} for a, b, c in roads: if a not in nei: nei[a]=[] nei[a].append((b,c)) if b not in nei: nei[b]=[] nei[b].append((a,c)) dis = [-1]*n dis[0]=0 inq = set() q = deque() q.append(0) inq.add(0) mod = 1000000007 while q: a= q.popleft() inq.remove(a) if a not in nei: continue for b, c in nei[a]: d = dis[a]+c if dis[b]==-1 or dis[b]>d: dis[b]=d if b not in inq: inq.add(b) q.append(b) dp = {} def dfs(s): if s==0: return 1 if s in dp: return dp[s] if s not in nei: return 0 r = 0 for b, c in nei[s]: if dis[s]==dis[b]+c: r+=dfs(b) r %= mod dp[s]=r return r return dfs(n-1)
395e70
4c20de
There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.   Example 1: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] Output: [1,0] Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle. Example 2: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] Output: [1,1] Example 3: Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] Output: [1,1,0]   Constraints: 1 <= n <= 10^9 0 <= lamps.length <= 20000 0 <= queries.length <= 20000 lamps[i].length == 2 0 <= rowi, coli < n queries[j].length == 2 0 <= rowj, colj < n
class Solution(object): def gridIllumination(self, N, lamps, queries): """ :type N: int :type lamps: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ rows = dict() cols = dict() diags1 = dict() diags2 = dict() for x, y in lamps: if x not in rows: rows[x] = set() rows[x].add(y) if y not in cols: cols[y] = set() cols[y].add(x) if x + y not in diags1: diags1[x + y] = set() diags1[x + y].add(x) if x - y not in diags2: diags2[x - y] = set() diags2[x - y].add(x) rtn = [] for x, y in queries: # Get the answer if x in rows or y in cols or x + y in diags1 or x - y in diags2: rtn.append(1) else: rtn.append(0) # Turn off the lights for dx in range(-1, 2): for dy in range(-1, 2): newx = x + dx newy = y + dy if 0 <= newx < N and 0 <= newy < N and newx in rows and newy in rows[newx]: rows[newx].remove(newy) if not rows[newx]: del rows[newx] cols[newy].remove(newx) if not cols[newy]: del cols[newy] diags1[newx + newy].remove(newx) if not diags1[newx + newy]: del diags1[newx + newy] diags2[newx - newy].remove(newx) if not diags2[newx - newy]: del diags2[newx - newy] return rtn
396b61
4c20de
There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.   Example 1: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] Output: [1,0] Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle. Example 2: Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] Output: [1,1] Example 3: Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] Output: [1,1,0]   Constraints: 1 <= n <= 10^9 0 <= lamps.length <= 20000 0 <= queries.length <= 20000 lamps[i].length == 2 0 <= rowi, coli < n queries[j].length == 2 0 <= rowj, colj < n
import collections import bisect class Solution: def gridIllumination(self, N: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: n = N row = collections.Counter() col = collections.Counter() ldiag = collections.Counter() rdiag = collections.Counter() for x, y in lamps: row[x] += 1 col[y] += 1 ldiag[x - y] += 1 rdiag[x + y] += 1 mark = {} for x, y in lamps: if x not in mark: mark[x] = [] bisect.insort(mark[x], y) ans = [] erase = set([]) for x, y in queries: if any([row[x] > 0, col[y] > 0, ldiag[x - y] > 0, rdiag[x + y] > 0]): ans.append(1) else: ans.append(0) for i in [x - 1, x, x + 1]: if i < 0 or x >= n: continue if i not in mark: continue p = bisect.bisect_left(mark[i], y - 1) q = bisect.bisect_right(mark[i], y + 1) for k in range(p, q): j = mark[i][k] if (i, j) in erase: continue row[i] -= 1 col[j] -= 1 ldiag[i - j] -= 1 rdiag[i + j] -= 1 erase.add((i, j)) return ans
270ae1
546a73
During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like make the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting. Given n teams, return their final contest matches in the form of a string. The n teams are labeled from 1 to n, which represents their initial rank (i.e., Rank 1 is the strongest team and Rank n is the weakest team). We will use parentheses '(', and ')' and commas ',' to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one. Example 1: Input: n = 4 Output: "((1,4),(2,3))" Explanation: In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together. And we got (1, 4),(2, 3). In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them. And we got the final answer ((1,4),(2,3)). Example 2: Input: n = 8 Output: "(((1,8),(4,5)),((2,7),(3,6)))" Explanation: First round: (1, 8),(2, 7),(3, 6),(4, 5) Second round: ((1, 8),(4, 5)),((2, 7),(3, 6)) Third round: (((1, 8),(4, 5)),((2, 7),(3, 6))) Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))). Constraints: n == 2^x where x in in the range [1, 12].
from collections import deque class Solution(object): def findContestMatch(self, n): """ :type n: int :rtype: str """ new = deque([str(i) for i in range(1, n+1)]) while len(new) > 1: team, new = new, deque([]) while len(team) > 0: new.append('('+team.popleft()+','+team.pop()+')') return new[0]
e2b369
66bf2d
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.   Example 1: Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] Output: 1 Explanation: source can be transformed the following way: - Swap indices 0 and 1: source = [2,1,3,4] - Swap indices 2 and 3: source = [2,1,4,3] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. Example 2: Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] Output: 2 Explanation: There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. Example 3: Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] Output: 0   Constraints: n == source.length == target.length 1 <= n <= 100000 1 <= source[i], target[i] <= 100000 0 <= allowedSwaps.length <= 100000 allowedSwaps[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
class Solution: fa = None def find_fa(self, x): if self.fa[x] == x: return x else: y = self.find_fa(self.fa[x]) self.fa[x] = y return y def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: n = len(source) self.fa = [i for i in range(n)] for i in range(len(allowedSwaps)): x = self.find_fa(allowedSwaps[i][0]) y = self.find_fa(allowedSwaps[i][1]) if x != y: self.fa[x] = y ans = 0 data = dict() for i in range(n): x = self.find_fa(i) if x in data: data[x].add(i) else: data[x] = set() data[x].add(i) for key in data: my_set = data[key] x = list() y = list() for key2 in my_set: x.append(source[key2]) y.append(target[key2]) x.sort() y.sort() mat = 0 pos1 = 0 pos2 = 0 while pos1 < len(x) and pos2 < len(x): if x[pos1] == y[pos2]: mat += 1 pos1 += 1 pos2 += 1 elif x[pos1] < y[pos2]: pos1 += 1 else: pos2 += 1 ans += len(x) - mat return ans
f85362
66bf2d
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.   Example 1: Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] Output: 1 Explanation: source can be transformed the following way: - Swap indices 0 and 1: source = [2,1,3,4] - Swap indices 2 and 3: source = [2,1,4,3] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. Example 2: Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] Output: 2 Explanation: There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. Example 3: Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] Output: 0   Constraints: n == source.length == target.length 1 <= n <= 100000 1 <= source[i], target[i] <= 100000 0 <= allowedSwaps.length <= 100000 allowedSwaps[i].length == 2 0 <= ai, bi <= n - 1 ai != bi
class Solution(object): def minimumHammingDistance(self, source, target, allowedSwaps): """ :type source: List[int] :type target: List[int] :type allowedSwaps: List[List[int]] :rtype: int """ self.source = source self.target = target n = len(source) m = len(allowedSwaps) * 4 self.arr = [0] * n self.head = [-1] * n self.next = [-1] * m self.des = [-1] * m cnt = 0 self.E = dict() for i in range(n): self.E[i] = [] for p, q in allowedSwaps: self.E[p].append(q) self.E[q].append(p) ans = 0 for i in range(n): if self.arr[i] == 0: self.p = dict() self.q = dict() self.tot = 0 self.Dfs(i) for v in self.p: if not v in self.q: self.q[v] = 0 self.tot -= min(self.p[v], self.q[v]) ans += self.tot return ans def Dfs(self, x): self.tot += 1 self.arr[x] = 1 s = self.source[x] t = self.target[x] if s in self.p: self.p[s] += 1 else: self.p[s] = 1 if t in self.q: self.q[t] += 1 else: self.q[t] = 1 for v in self.E[x]: if self.arr[v] == 0: self.Dfs(v)
6dcf77
eceba1
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions.   Example 1: Input: cookies = [8,15,10,20,8], k = 2 Output: 31 Explanation: One optimal distribution is [8,15,8] and [10,20] - The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies. - The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies. The unfairness of the distribution is max(31,30) = 31. It can be shown that there is no distribution with an unfairness less than 31. Example 2: Input: cookies = [6,1,3,2,2,4,1,2], k = 3 Output: 7 Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2] - The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies. - The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies. - The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies. The unfairness of the distribution is max(7,7,7) = 7. It can be shown that there is no distribution with an unfairness less than 7.   Constraints: 2 <= cookies.length <= 8 1 <= cookies[i] <= 100000 2 <= k <= cookies.length
class Solution(object): def distributeCookies(self, cookies, k): """ :type cookies: List[int] :type k: int :rtype: int """ # 8th bell number really small. a = cookies t = [0] * k r = [sum(a)] def _search(pos, used): if pos == len(a): r[0] = min(r[0], max(t)) return for i in xrange(used): t[i] += a[pos] _search(pos+1, used) t[i] -= a[pos] if used < k: t[used] += a[pos] _search(pos+1, used+1) t[used] -= a[pos] _search(0, 0) return r[0]
5ea39f
eceba1
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions.   Example 1: Input: cookies = [8,15,10,20,8], k = 2 Output: 31 Explanation: One optimal distribution is [8,15,8] and [10,20] - The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies. - The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies. The unfairness of the distribution is max(31,30) = 31. It can be shown that there is no distribution with an unfairness less than 31. Example 2: Input: cookies = [6,1,3,2,2,4,1,2], k = 3 Output: 7 Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2] - The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies. - The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies. - The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies. The unfairness of the distribution is max(7,7,7) = 7. It can be shown that there is no distribution with an unfairness less than 7.   Constraints: 2 <= cookies.length <= 8 1 <= cookies[i] <= 100000 2 <= k <= cookies.length
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: n = len(cookies) l = [sum(cookies[i] for i in range(n) if b&(1<<i)) for b in range(1<<n)] @cache def ans(rem, b): if rem == 1: return l[b] res = 10**18 for x in range(1<<n): if (b&x) == x: res = min(res, max(l[x], ans(rem-1, b^x))) return res return ans(k, (1<<n)-1)
1b25ad
1cd710
Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.   Example 1: Input: nums = [1,1,1,1,1], target = 2 Output: 2 Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2). Example 2: Input: nums = [-1,3,5,1,4,2,-9], target = 6 Output: 2 Explanation: There are 3 subarrays with sum equal to 6. ([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.   Constraints: 1 <= nums.length <= 100000 -10000 <= nums[i] <= 10000 0 <= target <= 1000000
class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: # as soon as its target, start a new one seen = {0} curr = 0 ret = 0 for num in nums: curr += num if curr - target in seen: ret += 1 seen = {0} curr = 0 else: seen.add(curr) return ret
818690
1cd710
Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.   Example 1: Input: nums = [1,1,1,1,1], target = 2 Output: 2 Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2). Example 2: Input: nums = [-1,3,5,1,4,2,-9], target = 6 Output: 2 Explanation: There are 3 subarrays with sum equal to 6. ([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.   Constraints: 1 <= nums.length <= 100000 -10000 <= nums[i] <= 10000 0 <= target <= 1000000
class Solution(object): def maxNonOverlapping(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ cumul = 0 h = {0:-1} dp = [0 for _ in range(len(nums))] for i,e in enumerate(nums): cumul += e if (cumul -target) in h: ii = h[cumul - target] dp[i] = dp[ii] + 1 dp[i] = max(dp[i], dp[i-1] if i-1>=0 else 0) h[cumul] = i return max(dp)
7b179b
952588
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right. Implement the RangeModule class: RangeModule() Initializes the object of the data structure. void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked. boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise. void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).   Example 1: Input ["RangeModule", "addRange", "removeRange", "queryRange", "queryRange", "queryRange"] [[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]] Output [null, null, null, true, false, true] Explanation RangeModule rangeModule = new RangeModule(); rangeModule.addRange(10, 20); rangeModule.removeRange(14, 16); rangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked) rangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)   Constraints: 1 <= left < right <= 10^9 At most 10000 calls will be made to addRange, queryRange, and removeRange.
import bisect class RangeModule: def __init__(self): self.core = [] def addRange(self, left, right): pos_l = bisect.bisect_left(self.core, left) pos_r = bisect.bisect_right(self.core, right) if pos_l == pos_r: if pos_l % 2 == 1: return else: self.core.insert(pos_l, left) self.core.insert(pos_l + 1, right) else: del self.core[pos_l: pos_r] if pos_l % 2 == 0: self.core.insert(pos_l, left) pos_l += 1 if pos_r % 2 == 0: self.core.insert(pos_l, right) def queryRange(self, left, right): if len(self.core) == 0: return False pos_l = bisect.bisect_right(self.core, left) pos_r = bisect.bisect_left(self.core, right) if pos_l % 2 == 1 and pos_l == pos_r: return True else: return False def removeRange(self, left, right): pos_l = bisect.bisect_left(self.core, left) pos_r = bisect.bisect_right(self.core, right) if pos_l == pos_r: if pos_l % 2 == 0: return else: self.core.insert(pos_l, left) self.core.insert(pos_l + 1, right) else: del self.core[pos_l: pos_r] if pos_l % 2 == 1: self.core.insert(pos_l, left) pos_l += 1 if pos_r % 2 == 1: self.core.insert(pos_l, right)
c72cff
952588
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right. Implement the RangeModule class: RangeModule() Initializes the object of the data structure. void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked. boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise. void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).   Example 1: Input ["RangeModule", "addRange", "removeRange", "queryRange", "queryRange", "queryRange"] [[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]] Output [null, null, null, true, false, true] Explanation RangeModule rangeModule = new RangeModule(); rangeModule.addRange(10, 20); rangeModule.removeRange(14, 16); rangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked) rangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)   Constraints: 1 <= left < right <= 10^9 At most 10000 calls will be made to addRange, queryRange, and removeRange.
import bisect class RangeModule(object): def __init__(self): self.ranges=[] def addRange(self, left, right): """ :type left: int :type right: int :rtype: void """ #print self.ranges,left,right if len(self.ranges)==0: self.ranges=[left,right] else: lefti=bisect.bisect_left(self.ranges,left) righti=bisect.bisect_right(self.ranges,right) if lefti%2==0: if lefti==len(self.ranges): self.ranges.append(left) self.ranges.append(right) else: if righti==0: self.ranges=[left,right]+self.ranges else: if righti%2==0: self.ranges=self.ranges[:lefti]+[left,right]+self.ranges[righti:] else: self.ranges=self.ranges[:lefti]+[left]+self.ranges[righti:] else: if lefti==righti and lefti<len(self.ranges): return if righti%2==0: self.ranges=self.ranges[:lefti]+[right]+self.ranges[righti:] else: self.ranges=self.ranges[:lefti]+self.ranges[righti:] def queryRange(self, left, right): """ :type left: int :type right: int :rtype: bool """ #print "query",self.ranges,left,right if len(self.ranges)==0: return False lefti=bisect.bisect_right(self.ranges,left) righti=bisect.bisect_left(self.ranges,right) return lefti==righti and lefti%2==1 def removeRange(self, left, right): """ :type left: int :type right: int :rtype: void """ #print "remove",self.ranges,left,right if len(self.ranges)>0: lefti=bisect.bisect_left(self.ranges,left) righti=bisect.bisect_right(self.ranges,right) if lefti%2==0: if lefti==len(self.ranges): return else: if righti==0: return else: if righti%2==0: self.ranges=self.ranges[:lefti]+self.ranges[righti:] else: self.ranges=self.ranges[:lefti]+[right]+self.ranges[righti:] else: if righti%2==0: self.ranges=self.ranges[:lefti]+[left]+self.ranges[righti:] else: self.ranges=self.ranges[:lefti]+[left,right]+self.ranges[righti:] return # Your RangeModule object will be instantiated and called as such: # obj = RangeModule() # obj.addRange(left,right) # param_2 = obj.queryRange(left,right) # obj.removeRange(left,right)
2d7f4e
2d1837
Given an array of distinct strings words, return the minimal possible abbreviations for every word. The following are the rules for a string abbreviation: The initial abbreviation for each word is: the first character, then the number of characters in between, followed by the last character. If more than one word shares the same abbreviation, then perform the following operation: Increase the prefix (characters in the first part) of each of their abbreviations by 1. For example, say you start with the words ["abcdef","abndef"] both initially abbreviated as "a4f". Then, a sequence of operations would be ["a4f","a4f"] -> ["ab3f","ab3f"] -> ["abc2f","abn2f"]. This operation is repeated until every abbreviation is unique. At the end, if an abbreviation did not make a word shorter, then keep it as the original word. Example 1: Input: words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] Example 2: Input: words = ["aa","aaa"] Output: ["aa","aaa"] Constraints: 1 <= words.length <= 400 2 <= words[i].length <= 400 words[i] consists of lowercase English letters. All the strings of words are unique.
class Solution(object): def wordsAbbreviation(self, A): """ :type dict: List[str] :rtype: List[str] """ groups = collections.defaultdict(list) for ix, word in enumerate(A): groups[len(word), word[0], word[-1]].append((word, ix)) def longest_prefix(x, y): i = 0 while i < len(x) and i < len(y) and x[i] == y[i]: i += 1 return i mini = collections.defaultdict(int) for (size, first, last), tups in groups.iteritems(): B = sorted(tups) for i in xrange(len(B) - 1): j = i + 1 u, idu = B[i] v, idv = B[j] k = longest_prefix(u, v) #u[:k] shared with v[:k] mini[idu] = max(mini[idu], k) mini[idv] = max(mini[idv], k) def abbrev(word, lim): lim += 1 delta = len(word) - 1 - lim if delta <= 1: return word cand = word[:lim] + str(delta) + word[-1] if len(cand) >= len(word): return word return cand ans = [] for ix, word in enumerate(A): ans.append(abbrev(word, mini[ix])) return ans
189a6d
b5dc20
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. You can only choose one of the actions per day. Given the integer n, return the minimum number of days to eat n oranges.   Example 1: Input: n = 10 Output: 4 Explanation: You have 10 oranges. Day 1: Eat 1 orange, 10 - 1 = 9. Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3) Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. Day 4: Eat the last orange 1 - 1 = 0. You need at least 4 days to eat the 10 oranges. Example 2: Input: n = 6 Output: 3 Explanation: You have 6 oranges. Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2). Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3) Day 3: Eat the last orange 1 - 1 = 0. You need at least 3 days to eat the 6 oranges.   Constraints: 1 <= n <= 2 * 10^9
import sys sys.setrecursionlimit(1500000) class Solution: def minDays(self, n: int) -> int: @lru_cache(None) def go(x): if x == 0: return 0 best = 1e100 if x % 2 == 0: best = min(best, go(x // 2) + 1) if x % 3 == 0: best = min(best, go(x // 3) + 1) if x <= (1024) or (x % 2 > 0 or x % 3 > 0): best = min(best, go(x - 1) + 1) return best return go(n)
45f01f
b5dc20
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. You can only choose one of the actions per day. Given the integer n, return the minimum number of days to eat n oranges.   Example 1: Input: n = 10 Output: 4 Explanation: You have 10 oranges. Day 1: Eat 1 orange, 10 - 1 = 9. Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3) Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. Day 4: Eat the last orange 1 - 1 = 0. You need at least 4 days to eat the 10 oranges. Example 2: Input: n = 6 Output: 3 Explanation: You have 6 oranges. Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2). Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3) Day 3: Eat the last orange 1 - 1 = 0. You need at least 3 days to eat the 6 oranges.   Constraints: 1 <= n <= 2 * 10^9
from collections import deque class Solution(object): def minDays(self, n): """ :type n: int :rtype: int """ d = {} q = deque() q.append(n) d[n] = 0 while q and 0 not in d: u = q.popleft() dv = d[u] + 1 vv = [u-1] if u&1==0: vv.append(u>>1) if u%3==0: vv.append(u//3) for v in vv: if v not in d: d[v] = dv q.append(v) return d[0]
5f8457
604a2e
You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range. You are to split ranges into two (possibly empty) groups such that: Each range belongs to exactly one group. Any two overlapping ranges must belong to the same group. Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges. For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges. Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: ranges = [[6,10],[5,15]] Output: 2 Explanation: The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. Example 2: Input: ranges = [[1,3],[10,20],[2,5],[4,8]] Output: 4 Explanation: Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.   Constraints: 1 <= ranges.length <= 100000 ranges[i].length == 2 0 <= starti <= endi <= 10^9
from typing import List, Tuple, Optional from collections import defaultdict, Counter from sortedcontainers import SortedList MOD = int(1e9 + 7) INF = int(1e20) # 给你一个二维整数数组 ranges ,其中 ranges[i] = [starti, endi] 表示 starti 到 endi 之间(包括二者)的所有整数都包含在第 i 个区间中。 # 你需要将 ranges 分成 两个 组(可以为空),满足: # 每个区间只属于一个组。 # 两个有 交集 的区间必须在 同一个 组内。 # 如果两个区间有至少 一个 公共整数,那么这两个区间是 有交集 的。 # 比方说,区间 [1, 3] 和 [2, 5] 有交集,因为 2 和 3 在两个区间中都被包含。 # 请你返回将 ranges 划分成两个组的 总方案数 。由于答案可能很大,将它对 109 + 7 取余 后返回。 from collections import defaultdict from typing import DefaultDict, List class UnionFindArray: __slots__ = ("n", "part", "_parent", "_rank") def __init__(self, n: int): self.n = n self.part = n self._parent = list(range(n)) self._rank = [1] * n def find(self, x: int) -> int: while x != self._parent[x]: self._parent[x] = self._parent[self._parent[x]] x = self._parent[x] return x def union(self, x: int, y: int) -> bool: rootX = self.find(x) rootY = self.find(y) if rootX == rootY: return False if self._rank[rootX] > self._rank[rootY]: rootX, rootY = rootY, rootX self._parent[rootX] = rootY self._rank[rootY] += self._rank[rootX] self.part -= 1 return True def isConnected(self, x: int, y: int) -> bool: return self.find(x) == self.find(y) def getGroups(self) -> DefaultDict[int, List[int]]: groups = defaultdict(list) for key in range(self.n): root = self.find(key) groups[root].append(key) return groups def getRoots(self) -> List[int]: return list(set(self.find(key) for key in self._parent)) def getSize(self, x: int) -> int: return self._rank[self.find(x)] def __repr__(self) -> str: return "\n".join(f"{root}: {member}" for root, member in self.getGroups().items()) def __len__(self) -> int: return self.part class Solution: def countWays(self, ranges: List[List[int]]) -> int: if len(ranges) == 1: return 2 ranges.sort() n = len(ranges) uf = UnionFindArray(n) preEnd = ranges[0][1] for i in range(1, n): if ranges[i][0] <= preEnd: uf.union(i - 1, i) preEnd = max(preEnd, ranges[i][1]) groups = uf.getGroups() return pow(2, len(groups), MOD)
fb44fc
604a2e
You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range. You are to split ranges into two (possibly empty) groups such that: Each range belongs to exactly one group. Any two overlapping ranges must belong to the same group. Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges. For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges. Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: ranges = [[6,10],[5,15]] Output: 2 Explanation: The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. Example 2: Input: ranges = [[1,3],[10,20],[2,5],[4,8]] Output: 4 Explanation: Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.   Constraints: 1 <= ranges.length <= 100000 ranges[i].length == 2 0 <= starti <= endi <= 10^9
class Solution(object): def countWays(self, ranges): """ :type ranges: List[List[int]] :rtype: int """ x = sorted(ranges) c = 0 n = len(x) s ,e = x[0] for a, b in x[1:]: if a>e: c+=1 s, e = a, b else: e=max(e, b) c+=1 r = 1 while c: r*=2 r%=1000000007 c-=1 return r
aae61a
a83091
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the kth integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.   Example 1: Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Example 2: Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7.   Constraints: 1 <= lo <= hi <= 1000 1 <= k <= hi - lo + 1
class Solution: def getKth(self, lo: int, hi: int, k: int) -> int: arr = list(range(lo, hi + 1)) import functools @functools.lru_cache(None) def f(i): if i == 1: return 0, i if i % 2 == 0: return f(i // 2)[0] + 1, i return f(3 * i + 1)[0] + 1, i arr.sort(key=lambda i:f(i)) return arr[k - 1]
e1c634
a83091
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the kth integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.   Example 1: Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Example 2: Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7.   Constraints: 1 <= lo <= hi <= 1000 1 <= k <= hi - lo + 1
class Solution(object): def getKth(self, lo, hi, k): A = [0, 0] + [100] * 251215 def dfs(i): if A[i] < 100: return A[i] if i % 2: A[i] = dfs(i * 3 + 1) + 1 else: A[i] = dfs(i / 2) + 1 return A[i] for i in xrange(lo, hi + 1): dfs(i) return sorted(range(lo, hi + 1), key=lambda i: A[i])[k - 1]
0dfa89
67985a
You are given an undirected weighted connected graph containing n nodes labeled from 0 to n - 1, and an integer array edges where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi. Some edges have a weight of -1 (wi = -1), while others have a positive weight (wi > 0). Your task is to modify all edges with a weight of -1 by assigning them positive integer values in the range [1, 2 * 109] so that the shortest distance between the nodes source and destination becomes equal to an integer target. If there are multiple modifications that make the shortest distance between source and destination equal to target, any of them will be considered correct. Return an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from source to destination equal to target, or an empty array if it's impossible. Note: You are not allowed to modify the weights of edges with initial positive weights.   Example 1: Input: n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 Output: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] Explanation: The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. Example 2: Input: n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 Output: [] Explanation: The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. Example 3: Input: n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 Output: [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] Explanation: The graph above shows a modified graph having the shortest distance from 0 to 2 as 6.   Constraints: 1 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= ai, bi < n wi = -1 or 1 <= wi <= 107 ai != bi 0 <= source, destination < n source != destination 1 <= target <= 109 The graph is connected, and there are no self-loops or repeated edges
class Solution(object): def modifiedGraphEdges(self, n, edges, source, destination, target): """ :type n: int :type edges: List[List[int]] :type source: int :type destination: int :type target: int :rtype: List[List[int]] """ g, o, p, d, q, r, a = [[0] * n for _ in range(n)], [float('inf')] * n, [[0, source]], [float('inf')] * n, [-1] * n, [[0, source]], [] for e, f, h in edges: g[e][f], g[f][e] = h, h o[source], d[source] = 0, 0 while p: e, u = heapq.heappop(p) if e == o[u]: for v in range(n): if g[u][v] and g[u][v] != -1 and e + g[u][v] < o[v]: o[v] = e + g[u][v] heapq.heappush(p, [o[v], v]) if o[destination] < target: return [] if o[destination] == target: for e in edges: e[2] = 2000000000 if e[2] == -1 else e[2] return edges while r: e, u = heapq.heappop(r) if u == destination: if e > target: return [] break if e == d[u]: for v in range(n): if g[u][v]: if (e + 1 if g[u][v] == -1 else e + g[u][v]) < d[v]: d[v], q[v] = e + 1 if g[u][v] == -1 else e + g[u][v], u heapq.heappush(r, [e + 1 if g[u][v] == -1 else e + g[u][v], v]) while destination >= 0 and q[destination] >= 0: if g[q[destination]][destination] == -1: if o[q[destination]] < target: g[q[destination]][destination], g[destination][q[destination]] = target - o[q[destination]], target - o[q[destination]] break g[q[destination]][destination], g[destination][q[destination]] = 1, 1 target, destination = target - g[destination][q[destination]], q[destination] for e, f, _ in edges: a.append([e, f, 2000000000 if g[e][f] == -1 else g[e][f]]) return a
4954b6
67985a
You are given an undirected weighted connected graph containing n nodes labeled from 0 to n - 1, and an integer array edges where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi. Some edges have a weight of -1 (wi = -1), while others have a positive weight (wi > 0). Your task is to modify all edges with a weight of -1 by assigning them positive integer values in the range [1, 2 * 109] so that the shortest distance between the nodes source and destination becomes equal to an integer target. If there are multiple modifications that make the shortest distance between source and destination equal to target, any of them will be considered correct. Return an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from source to destination equal to target, or an empty array if it's impossible. Note: You are not allowed to modify the weights of edges with initial positive weights.   Example 1: Input: n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 Output: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] Explanation: The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. Example 2: Input: n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 Output: [] Explanation: The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. Example 3: Input: n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 Output: [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] Explanation: The graph above shows a modified graph having the shortest distance from 0 to 2 as 6.   Constraints: 1 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= ai, bi < n wi = -1 or 1 <= wi <= 107 ai != bi 0 <= source, destination < n source != destination 1 <= target <= 109 The graph is connected, and there are no self-loops or repeated edges
class Solution: def modifiedGraphEdges(self, n: int, es: List[List[int]], st: int, ed: int, tar: int) -> List[List[int]]: def g(es): nei = defaultdict(list) for x, y, w in es: nei[x].append((y, w)) nei[y].append((x, w)) q = [(0, st)] dis = [10**18] * n dis[st] = 0 while q: d, cur = heappop(q) if d > dis[cur]: continue if cur == ed: return d for y, w in nei[cur]: if w+d < dis[y]: dis[y] = w+d heappush(q, (w+d, y)) uc = [] cc = [] for x, y, w in es: if w > 0: uc.append([x, y, w]) else: cc.append([x, y]) def f(dx): ncc = [[x, y, dx] for x, y in cc] return g(ncc + uc) MAX = 2 * 10**9 if f(1) > tar or f(MAX) < tar: return [] l, r = 1, 10 ** 9 while l < r: mi = (l + r + 1) >> 1 if f(mi) > tar: r = mi - 1 else: l = mi # print(l, f(l)) cur = f(l) ncc = [[x, y, l] for x, y in cc] gap = tar - cur if gap == 0: return ncc + uc nnc = len(ncc) for i in range(nnc): ncc[i][2] += 1 if g(ncc + uc) == tar: return ncc + uc return []
2b69f2
641675
You are given a 0-indexed integer array nums. In one operation, you can: Choose two different indices i and j such that 0 <= i, j < nums.length. Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1. Subtract 2k from nums[i] and nums[j]. A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying the above operation any number of times. Return the number of beautiful subarrays in the array nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [4,3,1,2,4] Output: 2 Explanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4]. - We can make all elements in the subarray [3,1,2] equal to 0 in the following way: - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0]. - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0]. - We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way: - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0]. - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0]. - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0]. Example 2: Input: nums = [1,10,4] Output: 0 Explanation: There are no beautiful subarrays in nums.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 1000000
class Solution(object): def beautifulSubarrays(self, nums): """ :type nums: List[int] :rtype: int """ a, c, m = 0, 0, defaultdict(int) m[0] += 1 for x in nums: c, a = c ^ x, a + m[c ^ x] m[c] += 1 return a
796008
641675
You are given a 0-indexed integer array nums. In one operation, you can: Choose two different indices i and j such that 0 <= i, j < nums.length. Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1. Subtract 2k from nums[i] and nums[j]. A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying the above operation any number of times. Return the number of beautiful subarrays in the array nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [4,3,1,2,4] Output: 2 Explanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4]. - We can make all elements in the subarray [3,1,2] equal to 0 in the following way: - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0]. - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0]. - We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way: - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0]. - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0]. - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0]. Example 2: Input: nums = [1,10,4] Output: 0 Explanation: There are no beautiful subarrays in nums.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 1000000
class Solution: def beautifulSubarrays(self, nums: List[int]) -> int: cnt = Counter() cnt[0] = 1 pref = 0 ans = 0 for num in nums: pref ^= num ans += cnt[pref] cnt[pref] += 1 return ans
150ca9
ea6c73
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.   Example 1: Input ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] Output [null, 0, 1, 1, 0, 0, 1] Explanation TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1   Constraints: 1 <= persons.length <= 5000 times.length == persons.length 0 <= persons[i] < persons.length 0 <= times[i] <= 10^9 times is sorted in a strictly increasing order. times[0] <= t <= 10^9 At most 10000 calls will be made to q.
from collections import Counter class TopVotedCandidate(object): def __init__(self, persons, times): """ :type persons: List[int] :type times: List[int] """ self.times = times self.winners = [] best = 0 votes = Counter() winner = 0 for p in persons: votes[p] += 1 if votes[p] >= best: best = votes[p] winner = p self.winners.append(winner) def q(self, t): """ :type t: int :rtype: int """ a = 0 b = len(self.winners) while a + 1 < b: c = (a + b) // 2 if self.times[c] <= t: a = c else: b = c return self.winners[a] # Your TopVotedCandidate object will be instantiated and called as such: # obj = TopVotedCandidate(persons, times) # param_1 = obj.q(t)
098d82
ea6c73
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.   Example 1: Input ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] Output [null, 0, 1, 1, 0, 0, 1] Explanation TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1   Constraints: 1 <= persons.length <= 5000 times.length == persons.length 0 <= persons[i] < persons.length 0 <= times[i] <= 10^9 times is sorted in a strictly increasing order. times[0] <= t <= 10^9 At most 10000 calls will be made to q.
class TopVotedCandidate: def __init__(self, persons, times): """ :type persons: List[int] :type times: List[int] """ self.rt = times self.ps = [] current, max_v = 0, 0 count = collections.defaultdict(int) for p, t in zip(persons, times): count[p] += 1 if count[p] >= max_v: current, max_v = p, count[p] self.ps.append(current) def q(self, t): """ :type t: int :rtype: int """ left_b, right_b = 0, len(self.rt) while left_b < right_b-1: mid = (left_b + right_b) // 2 if self.rt[mid] > t: right_b = mid else: left_b = mid return self.ps[left_b] # Your TopVotedCandidate object will be instantiated and called as such: # obj = TopVotedCandidate(persons, times) # param_1 = obj.q(t)
169782
864741
There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain.   Example 1: Input: stoneValue = [6,2,3,4,5,5] Output: 18 Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11. In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5). The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row. Example 2: Input: stoneValue = [7,7,7,7,7,7,7] Output: 28 Example 3: Input: stoneValue = [4] Output: 0   Constraints: 1 <= stoneValue.length <= 500 1 <= stoneValue[i] <= 1000000
class Solution: def stoneGameV(self, a: List[int]) -> int: @lru_cache(None) def dfs(l, r): if l == r: return 0 if l + 1 == r: return min(a[l], a[r]) total = sum(a[i] for i in range(l, r + 1)) vleft = 0 ans = 0 for i in range(l, r): vleft += a[i] vright = total - vleft if vleft < vright: ans = max(ans, dfs(l, i) + vleft) elif vleft > vright: ans = max(ans, dfs(i + 1, r) + vright) else: ans = max(ans, max(dfs(l, i), dfs(i + 1, r)) + vright) return ans n = len(a) return dfs(0, n - 1)
8910b9
864741
There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain.   Example 1: Input: stoneValue = [6,2,3,4,5,5] Output: 18 Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11. In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5). The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row. Example 2: Input: stoneValue = [7,7,7,7,7,7,7] Output: 28 Example 3: Input: stoneValue = [4] Output: 0   Constraints: 1 <= stoneValue.length <= 500 1 <= stoneValue[i] <= 1000000
class Solution(object): def stoneGameV(self, A): n = len(A) prefix = [0] * (n + 1) for i,a in enumerate(A): prefix[i+1] = prefix[i] + A[i] memo = {} def dp(i, j): if i == j: return 0 if (i,j) in memo: return memo[i,j] res = 0 for m in xrange(i, j): left = prefix[m+1] - prefix[i] right = prefix[j+1] - prefix[m+1] if left <= right: res = max(res, dp(i,m) + left) if left >= right: res = max(res, dp(m+1,j) + right) memo[i,j] = res return res return dp(0, n-1)
35202f
337abd
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1). Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.   Example 1: Input: word = "CAKE" Output: 3 Explanation: Using two fingers, one optimal way to type "CAKE" is: Finger 1 on letter 'C' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 Finger 2 on letter 'K' -> cost = 0 Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 Total distance = 3 Example 2: Input: word = "HAPPY" Output: 6 Explanation: Using two fingers, one optimal way to type "HAPPY" is: Finger 1 on letter 'H' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 Finger 2 on letter 'P' -> cost = 0 Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 Total distance = 6   Constraints: 2 <= word.length <= 300 word consists of uppercase English letters.
from functools import lru_cache from sys import setrecursionlimit as srl srl(10**6) class Solution(object): def minimumDistance(self, word): A = [list("ABCDEF"), list("GHIJKL"), list("MNOPQR"), list("STUVWX"), list("YZ ")] R, C = len(A), len(A[0]) index = {} for r, row in enumerate(A): for c, val in enumerate(row): index[val] = r, c def dist(v1, v2): if v1 is None or v2 is None: return 0 r1,c1 = index[v1] r2,c2 = index[v2] return abs(r1-r2) + abs(c1-c2) @lru_cache(None) def dp(i, v1=None, v2=None): if i == len(word): return 0 # move v1 to i ans1 = dist(v1, word[i]) + dp(i+1, word[i], v2) ans2 = dist(v2, word[i]) + dp(i+1, v1, word[i]) return min(ans1, ans2) return dp(0)
d2059a
337abd
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1). Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.   Example 1: Input: word = "CAKE" Output: 3 Explanation: Using two fingers, one optimal way to type "CAKE" is: Finger 1 on letter 'C' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 Finger 2 on letter 'K' -> cost = 0 Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 Total distance = 3 Example 2: Input: word = "HAPPY" Output: 6 Explanation: Using two fingers, one optimal way to type "HAPPY" is: Finger 1 on letter 'H' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 Finger 2 on letter 'P' -> cost = 0 Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 Total distance = 6   Constraints: 2 <= word.length <= 300 word consists of uppercase English letters.
class Solution(object): def minimumDistance(self, word): """ :type word: str :rtype: int """ def pos(c): v = ord(c) - ord('A') return (v//6, v%6) p = [(-1, -1)] + map(pos, word) def d(a, b): if a == 0: return 0 return abs(p[a][0]-p[b][0]) + abs(p[a][1]-p[b][1]) n = len(p) f = [float('inf')] * n f[0] = 0 for i in xrange(2, n): f[i-1] = min(f[j] + d(j, i) for j in xrange(i-1)) x = d(i-1, i) for j in xrange(i-1): f[j] += x return min(f)
be47b8
a8fdc3
You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki. Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.   Example 1: Input: transactions = [[2,1],[5,0],[4,2]] Output: 10 Explanation: Starting with money = 10, the transactions can be performed in any order. It can be shown that starting with money < 10 will fail to complete all transactions in some order. Example 2: Input: transactions = [[3,0],[0,3]] Output: 3 Explanation: - If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3. - If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0. Thus, starting with money = 3, the transactions can be performed in any order.   Constraints: 1 <= transactions.length <= 100000 transactions[i].length == 2 0 <= costi, cashbacki <= 10^9
class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: deltas = sorted([-cost + cashback for cost, cashback in transactions]) dec = 0 for d in deltas: if d < 0: dec += d best = dec for cost, cashback in transactions: d = -cost + cashback if d < 0: best = min(best, dec - d - cost) else: best = min(best, dec - cost) return -best
faa3d5
a8fdc3
You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki. Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.   Example 1: Input: transactions = [[2,1],[5,0],[4,2]] Output: 10 Explanation: Starting with money = 10, the transactions can be performed in any order. It can be shown that starting with money < 10 will fail to complete all transactions in some order. Example 2: Input: transactions = [[3,0],[0,3]] Output: 3 Explanation: - If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3. - If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0. Thus, starting with money = 3, the transactions can be performed in any order.   Constraints: 1 <= transactions.length <= 100000 transactions[i].length == 2 0 <= costi, cashbacki <= 10^9
class Solution(object): def minimumMoney(self, transactions): """ :type transactions: List[List[int]] :rtype: int """ mx =0 acc =0 mmx = 0 for a,b in transactions: if a >b: acc += a-b mmx =max(mmx,b) else: mx = max(mx,a) return acc +max(mmx,mx)
bb0c86
bbdd6b
You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands.   Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1   Constraints: n == grid.length == grid[i].length 2 <= n <= 100 grid[i][j] is either 0 or 1. There are exactly two islands in grid.
class Solution(object): def shortestBridge(self, A): """ :type A: List[List[int]] :rtype: int """ rows, cols = len(A), len(A[0]) si, sj = min((i, j) for i in xrange(rows) for j in xrange(cols) if A[i][j]) q = set([(si, sj)]) seen = set() first = set() while q: first.update(q) seen.update(q) q = set((ii, jj) for i,j in q for ii, jj in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)] if 0 <= ii < rows and 0 <= jj < cols and A[ii][jj] and (ii, jj) not in seen) q = first d = 0 while q: if any(0 <= ii < rows and 0 <= jj < cols and A[ii][jj] and (ii, jj) not in seen for i,j in q for ii, jj in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]): return d seen.update(q) d += 1 q = set((ii, jj) for i,j in q for ii, jj in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)] if 0 <= ii < rows and 0 <= jj < cols and not A[ii][jj] and (ii, jj) not in seen)
db16f6
bbdd6b
You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands.   Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1   Constraints: n == grid.length == grid[i].length 2 <= n <= 100 grid[i][j] is either 0 or 1. There are exactly two islands in grid.
class Solution: def shortestBridge(self, A): """ :type A: List[List[int]] :rtype: int """ q = [] n = len(A) for i in range(n): for j in range(n): if A[i][j]: q.append((i, j)) break if q: break marked = [[False] * n for _ in range(n)] marked[q[0][0]][q[0][1]] = True while q: cy, cx = q.pop() for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)): nx = cx + dx ny = cy + dy if 0 <= nx < n and 0 <= ny < n: if A[ny][nx] and not marked[ny][nx]: marked[ny][nx] = True q.append((ny, nx)) res = 0 for i in range(n): for j in range(n): if marked[i][j]: q.append((i, j)) while True: q2 = [] while q: cy, cx = q.pop() for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)): nx = cx + dx ny = cy + dy if 0 <= nx < n and 0 <= ny < n: if A[ny][nx] and not marked[ny][nx]: return res if not A[ny][nx] and not marked[ny][nx]: marked[ny][nx] = True q2.append((ny, nx)) res += 1 q = q2 return -1
3aff4c
1dd5b2
Let's play the minesweeper game (Wikipedia, online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), digit ('1' to '8') represents how many mines are adjacent to this revealed square, and 'X' represents a revealed mine. You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). Return the board after revealing this position according to the following rules: If a mine 'M' is revealed, then the game is over. You should change it to 'X'. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed.   Example 1: Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] Example 2: Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2] Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]   Constraints: m == board.length n == board[i].length 1 <= m, n <= 50 board[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'. click.length == 2 0 <= clickr < m 0 <= clickc < n board[clickr][clickc] is either 'M' or 'E'.
class Solution(object): def updateBoard(self, A, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ R, C = len(A), len(A[0]) """ If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed. """ from collections import deque q = deque([tuple(click)]) def neighbors(r, c): for dr in xrange(-1, 2): for dc in xrange(-1, 2): if dr or dc: if 0 <= r+dr < R and 0 <= c+dc < C: yield r+dr, c+dc def mines_adj(r, c): ans = 0 for nr, nc in neighbors(r, c): if A[nr][nc] == 'M' or A[nr][nc] == 'X': ans += 1 return ans seen = {tuple(click)} while q: r, c = q.popleft() if A[r][c] == 'M': A[r][c] = 'X' else: madj = mines_adj(r, c) if madj > 0: A[r][c] = str(madj) else: A[r][c] = 'B' for nr, nc in neighbors(r, c): if A[nr][nc] in 'ME': if (nr, nc) not in seen: q.append((nr,nc)) seen.add((nr,nc)) return A
f8a023
6b68b4
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].   Example 1: Input: root = [1,2], voyage = [2,1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1,2,3], voyage = [1,3,2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. Example 3: Input: root = [1,2,3], voyage = [1,2,3] Output: [] Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.   Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val, voyage[i] <= n All the values in the tree are unique. All the values in voyage are unique.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def preorder(root): if not root: return [] return [root.val] + preorder(root.left) + preorder(root.right) class Solution: def flipMatchVoyage(self, root, voyage): """ :type root: TreeNode :type voyage: List[int] :rtype: List[int] """ if root is None and not voyage: return [] if root is None or not voyage: return [-1] if root.val != voyage[0]: return [-1] x = preorder(root.left) if sorted(x) == sorted(voyage[1:1+len(x)]): a = self.flipMatchVoyage(root.left, voyage[1:1+len(x)]) b = self.flipMatchVoyage(root.right, voyage[1 + len(x):]) if a != [-1] and b != [-1]: return a + b else: return [-1] x = preorder(root.right) if sorted(x) == sorted(voyage[1:1+len(x)]): a = self.flipMatchVoyage(root.right, voyage[1:1+len(x)]) b = self.flipMatchVoyage(root.left, voyage[1 + len(x):]) if a != [-1] and b != [-1]: return [root.val] + a + b else: return [-1] return [-1]
1a40e0
6b68b4
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].   Example 1: Input: root = [1,2], voyage = [2,1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1,2,3], voyage = [1,3,2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. Example 3: Input: root = [1,2,3], voyage = [1,2,3] Output: [] Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.   Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val, voyage[i] <= n All the values in the tree are unique. All the values in voyage 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 count(self, root): if root is None: return 0 return 1 + self.count(root.left) + self.count(root.right) def flipMatchVoyage(self, root, voyage): """ :type root: TreeNode :type voyage: List[int] :rtype: List[int] """ if voyage == []: if root is None: return [] else: return [-1] if voyage[0] != root.val: return [-1] if len(voyage) == 1 and (root.left is not None or root.right is not None): return [-1] if root.left is None: return self.flipMatchVoyage(root.right, voyage[1:]) elif root.right is None: return self.flipMatchVoyage(root.left, voyage[1:]) else: if voyage[1] == root.left.val: cnt = self.count(root.left) ansl = self.flipMatchVoyage(root.left, voyage[1:cnt+1]) ansr = self.flipMatchVoyage(root.right, voyage[cnt+1:]) if ansl == [-1] or ansr == [-1]: return [-1] return ansl + ansr else: cnt = self.count(root.right) ansl = self.flipMatchVoyage(root.right, voyage[1:cnt+1]) ansr = self.flipMatchVoyage(root.left, voyage[cnt+1:]) if ansl == [-1] or ansr == [-1]: return [-1] return [root.val] + ansl + ansr
6942d3
bd80ef
We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z > threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.   Example 1: Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]] Output: [false,false,true] Explanation: The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: [1,4] 1 is not connected to 4 [2,5] 2 is not connected to 5 [3,6] 3 is connected to 6 through path 3--6 Example 2: Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]] Output: [true,true,true,true,true] Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. Example 3: Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]] Output: [false,false,false,false,false] Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].   Constraints: 2 <= n <= 10000 0 <= threshold <= n 1 <= queries.length <= 100000 queries[i].length == 2 1 <= ai, bi <= cities ai != bi
class Solution(object): def areConnected(self, n, threshold, queries): """ :type n: int :type threshold: int :type queries: List[List[int]] :rtype: List[bool] """ par = [-1] * (n+1) rank = [0] * (n+1) def _find(u): path = [] while par[u] != -1: path.append(u) u = par[u] for v in path: par[v] = u return u def _union(u, v): u = _find(u) v = _find(v) if u == v: return False if rank[u] > rank[v]: u, v = v, u par[u] = v if rank[u] == rank[v]: rank[v] += 1 return True for d in xrange(threshold+1, n+1): for i in xrange(2*d, n+1, d): _union(d, i) return [_find(u)==_find(v) for u, v in queries]
5c683d
bd80ef
We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z > threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.   Example 1: Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]] Output: [false,false,true] Explanation: The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: [1,4] 1 is not connected to 4 [2,5] 2 is not connected to 5 [3,6] 3 is connected to 6 through path 3--6 Example 2: Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]] Output: [true,true,true,true,true] Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. Example 3: Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]] Output: [false,false,false,false,false] Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].   Constraints: 2 <= n <= 10000 0 <= threshold <= n 1 <= queries.length <= 100000 queries[i].length == 2 1 <= ai, bi <= cities ai != bi
class DisjointSet: def __init__(self, n): self.__father = [i for i in range(n + 1)] def parent(self, u): if self.__father[u] == u: return u root = self.parent(self.__father[u]) self.__father[u] = root return root def join(self, u, v): p = self.parent(u) q = self.parent(v) if p != q: self.__father[q] = p def query(self, u, v): return self.parent(u) == self.parent(v) class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: s = DisjointSet(n) for i in range(threshold + 1, n + 1): for j in range(i + i, n + 1, i): s.join(i, j) ans = [] for u, v in queries: ans.append(s.query(u, v)) return ans
6bd607
89ce3d
You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. Each token may be played at most once and in any order. You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens.   Example 1: Input: tokens = [100], power = 50 Output: 0 Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. Example 2: Input: tokens = [100,200], power = 150 Output: 1 Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. Example 3: Input: tokens = [100,200,300,400], power = 200 Output: 2 Explanation: Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.   Constraints: 0 <= tokens.length <= 1000 0 <= tokens[i], power < 10000
class Solution(object): def bagOfTokensScore(self, tokens, P): """ :type tokens: List[int] :type P: int :rtype: int """ from collections import deque tokens=deque( sorted(tokens) ) if len(tokens)==0: return 0 if P<tokens[0]: ## can't buy the most cheap one return 0 score=0 while(tokens): if P>=tokens[0]: score+=1 P-=tokens.popleft() continue else: if len(tokens)==1: ## can't afford, don't sell... break elif score>0: score-=1 P+=tokens.pop() else: break return score
33b0e4
89ce3d
You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. Each token may be played at most once and in any order. You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens.   Example 1: Input: tokens = [100], power = 50 Output: 0 Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. Example 2: Input: tokens = [100,200], power = 150 Output: 1 Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. Example 3: Input: tokens = [100,200,300,400], power = 200 Output: 2 Explanation: Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.   Constraints: 0 <= tokens.length <= 1000 0 <= tokens[i], power < 10000
class Solution: def bagOfTokensScore(self, a, P): """ :type tokens: List[int] :type P: int :rtype: int """ ans = 0 a = sorted(a) if (not a) or a[0] > P: return 0 n = len(a) s = [0] for i in range(n): s += [s[-1] + a[i]] for t in range(n): #print(P + s[n] - s[n - t], s[n - t]) if P + s[n] - s[n - t] >= s[n - t]: ans = max(ans, n - t - t) if P + s[n] - s[n - t] >= s[n - t - 1]: ans = max(ans, n - t - t - 1) return ans
19a239
6cc61f
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.   Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST.   Constraints: The number of nodes in the tree is in the range [1, 4 * 10000]. -4 * 10000 <= Node.val <= 4 * 10000
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxSumBST(self, root: TreeNode) -> int: if root == None: return True ans = -1600000000 def travell(root): nonlocal ans ffst, llst, sm, canbe = None, None, root.val, True if root.left != None: tp = travell(root.left) if ffst == None: ffst = tp[0] llst = tp[1] sm += tp[2] if tp[1] >= root.val or not tp[3]: canbe = False if ffst == None: ffst = root.val llst = root.val if root.right != None: tp = travell(root.right) if ffst == None: ffst = tp[0] llst = tp[1] sm += tp[2] if tp[0] <= root.val or not tp[3]: canbe = False if canbe: ans = max(ans, sm) return ffst, llst, sm, canbe travell(root) return max(0, ans)
8a957e
6cc61f
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.   Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST.   Constraints: The number of nodes in the tree is in the range [1, 4 * 10000]. -4 * 10000 <= Node.val <= 4 * 10000
# 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 maxSumBST(self, root): self.ans = 0 def dfs(node): if not node: return [True,float('inf'),float('-inf'), 0] # valid, min, max, sum left = dfs(node.left) right = dfs(node.right) valid = left[0] and right[0] and (left[2] < node.val < right[1]) ans = [valid, min(left[1], node.val), max(right[2], node.val), left[3] + right[3] + node.val] if valid and ans[-1] > self.ans: self.ans = ans[-1] return ans dfs(root) return self.ans
5ea23a
7d6503
An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.   Example 1: Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]] Output: [false,true] Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. Example 2: Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]] Output: [true,false] Exaplanation: The above figure shows the given graph.   Constraints: 2 <= n <= 100000 1 <= edgeList.length, queries.length <= 100000 edgeList[i].length == 3 queries[j].length == 3 0 <= ui, vi, pj, qj <= n - 1 ui != vi pj != qj 1 <= disi, limitj <= 10^9 There may be multiple edges between two nodes.
class DSU: def __init__(self, N): self.par = list(range(N)) self.sz = [1] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return False if self.sz[xr] < self.sz[yr]: xr, yr = yr, xr self.par[yr] = xr self.sz[xr] += self.sz[yr] return True def size(self, x): return self.sz[self.find(x)] class Solution(object): def distanceLimitedPathsExist(self, n, edgeList, queries): edgeList.sort(key=lambda z: z[2]) for i, query in enumerate(queries): query.append(i) queries.sort(key=lambda q: q[2]) ans = [False] * len(queries) i = 0 dsu = DSU(n) for p,q,limit,qid in queries: while i < len(edgeList) and edgeList[i][2] < limit: # print("!", edgeList[i], p,q,limit,qid) dsu.union(edgeList[i][0], edgeList[i][1]) i += 1 if dsu.find(p) == dsu.find(q): ans[qid] = True return ans
06ae7e
7d6503
An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.   Example 1: Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]] Output: [false,true] Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. Example 2: Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]] Output: [true,false] Exaplanation: The above figure shows the given graph.   Constraints: 2 <= n <= 100000 1 <= edgeList.length, queries.length <= 100000 edgeList[i].length == 3 queries[j].length == 3 0 <= ui, vi, pj, qj <= n - 1 ui != vi pj != qj 1 <= disi, limitj <= 10^9 There may be multiple edges between two nodes.
class Solution: def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]: inputs = [] n = 0 for e in edgeList: inputs.append([e[2], 1, e[0], e[1]]) n = max(n, e[0]+1, e[1]+1) for z, q in enumerate(queries): inputs.append([q[2], 0, q[0], q[1], z]) n = max(n, q[0]+1, q[1]+1) inputs.sort() fu = [0] * n for i in range(n): fu[i] = i def find(i): if fu[i] == i: return i fu[i] = find(fu[i]) return fu[i] def merge(i, j): i = find(i) j = find(j) if i != j: fu[i] = j out = [-1] * len(queries) for x in inputs: if x[1] == 1: merge(x[2], x[3]) else: i = x[2] j = x[3] out[x[4]] = (find(i) == find(j)) return out
47e40f
be09c4
Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. Example 2: Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. Example 3: Input: root = [1,2,3,4,6,5,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.   Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 1000
# 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 verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] pos=collections.defaultdict(list) def dfs(node,x,y): if node: pos[x,y].append(node.val) dfs(node.left,x-1,y-1) dfs(node.right,x+1,y-1) dfs(root,0,0) keys=list(pos.keys()) keys=sorted(keys,key=lambda x: (x[0],-x[1])) x=keys[0][0] cur=[] ans=[] for key in keys: if key[0]==x: cur.extend(sorted(pos[key])) else: ans.append(cur) x=key[0] cur=sorted(pos[key]) if cur: ans.append(cur) return ans
4b2fa5
be09c4
Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. Example 2: Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. Example 3: Input: root = [1,2,3,4,6,5,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.   Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 1000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import defaultdict class Solution: def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]': d = defaultdict(lambda: defaultdict(list)) def f(n, x, y): if not n: return d[x][y].append(n.val) f(n.left, x-1, y-1) f(n.right, x+1, y-1) f(root, 0, 0) return [[v for k,vs in sorted(v.items(), key=lambda kv: -kv[0]) for v in sorted(vs)] for k,v in sorted(d.items())]
83d240
24e7f0
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a graph, and assuming both players play optimally, return 1 if the mouse wins the game, 2 if the cat wins the game, or 0 if the game is a draw.   Example 1: Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] Output: 0 Example 2: Input: graph = [[1,3],[0],[3],[0,2]] Output: 1   Constraints: 3 <= graph.length <= 50 1 <= graph[i].length < graph.length 0 <= graph[i][j] < graph.length graph[i][j] != i graph[i] is unique. The mouse and the cat can always move. 
class Solution: def catMouseGame(self, graph): """ :type graph: List[List[int]] :rtype: int """ memo = {} def move(ci, mi, mt): key = (ci, mi, mt) if key in memo: return memo[key] memo[key] = 0 if not mt: #cats turn for nxtmove in graph[ci]: if nxtmove == mi: memo[key] = 2 return 2 res = 1 for nxtmove in graph[ci]: if nxtmove == 0: continue tmp = move(nxtmove, mi, True) if tmp == 2: res =2 break if tmp == 0: res = 0 memo[key] = res return res #mouse True for nxtmove in graph[mi]: if nxtmove == 0: memo[key] = 1 return 1 res = 2 for nxtmove in graph[mi]: if nxtmove != ci: tmp = move(ci, nxtmove, False) if tmp == 1: res = 1 break if tmp == 0: res = 0 memo[key] = res return res return move(2, 1, True)