sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
d76950
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(object): def catMouseGame(self, graph): """ :type graph: List[List[int]] :rtype: int """ cache = set() path = collections.defaultdict(list) for i in range(len(graph)): path[i] = graph[i] #print path cache2 = {} def helper(path, i, j, turn, cache): # print i, j, turn, step if (i, j, turn) in cache: return 0 if (i, j, turn) in cache2: return cache2[(i, j, turn)] cache.add((i, j, turn)) if turn == "m": if 0 in path[i]: return 1 isDraw = False for nxt in path[i]: if nxt == j: continue cache3 = set(cache) tmp = helper(path, nxt, j, "c", cache3) if tmp == 1: cache2[(i, j, turn)] = 1 return 1 elif tmp == 0: isDraw = True if not isDraw: cache2[(i, j, turn)] = 2 return 2 cache2[(i, j, turn)] = 0 return 0 if i in path[j]: return 2 isDraw = False for nxt in path[j]: if nxt == 0: continue cache3 = set(cache) tmp = helper(path, i, nxt, "m", cache3) if tmp == 2: cache2[(i, j, turn)] = 2 return 2 elif tmp == 0: isDraw = True if not isDraw: cache2[(i, j, turn)] = 1 return 1 cache2[(i, j, turn)] = 0 return 0 return helper(path, 1, 2, "m", cache)
c77f15
6aa387
This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules: If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps. If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board. You need to perform the above rules until the board becomes stable, then return the stable board. Example 1: Input: board = [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]] Output: [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]] Example 2: Input: board = [[1,3,5,5,2],[3,4,3,3,1],[3,2,4,5,2],[2,4,4,5,5],[1,4,4,1,1]] Output: [[1,3,0,0,0],[3,4,0,5,2],[3,2,0,3,1],[2,4,0,5,2],[1,4,3,1,1]] Constraints: m == board.length n == board[i].length 3 <= m, n <= 50 1 <= board[i][j] <= 2000
class Solution: def candyCrush(self, board): """ :type board: List[List[int]] :rtype: List[List[int]] """ xlen = len(board[0]) ylen = len(board) while True: crushed_some = False crushed = [[False for i in range(xlen)] for j in range(ylen)] for j in range(ylen): typ = -1 nliketyp = 0 for i in range(xlen): if board[j][i] == typ: nliketyp += 1 else: if nliketyp >= 3 and typ > 0: #print(nliketyp) for di in range(nliketyp): crushed[j][i-di-1] = True crushed_some = True typ = board[j][i] nliketyp = 1 if nliketyp >= 3 and typ > 0: #print(nliketyp) for di in range(nliketyp): crushed[j][xlen-di-1] = True crushed_some = True for i in range(xlen): typ = -1 nliketyp = 0 for j in range(ylen): if board[j][i] == typ: nliketyp += 1 else: if nliketyp >= 3 and typ > 0: #print(nliketyp) for dj in range(nliketyp): crushed[j-dj-1][i] = True crushed_some = True typ = board[j][i] nliketyp = 1 if nliketyp >= 3 and typ > 0: #print(nliketyp) for dj in range(nliketyp): crushed[ylen-dj-1][i] = True crushed_some = True #print(crushed) if not crushed_some: break for i in range(xlen): wj = ylen-1 for j in range(ylen-1, -1, -1): if crushed[j][i]: continue board[wj][i] = board[j][i] wj -= 1 for j in range(wj, -1, -1): board[j][i] = 0 #break return board
c6e1df
6aa387
This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules: If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps. If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board. You need to perform the above rules until the board becomes stable, then return the stable board. Example 1: Input: board = [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]] Output: [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]] Example 2: Input: board = [[1,3,5,5,2],[3,4,3,3,1],[3,2,4,5,2],[2,4,4,5,5],[1,4,4,1,1]] Output: [[1,3,0,0,0],[3,4,0,5,2],[3,2,0,3,1],[2,4,0,5,2],[1,4,3,1,1]] Constraints: m == board.length n == board[i].length 3 <= m, n <= 50 1 <= board[i][j] <= 2000
class Solution(object): def candyCrush(self, board): """ :type board: List[List[int]] :rtype: List[List[int]] """ from numpy import array,zeros_like board=array(board) while True: mask=zeros_like(board,dtype=bool) heng=(board[:,:-2]==board[:,1:-1])*((board[:,2:]==board[:,1:-1]))*(board[:,1:-1]!=0) ids=heng.nonzero() mask[ids[0],ids[1]]=mask[ids[0],ids[1]+1]=mask[ids[0],ids[1]+2]=True shu=(board[:-2]==board[1:-1])*((board[2:]==board[1:-1]))*(board[1:-1]!=0) ids=shu.nonzero() mask[ids[0],ids[1]]=mask[ids[0]+1,ids[1]]=mask[ids[0]+2,ids[1]]=True if mask.sum()==0: return [[int(j) for j in i] for i in board] board[mask]=False for i in range(board.shape[1]): t=len(board[board[:,i]!=0,i]) if t==0: board[:,i]=0 continue board[-t:,i]=board[board[:,i]!=0,i] board[:-t,i]=0
3f1503
506eba
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.   Example 1: Input: arr = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is [1,5,7], so the answer is 13. Example 2: Input: grid = [[7]] Output: 7   Constraints: n == grid.length == grid[i].length 1 <= n <= 200 -99 <= grid[i][j] <= 99
class Solution: def minFallingPathSum(self, arr: List[List[int]]) -> int: m, n = len(arr), len(arr[0]) for i in range(1, m): a, b = sorted(arr[i - 1])[:2] for j in range(n): arr[i][j] += a if arr[i - 1][j] != a else b return min(arr[-1])
27e0f7
506eba
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.   Example 1: Input: arr = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is [1,5,7], so the answer is 13. Example 2: Input: grid = [[7]] Output: 7   Constraints: n == grid.length == grid[i].length 1 <= n <= 200 -99 <= grid[i][j] <= 99
class Solution(object): def minFallingPathSum(self, A): # min sum of falling path with nonzero shift dp = A.pop(0) N = len(dp) # dp[i] : currently minimum sum that ends here for row in A: m1 = min(dp) i1 = dp.index(m1) dp2 = [m1 + x for x in row] # dp2 is wrong at i1 m2 = float('inf') for j in xrange(N): if j != i1: x = dp[j] if x < m2: m2 = x dp2[i1] = m2 + row[i1] dp = dp2 return min(dp)
a96716
9df972
Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array.   Example 1: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] Example 2: Input: nums = [5], k = 9 Output: 0   Constraints: 1 <= nums.length <= 3 * 10000 -10000 <= nums[i] <= 10000 2 <= k <= 10000
class Solution: def subarraysDivByK(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ a = A n = len(a) k = K s = [0] for e in a: s.append(s[-1] + e) s = [e % k for e in s] import collections cnt = collections.Counter(s) ans = 0 for k, v in cnt.items(): if v >= 2: ans += v * (v - 1) // 2 return ans
af2eeb
9df972
Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array.   Example 1: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] Example 2: Input: nums = [5], k = 9 Output: 0   Constraints: 1 <= nums.length <= 3 * 10000 -10000 <= nums[i] <= 10000 2 <= k <= 10000
class Solution(object): def subarraysDivByK(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ sum_so_far = {0: 1} curr = 0 rtn = 0 for x in A: curr += x rtn += sum_so_far.get(curr % K, 0) if curr % K not in sum_so_far: sum_so_far[curr % K] = 1 else: sum_so_far[curr % K] += 1 return rtn
636318
6e80c3
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.   Example 1: Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]] Output: 4 Example 2: Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] Output: 2   Constraints: 1 <= points.length <= 500 points[i].length == 2 0 <= xi, yi <= 4 * 10000 All the given points are unique.
class Solution(object): def minAreaRect(self, points): """ :type points: List[List[int]] :rtype: int """ from collections import defaultdict ysforx = defaultdict(set) for x, y in points: ysforx[x].add(y) ans = 10 ** 100 keys = sorted(ysforx) n = len(keys) for i in range(n): for j in range(i + 1, n): ps = ysforx[keys[i]] & ysforx[keys[j]] ps = sorted(ps) mindiff = 10 ** 100 for x, y in zip(ps, ps[1:]): mindiff = min(mindiff, y - x) if mindiff < 10 ** 100: ans = min(ans, (keys[j] - keys[i]) * mindiff) return ans if ans < 10 ** 100 else 0
53095f
6e80c3
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.   Example 1: Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]] Output: 4 Example 2: Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] Output: 2   Constraints: 1 <= points.length <= 500 points[i].length == 2 0 <= xi, yi <= 4 * 10000 All the given points are unique.
class Solution: def minAreaRect(self, points): """ :type points: List[List[int]] :rtype: int """ points.sort() v = collections.defaultdict(set) h = collections.defaultdict(set) for x, y in points: v[x].add(y) h[y].add(x) ma = float('inf') # print(h) # print(v) for ix, (x, y) in enumerate(points): for j in range(ix + 1, len(points)): xp, yp = points[j] if xp != x and yp != y and (yp in v[x] and xp in h[y]): # print(x, xp, y, yp) ma = min(ma, abs(y-yp) * abs(x-xp)) return ma if (ma != float('inf')) else 0
837fde
012ef2
You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: num = "327" Output: 2 Explanation: You could have written down the numbers: 3, 27 327 Example 2: Input: num = "094" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive. Example 3: Input: num = "0" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive.   Constraints: 1 <= num.length <= 3500 num consists of digits '0' through '9'.
class Solution: def numberOfCombinations(self, num: str) -> int: mod = 10 ** 9 + 7 n = len(num) dp = [deque() for _ in range(n+1)] dp[n].append([inf, 1]) su = [0] * (n+1) su[n] = 1 for i in range(n-1, -1, -1): if num[i] == '0': continue a = 0 for j in range(i, n): a = a * 10 + int(num[j]) while dp[j+1] and dp[j+1][0][0] < a: _, m = dp[j+1].popleft() su[j+1] = (su[j+1] - m + mod) % mod dp[i].append([a, su[j+1]]) su[i] = (su[i] + su[j+1]) % mod if j+1 < n and num[j+1] != '0' and su[j+1] == 0: # print(i, j, num[i:j], num[j+1:]) su[i] = (su[i] + 1) % mod dp[i].append([int(num[i:]), 1]) break return su[0]
e7adf5
012ef2
You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: num = "327" Output: 2 Explanation: You could have written down the numbers: 3, 27 327 Example 2: Input: num = "094" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive. Example 3: Input: num = "0" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive.   Constraints: 1 <= num.length <= 3500 num consists of digits '0' through '9'.
class Solution(object): def numberOfCombinations(self, num): """ :type num: str :rtype: int """ mod = 1000000007 n = len(num) dp2 = [[0]*(n+1) for _ in range(n)] i=n-1 while i>=0: j=n-1 while j>i: if num[i]!=num[j]: dp2[i][j]=0 else: dp2[i][j]=1+dp2[i+1][j+1] j-=1 i-=1 dp = [[0]*(n+1) for _ in range(n)] i = n-1 while i>=0: if num[i]!='0': d=n-i dp[i][d]=1 d-=1 while d>0: r = dp[i][d+1] j = i+d if num[j]!='0' and j+d<=n: kk = dp2[i][j] if kk>=d or num[i+kk]<num[j+kk]: nd=d else: nd=d+1 if j+nd<=n: r+=dp[j][nd] r%=mod dp[i][d]=r d-=1 i-=1 """ def dfs(i, d): j=i+d if j==n: return 1 if j>n: return 0 k = (i, d) if k in dp: return dp[k] r = dfs(i, d+1) if num[j]!='0' and j+d<=n: kk = dp2[i][j] if kk>=d or num[i+kk]<num[j+kk]: nd=d else: nd=d+1 if j+nd<=n: r += dfs(j, nd) r %= mod dp[k]=r return r """ rc = 0 if num[0]=='0': rc = 0 else: rc = dp[0][1] return rc
759c86
1ec1a1
There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.   Example 1: Input: stones = [3,2,4,1], k = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible. Example 2: Input: stones = [3,2,4,1], k = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. Example 3: Input: stones = [3,5,1,2,6], k = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.   Constraints: n == stones.length 1 <= n <= 30 1 <= stones[i] <= 100 2 <= k <= 30
class Solution(object): def mergeStones(self, stones, K): """ :type stones: List[int] :type K: int :rtype: int """ n = len(stones) ps = [0] * (n + 1) for i, j in enumerate(stones): ps[i + 1] = ps[i] + j dp = [[[float('inf')] * (K + 1) for i in range(n + 1)] for j in range(n)] for i in range(n - 1, -1, -1): dp[i][i + 1][1] = 0 for j in range(i + 2, n + 1): if j - i <= K: dp[i][j][j - i] = 0 for k in range(2, min(K + 1, j - i)): for p in range(i + 1, j): dp[i][j][k] = min(dp[i][j][k], dp[i][p][k - 1] + dp[p][j][1]) dp[i][j][1] = dp[i][j][K] + ps[j] - ps[i] ret = dp[0][n][1] return -1 if ret == float('inf') else ret
1e7110
1ec1a1
There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.   Example 1: Input: stones = [3,2,4,1], k = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible. Example 2: Input: stones = [3,2,4,1], k = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. Example 3: Input: stones = [3,5,1,2,6], k = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.   Constraints: n == stones.length 1 <= n <= 30 1 <= stones[i] <= 100 2 <= k <= 30
class Solution: def mergeStones(self, stones: List[int], K: int) -> int: n = len(stones) if n == 1: return 0 if (n - 1) % (K - 1): return -1 ps = [0] for a in stones: ps.append(ps[-1] + a) INF = float('inf') cache = {} def find(l, r, m): if m == 1 and r - l == 1: return 0 if (l, r, m) not in cache: tmp = INF for i in range(l+1, r, K - 1): cl = find(l, i, 1) cr = find(i, r, m - 1 if m > 1 else K - 1) tmp = min(tmp, cl + cr) cache[(l, r, m)] = tmp + (ps[r] - ps[l] if m == 1 else 0) return cache[(l, r, m)] return find(0, n, 1)
b30b5d
db5e89
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity. void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity. int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty. int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.   Example 1: Input ["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"] [[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []] Output [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1] Explanation: DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 D.push(1); D.push(2); D.push(3); D.push(4); D.push(5); // The stacks are now: 2 4 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 2. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.push(20); // The stacks are now: 20 4 1 3 5 ﹈ ﹈ ﹈ D.push(21); // The stacks are now: 20 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 20. The stacks are now: 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(2); // Returns 21. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.pop() // Returns 5. The stacks are now: 4 1 3 ﹈ ﹈ D.pop() // Returns 4. The stacks are now: 1 3 ﹈ ﹈ D.pop() // Returns 3. The stacks are now: 1 ﹈ D.pop() // Returns 1. There are no stacks. D.pop() // Returns -1. There are still no stacks.   Constraints: 1 <= capacity <= 2 * 10000 1 <= val <= 2 * 10000 0 <= index <= 100000 At most 2 * 100000 calls will be made to push, pop, and popAtStack.
class DinnerPlates(object): def __init__(self, capacity): """ :type capacity: int """ self.c = capacity self.stack = [] self.n = [] def push(self, val): """ :type val: int :rtype: None """ if self.n: index = heapq.heappop(self.n) if index >= len(self.stack): self.stack.append([]) index = len(self.stack) - 1 self.stack[index].append(val) if len(self.stack[index]) < self.c: heapq.heappush(self.n, index) else: self.stack.append([]) self.stack[-1].append(val) self.n.append(len(self.stack) - 1) def pop(self): """ :rtype: int """ while self.stack and not self.stack[-1]: self.stack.pop() if self.stack: if len(self.stack[-1]) == self.c: heapq.heappush(self.n, len(self.stack)-1) return self.stack[-1].pop() else: return -1 def popAtStack(self, index): """ :type index: int :rtype: int """ if index < len(self.stack): s = self.stack[index] if s: if len(s) == self.c: heapq.heappush(self.n, index) return s.pop() else: return -1 else: return -1 # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = obj.popAtStack(index)
4c8579
db5e89
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity. void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity. int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty. int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.   Example 1: Input ["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"] [[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []] Output [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1] Explanation: DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 D.push(1); D.push(2); D.push(3); D.push(4); D.push(5); // The stacks are now: 2 4 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 2. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.push(20); // The stacks are now: 20 4 1 3 5 ﹈ ﹈ ﹈ D.push(21); // The stacks are now: 20 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 20. The stacks are now: 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(2); // Returns 21. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.pop() // Returns 5. The stacks are now: 4 1 3 ﹈ ﹈ D.pop() // Returns 4. The stacks are now: 1 3 ﹈ ﹈ D.pop() // Returns 3. The stacks are now: 1 ﹈ D.pop() // Returns 1. There are no stacks. D.pop() // Returns -1. There are still no stacks.   Constraints: 1 <= capacity <= 2 * 10000 1 <= val <= 2 * 10000 0 <= index <= 100000 At most 2 * 100000 calls will be made to push, pop, and popAtStack.
class DinnerPlates: def __init__(self, capacity: int): self.capacity = capacity self.first_not_full = 0 self.last_has_value = 0 self.stacks = {0:[]} def push(self, val: int) -> None: self.stacks[self.first_not_full].append(val) self.checkPointer() def pop(self) -> int: return self.popAtStack(self.last_has_value) def popAtStack(self, index: int) -> int: stack = self.stacks.get(index, []) ret = -1 if len(stack): ret = stack.pop(-1) self.first_not_full = min(self.first_not_full, index) self.checkPointer() return ret def checkPointer(self): while len(self.stacks[self.first_not_full]) == self.capacity: self.first_not_full += 1 if self.first_not_full not in self.stacks: self.stacks[self.first_not_full] = [] break self.last_has_value = max(self.last_has_value, self.first_not_full) while self.last_has_value and len(self.stacks[self.last_has_value]) is 0: self.last_has_value -= 1 # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = obj.popAtStack(index)
b2c7c4
6b6218
You are given an integer array nums and an integer k. Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split. Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed. For example, trimmed([3,1,2,4,3,4]) = [3,4,3,4]. The importance value of a subarray is k + trimmed(subarray).length. For example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].The importance value of this subarray will be k + 5. Return the minimum possible cost of a split of nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,2,1,2,1,3,3], k = 2 Output: 8 Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. Example 2: Input: nums = [1,2,1,2,1], k = 2 Output: 6 Explanation: We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. Example 3: Input: nums = [1,2,1,2,1], k = 5 Output: 10 Explanation: We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < nums.length 1 <= k <= 10^9  
class Solution: def minCost(self, nums: List[int], k: int) -> int: n = len(nums) dp = [0] oo = 0 comp = [] d = dict() for v in nums: if v not in d: d[v] = oo oo += 1 comp.append(d[v]) for i in range(n): app = [0] * n poss = [] sz = 0 for j in range(i, -1, -1): app[comp[j]] += 1 if app[comp[j]] == 2: sz += 2 elif app[comp[j]] > 2: sz += 1 poss.append(dp[j] + k + sz) dp.append(min(poss)) return dp[-1]
40b0c2
6b6218
You are given an integer array nums and an integer k. Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split. Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed. For example, trimmed([3,1,2,4,3,4]) = [3,4,3,4]. The importance value of a subarray is k + trimmed(subarray).length. For example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].The importance value of this subarray will be k + 5. Return the minimum possible cost of a split of nums. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,2,1,2,1,3,3], k = 2 Output: 8 Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. Example 2: Input: nums = [1,2,1,2,1], k = 2 Output: 6 Explanation: We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. Example 3: Input: nums = [1,2,1,2,1], k = 5 Output: 10 Explanation: We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < nums.length 1 <= k <= 10^9  
from collections import Counter class Solution(object): def minCost(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ a = nums n = len(a) cost = [[float('inf')]*(n+1) for _ in xrange(n+1)] for i in xrange(n): c = Counter() d = 0 for j in xrange(i, n): c[a[j]] += 1 if c[a[j]] == 2: d += 2 elif c[a[j]] > 2: d += 1 cost[i][j+1] = k + d r = [float('inf')] * (n+1) r[0] = 0 for i in xrange(1, n+1): r[i] = min(r[j]+cost[j][i] for j in xrange(i)) return r[n]
2dac54
10c3e9
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.   Example 1: Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: The first group has [1,4], and the second group has [2,3]. Example 2: Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.   Constraints: 1 <= n <= 2000 0 <= dislikes.length <= 10000 dislikes[i].length == 2 1 <= ai < bi <= n All the pairs of dislikes are unique.
class Solution: def possibleBipartition(self, N, dislikes): """ :type N: int :type dislikes: List[List[int]] :rtype: bool """ edges = [[] for i in range(N)] for pair in dislikes: edges[pair[0]-1].append(pair[1]-1) edges[pair[1]-1].append(pair[0]-1) team = [-1 for i in range(N)] for i, p in enumerate(team): if p == -1: team[i] = 0 q = collections.deque() q.append(i) while len(q): pre = q.popleft() for j in edges[pre]: if team[j] == -1: team[j] = 1 - team[pre] q.append(j) elif team[j] == team[pre]: return False return True
f72fe9
10c3e9
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.   Example 1: Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: The first group has [1,4], and the second group has [2,3]. Example 2: Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.   Constraints: 1 <= n <= 2000 0 <= dislikes.length <= 10000 dislikes[i].length == 2 1 <= ai < bi <= n All the pairs of dislikes are unique.
class Solution(object): def possibleBipartition(self, N, dislikes): """ :type N: int :type dislikes: List[List[int]] :rtype: bool """ edges = [[] for _ in range(N)] for x, y in dislikes: edges[x-1].append(y-1) edges[y-1].append(x-1) color = [0] * N for i in range(N): if color[i] != 0: continue q = [i] color[i] = 1 while q: q2 = [] for x in q: for y in edges[x]: if color[y] == 0: color[y] = -color[x] q2.append(y) elif color[y] == color[x]: return False q = q2 return True
6c1f3d
a6ab06
You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total. growTime[i] is the number of full days it takes the ith seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever. From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming.   Example 1: Input: plantTime = [1,4,3], growTime = [2,3,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3. On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8. On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 2: Input: plantTime = [1,2,3,2], growTime = [2,1,2,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4. On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5. On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8. On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 3: Input: plantTime = [1], growTime = [1] Output: 2 Explanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2. Thus, on day 2, all the seeds are blooming.   Constraints: n == plantTime.length == growTime.length 1 <= n <= 100000 1 <= plantTime[i], growTime[i] <= 10000
class Solution: def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: pg = list(zip(growTime, plantTime)) pg.sort(reverse=True) time = 0 ans = 0 for g, p in pg: time += p ans = max(ans, time + g) return ans
668191
a6ab06
You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total. growTime[i] is the number of full days it takes the ith seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever. From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming.   Example 1: Input: plantTime = [1,4,3], growTime = [2,3,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3. On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8. On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 2: Input: plantTime = [1,2,3,2], growTime = [2,1,2,1] Output: 9 Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. One optimal way is: On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4. On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5. On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8. On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9. Thus, on day 9, all the seeds are blooming. Example 3: Input: plantTime = [1], growTime = [1] Output: 2 Explanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2. Thus, on day 2, all the seeds are blooming.   Constraints: n == plantTime.length == growTime.length 1 <= n <= 100000 1 <= plantTime[i], growTime[i] <= 10000
class Solution(object): def earliestFullBloom(self, plantTime, growTime): """ :type plantTime: List[int] :type growTime: List[int] :rtype: int """ a = plantTime b = growTime n = len(a) c = [(b[i], a[i]) for i in xrange(n)] c.sort(key=lambda (x, y): -x) r = s = 0 for x, y in c: s += y r = max(r, s+x) return r
3b2623
d729ae
The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary. The left boundary is the set of nodes defined by the following: The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is empty. If a node in the left boundary and has a left child, then the left child is in the left boundary. If a node is in the left boundary, has no left child, but has a right child, then the right child is in the left boundary. The leftmost leaf is not in the left boundary. The right boundary is similar to the left boundary, except it is the right side of the root's right subtree. Again, the leaf is not part of the right boundary, and the right boundary is empty if the root does not have a right child. The leaves are nodes that do not have any children. For this problem, the root is not a leaf. Given the root of a binary tree, return the values of its boundary. Example 1: Input: root = [1,null,2,3,4] Output: [1,3,4,2] Explanation: - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root's right child 2 -> 4. 4 is a leaf, so the right boundary is [2]. - The leaves from left to right are [3,4]. Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2]. Example 2: Input: root = [1,2,3,4,5,6,null,null,null,7,8,9,10] Output: [1,2,4,7,8,9,10,6,3] Explanation: - The left boundary follows the path starting from the root's left child 2 -> 4. 4 is a leaf, so the left boundary is [2]. - The right boundary follows the path starting from the root's right child 3 -> 6 -> 10. 10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3]. - The leaves from left to right are [4,7,8,9,10]. Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3]. Constraints: The number of nodes in the tree is in the range [1, 10000]. -1000 <= 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 boundaryOfBinaryTree(self, root): if not root: return [] lb =[root] cur = root.left while cur: lb.append(cur) if cur.left: cur = cur.left else: cur = cur.right rb=[root] cur=root.right while cur: rb.append(cur) if cur.right: cur = cur.right else:cur=cur.left leaves = [] stack = [root] while stack: node=stack.pop() if node.left and node.right: stack.append(node.right) stack.append(node.left) elif node.left: stack.append(node.left) elif node.right: stack.append(node.right) else: leaves.append(node) ans = [] ansset = set() def visit(node): if node not in ansset: ansset.add(node) ans.append(node.val) for x in lb: visit(x) for x in leaves: visit(x) for x in rb[::-1]: visit(x) return ans
01eed3
9d2ed3
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: 0 represents a wall that you cannot pass through. 1 represents an empty cell that you can freely move to and from. All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank). Price (lower price has a higher rank, but it must be in the price range). The row number (smaller row number has a higher rank). The column number (smaller column number has a higher rank). Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.   Example 1: Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3 Output: [[0,1],[1,1],[2,1]] Explanation: You start at (0,0). With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2). The ranks of these items are: - (0,1) with distance 1 - (1,1) with distance 2 - (2,1) with distance 3 - (2,2) with distance 4 Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1). Example 2: Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2 Output: [[2,1],[1,2]] Explanation: You start at (2,3). With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1). The ranks of these items are: - (2,1) with distance 2, price 2 - (1,2) with distance 2, price 3 - (1,1) with distance 3 - (0,1) with distance 4 Thus, the 2 highest ranked items in the price range are (2,1) and (1,2). Example 3: Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3 Output: [[2,1],[2,0]] Explanation: You start at (0,0). With a price range of [2,3], we can take items from (2,0) and (2,1). The ranks of these items are: - (2,1) with distance 5 - (2,0) with distance 6 Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). Note that k = 3 but there are only 2 reachable items within the price range.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100000 1 <= m * n <= 100000 0 <= grid[i][j] <= 100000 pricing.length == 2 2 <= low <= high <= 100000 start.length == 2 0 <= row <= m - 1 0 <= col <= n - 1 grid[row][col] > 0 1 <= k <= m * n
class Solution: def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]: n, m = len(grid), len(grid[0]) dist = [[-1]*m for i in range(n)] q = deque() q.append((start[0], start[1])) dist[start[0]][start[1]] = 0 while len(q): x, y = q.popleft() 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[i][j] and dist[i][j] == -1: dist[i][j] = dist[x][y]+1 q.append((i, j)) l = [] for i in range(n): for j in range(m): if dist[i][j] > -1 and pricing[0] <= grid[i][j] <= pricing[1]: l.append((dist[i][j], grid[i][j], i, j)) l.sort() return [i[2:] for i in l[:k]]
7228e5
9d2ed3
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: 0 represents a wall that you cannot pass through. 1 represents an empty cell that you can freely move to and from. All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank). Price (lower price has a higher rank, but it must be in the price range). The row number (smaller row number has a higher rank). The column number (smaller column number has a higher rank). Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.   Example 1: Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3 Output: [[0,1],[1,1],[2,1]] Explanation: You start at (0,0). With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2). The ranks of these items are: - (0,1) with distance 1 - (1,1) with distance 2 - (2,1) with distance 3 - (2,2) with distance 4 Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1). Example 2: Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2 Output: [[2,1],[1,2]] Explanation: You start at (2,3). With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1). The ranks of these items are: - (2,1) with distance 2, price 2 - (1,2) with distance 2, price 3 - (1,1) with distance 3 - (0,1) with distance 4 Thus, the 2 highest ranked items in the price range are (2,1) and (1,2). Example 3: Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3 Output: [[2,1],[2,0]] Explanation: You start at (0,0). With a price range of [2,3], we can take items from (2,0) and (2,1). The ranks of these items are: - (2,1) with distance 5 - (2,0) with distance 6 Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). Note that k = 3 but there are only 2 reachable items within the price range.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100000 1 <= m * n <= 100000 0 <= grid[i][j] <= 100000 pricing.length == 2 2 <= low <= high <= 100000 start.length == 2 0 <= row <= m - 1 0 <= col <= n - 1 grid[row][col] > 0 1 <= k <= m * n
class Solution(object): def highestRankedKItems(self, grid, pricing, start, k): """ :type grid: List[List[int]] :type pricing: List[int] :type start: List[int] :type k: int :rtype: List[List[int]] """ heap = [] m,n = len(grid),len(grid[0]) visited = [[False for _ in range(n)] for _ in range(m)] distances = [[float("inf") for _ in range(n)] for _ in range(m)] visited[start[0]][start[1]] = True level = [start] step = 0 while level: newlevel = [] for i,j in level: distances[i][j] = step for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]: x,y = i+dx,j+dy if 0<=x<m and 0<=y<n and grid[x][y]!=0 and not visited[x][y]: newlevel.append((x,y)) visited[x][y] = True level = newlevel step += 1 for i in range(m): for j in range(n): if visited[i][j] and grid[i][j]>=pricing[0] and grid[i][j]<=pricing[1]: # if len(heap)<k: # heapq.heappush(heap,(abs(i-start[0])+abs(j-start[1]),grid[i][j],i,j)) # else: heapq.heappush(heap,(distances[i][j],grid[i][j],i,j)) # print(heap) res = [] while heap and len(res)<k: rank,price,i,j = heapq.heappop(heap) res.append([i,j]) return res
46c23c
6d713c
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them.   Example 1: Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7] Example 2: Input: preorder = [1], postorder = [1] Output: [1]   Constraints: 1 <= preorder.length <= 30 1 <= preorder[i] <= preorder.length All the values of preorder are unique. postorder.length == preorder.length 1 <= postorder[i] <= postorder.length All the values of postorder are unique. It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructFromPrePost(self, pre, post): """ :type pre: List[int] :type post: List[int] :rtype: TreeNode """ def make(s, t): if not s: return None node = TreeNode(s[0]) if len(s) == 1: return node i = 0 while t[i] != s[1]: i += 1 node.left = make(s[1:i+2], t[:i+1]) node.right = make(s[i+2:], t[i+1:]) return node return make(pre, post)
917917
6d713c
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them.   Example 1: Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7] Example 2: Input: preorder = [1], postorder = [1] Output: [1]   Constraints: 1 <= preorder.length <= 30 1 <= preorder[i] <= preorder.length All the values of preorder are unique. postorder.length == preorder.length 1 <= postorder[i] <= postorder.length All the values of postorder are unique. It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
# 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 constructFromPrePost(self, pre, post): """ :type pre: List[int] :type post: List[int] :rtype: TreeNode """ if not pre: return None root = TreeNode(pre[0]) if len(pre) == 1: return root leftVal = pre[1] for i in range(len(post)): if post[i] == leftVal: break leftLen = i+1 leftPre = pre[1:1+leftLen] leftPost = post[:leftLen] rightPre = pre[1+leftLen:] rightPost = post[leftLen:-1] root.left = self.constructFromPrePost(leftPre, leftPost) root.right = self.constructFromPrePost(rightPre, rightPost) return root
84f102
bf81d8
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.   Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: ""   Constraints: 1 <= digits.length <= 10000 0 <= digits[i] <= 9
class Solution(object): def largestMultipleOfThree(self, digits): """ :type digits: List[int] :rtype: str """ digs=sorted(digits,reverse=True) rems=collections.defaultdict(list) sums=0 for d in digs: r=d%3 rems[r].append(d) sums+=r sums=sums%3 if sums==0: ans="".join([str(d) for d in digs]) elif sums==1: if len(rems[1])>0: de=rems[1].pop() digs.remove(de) ans="".join([str(d) for d in digs]) elif len(rems[2])>1: de1=rems[2].pop() de2=rems[2].pop() digs.remove(de1) digs.remove(de2) ans="".join([str(d) for d in digs]) else: return "" else: if len(rems[2])>0: de=rems[2].pop() digs.remove(de) ans="".join([str(d) for d in digs]) elif len(rems[1])>1: de1=rems[1].pop() de2=rems[1].pop() digs.remove(de1) digs.remove(de2) ans="".join([str(d) for d in digs]) else: return "" if not ans: return "" if ans[0]=="0": return "0" return ans
b04979
bf81d8
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.   Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: ""   Constraints: 1 <= digits.length <= 10000 0 <= digits[i] <= 9
class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: a = [[], [], []] for d in digits: a[d % 3].append(d) a[0].sort(reverse=True) a[1].sort(reverse=True) a[2].sort(reverse=True) s = sum(digits) k = s % 3 if k != 0: if len(a[k]) != 0: a[k].pop() else: assert len(a[3 - k]) >= 2 a[3 - k].pop() a[3 - k].pop() b = a[0] + a[1] + a[2] b.sort(reverse=True) if len(b) == 0: return '' elif b[0] == 0: return '0' else: return ''.join(map(str, b))
93eb76
2e2a8b
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: You choose any number of obstacles between 0 and i inclusive. You must include the ith obstacle in the course. You must put the chosen obstacles in the same order as they appear in obstacles. Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it. Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.   Example 1: Input: obstacles = [1,2,3,2] Output: [1,2,3,3] Explanation: The longest valid obstacle course at each position is: - i = 0: [1], [1] has length 1. - i = 1: [1,2], [1,2] has length 2. - i = 2: [1,2,3], [1,2,3] has length 3. - i = 3: [1,2,3,2], [1,2,2] has length 3. Example 2: Input: obstacles = [2,2,1] Output: [1,2,1] Explanation: The longest valid obstacle course at each position is: - i = 0: [2], [2] has length 1. - i = 1: [2,2], [2,2] has length 2. - i = 2: [2,2,1], [1] has length 1. Example 3: Input: obstacles = [3,1,5,6,4,2] Output: [1,1,2,3,2,2] Explanation: The longest valid obstacle course at each position is: - i = 0: [3], [3] has length 1. - i = 1: [3,1], [1] has length 1. - i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid. - i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid. - i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid. - i = 5: [3,1,5,6,4,2], [1,2] has length 2.   Constraints: n == obstacles.length 1 <= n <= 100000 1 <= obstacles[i] <= 10^7
class Solution: def longestObstacleCourseAtEachPosition(self, p: List[int]) -> List[int]: arr = [] res = [] for c in p: ind = bisect.bisect_right(arr,c) # print(ind) if ind>=len(arr): arr += [c] res += [len(arr)] else: arr[ind] = c res += [ind+1] return res
ec2079
2e2a8b
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: You choose any number of obstacles between 0 and i inclusive. You must include the ith obstacle in the course. You must put the chosen obstacles in the same order as they appear in obstacles. Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it. Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.   Example 1: Input: obstacles = [1,2,3,2] Output: [1,2,3,3] Explanation: The longest valid obstacle course at each position is: - i = 0: [1], [1] has length 1. - i = 1: [1,2], [1,2] has length 2. - i = 2: [1,2,3], [1,2,3] has length 3. - i = 3: [1,2,3,2], [1,2,2] has length 3. Example 2: Input: obstacles = [2,2,1] Output: [1,2,1] Explanation: The longest valid obstacle course at each position is: - i = 0: [2], [2] has length 1. - i = 1: [2,2], [2,2] has length 2. - i = 2: [2,2,1], [1] has length 1. Example 3: Input: obstacles = [3,1,5,6,4,2] Output: [1,1,2,3,2,2] Explanation: The longest valid obstacle course at each position is: - i = 0: [3], [3] has length 1. - i = 1: [3,1], [1] has length 1. - i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid. - i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid. - i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid. - i = 5: [3,1,5,6,4,2], [1,2] has length 2.   Constraints: n == obstacles.length 1 <= n <= 100000 1 <= obstacles[i] <= 10^7
class Solution(object): def longestObstacleCourseAtEachPosition(self, obstacles): """ :type obstacles: List[int] :rtype: List[int] """ a = obstacles n = len(a) s = sorted(set(a)) d = {v:i for i,v in enumerate(s)} m = len(s)+1 a = [d[i] for i in a] ans = [0] * n fen = [0] * (m+1) def _get(i): r = 0 while i: r = max(r, fen[i]) i -= i & -i return r def _upd(i, v): i += 1 while i <= m: fen[i] = max(fen[i], v) i += i & -i for i in xrange(n): v = _get(a[i]+1) + 1 _upd(a[i], v) ans[i] = v return ans
b0a775
c9e960
Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order.   Example 1: Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] Output: [[0,1],[2,3,4,5]] Explanation: The figure above describes the graph. The following figure shows all the possible MSTs: Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. Example 2: Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] Output: [[],[0,1,2,3]] Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.   Constraints: 2 <= n <= 100 1 <= edges.length <= min(200, n * (n - 1) / 2) edges[i].length == 3 0 <= ai < bi < n 1 <= weighti <= 1000 All pairs (ai, bi) are distinct.
class Solution: def findCriticalAndPseudoCriticalEdges(self, n: int, e: List[List[int]]) -> List[List[int]]: for i in range(len(e)): e[i].append(i) e.sort(key=lambda v:v[2]) def mst(a,ig): def root(n): if a[n]==n: return n a[n]=root(a[n]) return a[n] w=0 for vv in e: if vv[3]==ig: continue u,v=root(vv[0]),root(vv[1]) if u==v: continue w+=vv[2] a[u]=v for i in range(n): if root(i) != root(0): return 1<<30 return w self.ms=mst([k for k in range(n)],-1) print(self.ms) def cric(): ans=[] for i in range(len(e)): a=[j for j in range(n)] v=mst(a,i) if self.ms<v: # print(a,i,v) ans.append(i) return ans def pcric(): ans=[] for vv in e: a=[j for j in range(n)] a[vv[0]]=vv[1] if self.ms==mst(a,vv[3])+vv[2]: ans.append(vv[3]) return ans cr=cric() pcr=pcric() d={x for x in cr} ppcr=[] for x in pcr: if x in d: continue ppcr.append(x) return [cr,ppcr]
2f61f1
c9e960
Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order.   Example 1: Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] Output: [[0,1],[2,3,4,5]] Explanation: The figure above describes the graph. The following figure shows all the possible MSTs: Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. Example 2: Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] Output: [[],[0,1,2,3]] Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.   Constraints: 2 <= n <= 100 1 <= edges.length <= min(200, n * (n - 1) / 2) edges[i].length == 3 0 <= ai < bi < n 1 <= weighti <= 1000 All pairs (ai, bi) are distinct.
class Solution(object): def findCriticalAndPseudoCriticalEdges(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[List[int]] """ gid = [0]*(n+1) gc = [0]*(n+1) def findg(g): while gid[g]!=g: g=gid[g] return g ne = sorted([(e[2], e[0], e[1], i) for i,e in enumerate(edges)]) m = len(edges) mk = [0]*m for i in range(-1, m): for j in range(n): gid[j]=j gc[j]=1 c, ww = n, 0 for k in range(m): if k==i: continue w, a, b, _ = ne[k] ga, gb = findg(a), findg(b) if ga==gb: continue if gc[ga]>gc[gb]: gid[gb]=ga; gc[ga]+=gc[gb] else: gid[ga]=gb gc[gb]+=gc[ga] c-=1 ww += w if i==-1: mw=ww else: if c!=1 or mw!=ww: mk[ne[i][3]] |= 1 for i in range(m): for j in range(n): gid[j]=j gc[j]=1 w, a, b, ii = ne[i] gid[a]=b gc[b]+=gc[a] c, ww = n-1, w for k in range(m): if k==i: continue w, a, b, _ = ne[k] ga, gb = findg(a), findg(b) if ga==gb: continue if gc[ga]>gc[gb]: gid[gb]=ga; gc[ga]+=gc[gb] else: gid[ga]=gb gc[gb]+=gc[ga] c-=1 ww += w if mw==ww: mk[ii] |= 2 r1, r2 = [], [] for i in range(m): if mk[i] & 1: r1.append(i) elif mk[i]&2: r2.append(i) return [r1,r2]
66db40
a08e7a
There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.   Example 1: Input: row = [0,2,1,3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3,2,0,1] Output: 0 Explanation: All couples are already seated side by side.   Constraints: 2n == row.length 2 <= n <= 30 n is even. 0 <= row[i] < 2n All the elements of row are unique.
class Solution(object): def minSwapsCouples(self, row): """ :type row: List[int] :rtype: int """ def matcher(x): if x%2 == 0: return x+1 return x-1 ans = 0 for i in range(0, len(row), 2): need = matcher(row[i]) if need == row[i+1]: continue t = next(i for i in range(len(row)) if row[i] == need) row[i+1], row[t] = row[t], row[i+1] ans += 1 return ans
e61815
a08e7a
There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.   Example 1: Input: row = [0,2,1,3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3,2,0,1] Output: 0 Explanation: All couples are already seated side by side.   Constraints: 2n == row.length 2 <= n <= 30 n is even. 0 <= row[i] < 2n All the elements of row are unique.
class Solution: def minSwapsCouples(self, row): """ :type row: List[int] :rtype: int """ s=[i//2 for i in row] ans=0 n=len(s) for i in range(1,n,2): if s[i]!=s[i-1]: p=s.index(s[i-1],i) s[p]=s[i] s[i]=s[i-1] ans+=1 return ans
aefc1e
236464
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.   Example 1: Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]] Example 2: Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]]   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 10000 1 <= m * n <= 10000 mat[i][j] is either 0 or 1. There is at least one 0 in mat.
from collections import deque class Solution(object): def updateMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if len(matrix) == 0: return matrix q = deque() for y in range(len(matrix)): for x in range(len(matrix[0])): if matrix[y][x] == 0: q.append((y, x)) else: matrix[y][x] = 10000 while len(q): y, x = q.popleft() for j, i in [(y,x+1), (y,x-1), (y+1,x), (y-1,x)]: if 0 <= j < len(matrix) and 0 <= i < len(matrix[0]) and matrix[j][i] > matrix[y][x]+1: matrix[j][i] = matrix[y][x]+1 q.append((j, i)) return matrix
0fd41a
edaac9
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 node i, then edges[i] == -1. Return the length of the longest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node.   Example 1: Input: edges = [3,3,4,2,3] Output: 3 Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2. The length of this cycle is 3, so 3 is returned. Example 2: Input: edges = [2,-1,3,1] Output: -1 Explanation: There are no cycles in this graph.   Constraints: n == edges.length 2 <= n <= 100000 -1 <= edges[i] < n edges[i] != i
class Solution: def longestCycle(self, edges): sol = -1 visited = set() for node in range(len(edges)): i = 0 position = {} while node != -1 and node not in visited: position[node] = i visited.add(node) node = edges[node] i += 1 if node != -1 and node in position: sol = max(sol, i - position[node]) return sol
ce1840
edaac9
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 node i, then edges[i] == -1. Return the length of the longest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node.   Example 1: Input: edges = [3,3,4,2,3] Output: 3 Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2. The length of this cycle is 3, so 3 is returned. Example 2: Input: edges = [2,-1,3,1] Output: -1 Explanation: There are no cycles in this graph.   Constraints: n == edges.length 2 <= n <= 100000 -1 <= edges[i] < n edges[i] != i
class Solution(object): def longestCycle(self, edges): """ :type edges: List[int] :rtype: int """ v, m, r = [False] * len(edges), {}, [-1] def d(n, c): if n in m: r[0] = max(r[0], c - m[n]) elif n > -1 and not v[n]: v[n], m[n] = True, c d(edges[n], c + 1) for i in range(len(edges)): if not v[i]: m = {} d(i, 0) return r[0]
776fae
cc839a
You are given a 0-indexed positive integer array nums and a positive integer k. A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Both the numbers num1 and num2 exist in the array nums. The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation. Return the number of distinct excellent pairs. Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.   Example 1: Input: nums = [1,2,3,1], k = 3 Output: 5 Explanation: The excellent pairs are the following: - (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3. - (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. - (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. So the number of excellent pairs is 5. Example 2: Input: nums = [5,1,1], k = 10 Output: 0 Explanation: There are no excellent pairs for this array.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= k <= 60
from typing import List class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: li = [] for num in set(nums): li.append(sum(c == '1' for c in bin(num)[2:])) li.sort() n = len(li) idx = n ans = 0 for i in range(n): while idx > 0 and li[idx - 1] + li[i] >= k: idx -= 1 ans += n - idx return ans
63eaa6
cc839a
You are given a 0-indexed positive integer array nums and a positive integer k. A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Both the numbers num1 and num2 exist in the array nums. The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation. Return the number of distinct excellent pairs. Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.   Example 1: Input: nums = [1,2,3,1], k = 3 Output: 5 Explanation: The excellent pairs are the following: - (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3. - (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. - (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. So the number of excellent pairs is 5. Example 2: Input: nums = [5,1,1], k = 10 Output: 0 Explanation: There are no excellent pairs for this array.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= k <= 60
class Solution(object): def countExcellentPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ digits = [] n = len(nums) repeat = {} for i in range(n): if nums[i] in repeat: continue repeat[nums[i]] = 1 s = bin(nums[i])[2:] tot = 0 for c in s: tot += int(c) digits.append(tot) n = len(digits) digits.sort() # print(digits) ans = 0 for i in range(n): ans += n - bisect.bisect_left(digits,k - digits[i]) # print(ans) return ans
8165b4
70bfc8
You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array.   Example 1: Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. Example 2: Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.   Constraints: 1 <= arr.length <= 2000 0 <= arr[i] <= 10^8
class Solution(object): def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ aSorted = sorted(arr) ans = 1 end = 0 mem = {} for i in range(len(aSorted)): if i > end: ans += 1 targetIdx = None start = 0 if aSorted[i] not in mem else mem[aSorted[i]] for j in range(start, len(arr)): if arr[j] == aSorted[i]: targetIdx = j mem[aSorted[i]] = targetIdx+1 break if targetIdx > end: end = targetIdx return ans
2210c4
70bfc8
You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array.   Example 1: Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. Example 2: Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.   Constraints: 1 <= arr.length <= 2000 0 <= arr[i] <= 10^8
class Solution: def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ N = len(arr) idx = list(range(N)) idx.sort(key=lambda x: arr[x]) # print(idx) seg = 0 rChk = 0 for i in range(N): if idx[i] > seg: seg = idx[i] elif i == seg: rChk += 1 seg = i+1 return rChk
3b81bf
a0929a
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).   Example 1: Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= nums.length <= 1000 0 <= nums[i] <= 500
from collections import defaultdict class Solution(object): def longestArithSeqLength(self, A): """ :type A: List[int] :rtype: int """ best = defaultdict(int) for i, a in enumerate(A): for j in xrange(i): d = a - A[j] best[(i,d)] = max(best[(i,d)], 1+best[(j,d)]) return max(best.itervalues()) + 1
97d803
a0929a
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).   Example 1: Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= nums.length <= 1000 0 <= nums[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: n = len(A) dp = [collections.Counter() for _ in range(n)] ans = 0 for i in range(n): for j in range(i - 1, -1, -1): dp[i][A[i] - A[j]] = max(dp[i][A[i] - A[j]], dp[j][A[i] - A[j]] + 1) ans = max(ans, dp[i][A[i] - A[j]]) return ans + 1
b2c8a1
660ca0
A generic microwave supports cooking times for: at least 1 second. at most 99 minutes and 99 seconds. To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds. You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds. You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds. You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds. You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds.   Example 1: Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600 Output: 6 Explanation: The following are the possible ways to set the cooking time. - 1 0 0 0, interpreted as 10 minutes and 0 seconds.   The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).   The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost. - 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.   The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12. - 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.   The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9. Example 2: Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 Output: 6 Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds. The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6 Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.   Constraints: 0 <= startAt <= 9 1 <= moveCost, pushCost <= 100000 1 <= targetSeconds <= 6039
class Solution: def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int: def get_cost(digits): current = startAt cost = 0 for d in digits: if d != current: cost += moveCost current = d cost += pushCost return cost def get_digits(minutes, seconds): if minutes == 0: if seconds < 10: return [seconds] else: return [seconds // 10, seconds % 10] elif minutes < 10: return [minutes, seconds // 10, seconds % 10] else: return [minutes // 10, minutes % 10, seconds // 10, seconds % 10] minutes, seconds = divmod(targetSeconds, 60) ans = float('inf') if minutes < 100: ans = get_cost(get_digits(minutes, seconds)) if minutes >= 1 and seconds + 60 < 100: ans = min(ans, get_cost(get_digits(minutes - 1, seconds + 60))) return ans
c26cc7
660ca0
A generic microwave supports cooking times for: at least 1 second. at most 99 minutes and 99 seconds. To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds. You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds. You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds. You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds. You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds.   Example 1: Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600 Output: 6 Explanation: The following are the possible ways to set the cooking time. - 1 0 0 0, interpreted as 10 minutes and 0 seconds.   The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).   The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost. - 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.   The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12. - 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.   The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).   The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9. Example 2: Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 Output: 6 Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds. The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6 Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.   Constraints: 0 <= startAt <= 9 1 <= moveCost, pushCost <= 100000 1 <= targetSeconds <= 6039
class Solution(object): def minCostSetTime(self, startAt, moveCost, pushCost, targetSeconds): """ :type startAt: int :type moveCost: int :type pushCost: int :type targetSeconds: int :rtype: int """ rr = 1000000 s = startAt ds = [0]*4 def count(): s=startAt i=0 r = 0 while i<4: if ds[i]: break i+=1 while i<4: if s!=ds[i]: r+=moveCost s=ds[i] r+=pushCost i+=1 return r m=0 while True: if m*60>targetSeconds: break if m>=100: break s=targetSeconds-m*60 ds[0]=m/10; ds[1]=m%10 if s<100: ds[2]=s/10 ds[3]=s%10 rr=min(rr, count()) m+=1 return rr
48e148
1d0fab
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.   Example 1: Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. Example 2: Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: All 1s are either on the boundary or can reach the boundary.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 500 grid[i][j] is either 0 or 1.
class Solution: def numEnclaves(self, A: List[List[int]]) -> int: def dfs(r, c): if 0 <= r < len(A) and 0 <= c < len(A[0]) and A[r][c] == 1: A[r][c] = 0 for newr, newc in (r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1): dfs(newr, newc) # for i, row in enumerate(A): # for j, val in enumerate(row): # if i == 0 or i == len(A) - 1 or j == 0 or j == len(A[0]) - 1: # dfs(i, j) m, n = len(A), len(A[0]) for j in range(n): dfs(0, j) dfs(m - 1, j) for i in range(m): dfs(i, 0) dfs(i, n - 1) return sum(val == 1 for row in A for val in row)
7dd220
1d0fab
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.   Example 1: Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. Example 2: Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: All 1s are either on the boundary or can reach the boundary.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 500 grid[i][j] is either 0 or 1.
class Solution(object): def numEnclaves(self, A): """ :type A: List[List[int]] :rtype: int """ n = len(A) m = len(A[0]) cnt = sum(sum(i) for i in A) b = collections.deque([(0, i) for i in range(m) if A[0][i]] + [(n - 1, i) for i in range(m) if A[n - 1][i]] + [(j, 0) for j in range(1, n - 1) if A[j][0]] + [(j, m - 1) for j in range(1, n - 1) if A[j][m - 1]]) for i in range(m): A[0][i] = A[n - 1][i] = 0 for j in range(n): A[j][0] = A[j][m - 1] =0 dx, dy = [-1, 0, 1, 0], [0, 1, 0, -1] while b: cnt -= 1 x, y = b.popleft() for k in range(4): nx, ny = x + dx[k], y + dy[k] if 0 <= nx < n and 0 <= ny < m and A[nx][ny] == 1: b.append((nx, ny)) A[nx][ny] = 0 return cnt
a5ce1b
37a4e9
Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: WordFilter(string[] words) Initializes the object with the words in the dictionary. f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.   Example 1: Input ["WordFilter", "f"] [[["apple"]], ["a", "e"]] Output [null, 0] Explanation WordFilter wordFilter = new WordFilter(["apple"]); wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".   Constraints: 1 <= words.length <= 10000 1 <= words[i].length <= 7 1 <= pref.length, suff.length <= 7 words[i], pref and suff consist of lowercase English letters only. At most 10000 calls will be made to the function f.
class WordFilter(object): def __init__(self, words): """ :type words: List[str] """ self.resultMap = {} for w in range(len(words)): word = words[w] for i in range(len(word) + 1): for j in range(len(word) + 1): self.resultMap[(word[:i], word[j:])] = w def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int """ return self.resultMap.get((prefix, suffix), -1) # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix)
ebf46c
37a4e9
Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: WordFilter(string[] words) Initializes the object with the words in the dictionary. f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.   Example 1: Input ["WordFilter", "f"] [[["apple"]], ["a", "e"]] Output [null, 0] Explanation WordFilter wordFilter = new WordFilter(["apple"]); wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".   Constraints: 1 <= words.length <= 10000 1 <= words[i].length <= 7 1 <= pref.length, suff.length <= 7 words[i], pref and suff consist of lowercase English letters only. At most 10000 calls will be made to the function f.
class Node: def __init__(self): self.next=[None]*26 self.lst=[] class WordFilter: def __init__(self, words): """ :type words: List[str] """ self.p=Node() self.s=Node() def build(st,ptr,i): ptr.lst.append(i) for c in st: o=ord(c)-ord('a') if not ptr.next[o]: ptr.next[o]=Node() ptr=ptr.next[o] ptr.lst.append(i) for i in range(len(words)): build(words[i],self.p,i) build(words[i][::-1],self.s,i) def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int """ def find(st,ptr): for c in st: o=ord(c)-ord('a') if not ptr.next[o]: return [] ptr=ptr.next[o] return ptr.lst l=find(prefix,self.p) if not l: return -1 r=find(suffix[::-1],self.s) if not r: return -1 i=len(l)-1 j=len(r)-1 while i>=0 and j>=0: if l[i]==r[j]: return l[i] if l[i]>r[j]: i-=1 else: j-=1 return -1 # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix)
2a4454
34330a
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [4,2,3,0,3,1,2], start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3 Example 2: Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3 Example 3: Input: arr = [3,0,2,1,2], start = 2 Output: false Explanation: There is no way to reach at index 1 with value 0.   Constraints: 1 <= arr.length <= 5 * 10000 0 <= arr[i] < arr.length 0 <= start < arr.length
class Solution(object): def canReach(self, A, start): N = len(A) seen = [False] * N seen[start] = True stack = [start] while stack: node = stack.pop() if A[node] == 0: return True for nei in (node - A[node], node + A[node]): if 0 <= nei < N and not seen[nei]: stack.append(nei) seen[nei] = True return False
4c89c6
34330a
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [4,2,3,0,3,1,2], start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3 Example 2: Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3 Example 3: Input: arr = [3,0,2,1,2], start = 2 Output: false Explanation: There is no way to reach at index 1 with value 0.   Constraints: 1 <= arr.length <= 5 * 10000 0 <= arr[i] < arr.length 0 <= start < arr.length
class Solution: def canReach(self, arr: List[int], start: int) -> bool: graph = dict() l = len(arr) zeroset = [] for i in range(l): if arr[i] == 0: zeroset.append(i) else: if i + arr[i] < l: graph[i] = [i+arr[i]] if i - arr[i] >= 0: if i in graph: graph[i] += [i-arr[i]] else: graph[i] = [i-arr[i]] visited = set() visited.add(start) stack = [start] while stack: ci = stack.pop() if ci not in graph: continue for nei in graph[ci]: if nei not in visited: stack.append(nei) visited.add(nei) for zero in zeroset: if zero in visited: return True return False
a3a0bf
10101f
You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.   Example 1: Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1 Output: 4 Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. No other pairs satisfy the condition, so we return the max of 4 and 1. Example 2: Input: points = [[0,0],[3,0],[9,2]], k = 3 Output: 3 Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.   Constraints: 2 <= points.length <= 100000 points[i].length == 2 -10^8 <= xi, yi <= 10^8 0 <= k <= 2 * 10^8 xi < xj for all 1 <= i < j <= points.length xi form a strictly increasing sequence.
class Solution: def findMaxValueOfEquation(self, p: List[List[int]], k: int) -> int: stack=[] ans=-inf for x,y in p: ind=bisect.bisect(stack,(x-k,-inf)) if ind!=len(stack): ans=max(ans,stack[ind][1]+x+y) while stack and stack[-1][1]<=y-x: stack.pop() stack.append((x,y-x)) return ans
03c6fd
10101f
You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.   Example 1: Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1 Output: 4 Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. No other pairs satisfy the condition, so we return the max of 4 and 1. Example 2: Input: points = [[0,0],[3,0],[9,2]], k = 3 Output: 3 Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.   Constraints: 2 <= points.length <= 100000 points[i].length == 2 -10^8 <= xi, yi <= 10^8 0 <= k <= 2 * 10^8 xi < xj for all 1 <= i < j <= points.length xi form a strictly increasing sequence.
class Monoqueue(collections.deque): def enqueue(self, val): count = 1 while self and self[-1][0] < val: count += self.pop()[1] self.append([val, count]) def dequeue(self): ans = self.max() self[0][1] -= 1 if self[0][1] <= 0: self.popleft() return ans def max(self): return self[0][0] if self else None class Solution(object): def findMaxValueOfEquation(self, A, K): N = len(A) i = 0 mq = Monoqueue() ans = float('-inf') for j in xrange(N): while i <= j and A[j][0] - A[i][0] > K: mq.dequeue() i += 1 M = mq.max() if M is not None: cand = M + A[j][0] + A[j][1] if cand>ans:ans=cand mq.enqueue(A[j][1] - A[j][0]) return ans
4b0899
21f66b
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.   Example 1: Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4 Output: 21 Explanation: Lap 1: Start with tire 0 and finish the lap in 2 seconds. Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds. The minimum time to complete the race is 21 seconds. Example 2: Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5 Output: 25 Explanation: Lap 1: Start with tire 1 and finish the lap in 2 seconds. Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second. Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds. The minimum time to complete the race is 25 seconds.   Constraints: 1 <= tires.length <= 100000 tires[i].length == 2 1 <= fi, changeTime <= 100000 2 <= ri <= 100000 1 <= numLaps <= 1000
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: dp = defaultdict(lambda: inf) for f, r in tires: cost = changeTime count = 0 while cost < 1e6 and count <= numLaps: cost += f * (r ** count) count += 1 dp[count] = min(dp[count], cost) dp2 = defaultdict(lambda: inf) dp2[0] = 0 for i in range(1, numLaps + 1): for count, cost in dp.items(): if i - count >= 0: dp2[i] = min(dp2[i], cost + dp2[i - count]) return dp2[numLaps] - changeTime
cfbaa3
21f66b
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.   Example 1: Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4 Output: 21 Explanation: Lap 1: Start with tire 0 and finish the lap in 2 seconds. Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds. The minimum time to complete the race is 21 seconds. Example 2: Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5 Output: 25 Explanation: Lap 1: Start with tire 1 and finish the lap in 2 seconds. Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second. Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds. The minimum time to complete the race is 25 seconds.   Constraints: 1 <= tires.length <= 100000 tires[i].length == 2 1 <= fi, changeTime <= 100000 2 <= ri <= 100000 1 <= numLaps <= 1000
class Solution(object): def minimumFinishTime(self, tires, changeTime, numLaps): """ :type tires: List[List[int]] :type changeTime: int :type numLaps: int :rtype: int """ d = changeTime cost = {} for f, r in tires: s = 0 x = 0 t = f while t < d+f: s += t x += 1 if x not in cost: cost[x] = s else: cost[x] = min(cost[x], s) t *= r n = numLaps best = [0]*(n+1) for i in xrange(1, n+1): best[i] = min(best[i-j]+c+d for j, c in cost.iteritems() if j <= i) return best[n]-d
61dc04
8187e7
You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '. A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s. For example, "acb dfe" is an anagram of "abc def", but "def cab" and "adc bef" are not. Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: s = "too hot" Output: 18 Explanation: Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht". Example 2: Input: s = "aa" Output: 1 Explanation: There is only one anagram possible for the given string.   Constraints: 1 <= s.length <= 100000 s consists of lowercase English letters and spaces ' '. There is single space between consecutive words.
def exgcd(a, b): if b == 0: return 1, 0, a else: x, y, q = exgcd(b, a % b) x, y = y, (x - (a // b) * y) return x, y, q def ModReverse(a, p): x, y, q = exgcd(a, p) return x % p k, mod = 10 ** 6, 10 ** 9 + 7 fac = [1] for i in range(1, k+1): fac.append(fac[-1] * i % mod) k_inv = k fac_inv = [0] * (k_inv + 1) fac_inv[k_inv] = ModReverse(fac[k_inv], mod) for i in range(k_inv-1, -1, -1): fac_inv[i] = fac_inv[i+1] * (i+1) % mod class Solution: def countAnagrams(self, s: str) -> int: words = s.split() ans = 1 for word in words: cnt = Counter(word) res = fac[len(word)] for x in cnt.values(): res *= fac_inv[x] res %= mod ans = ans * res % mod return ans
1fa09f
8187e7
You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '. A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s. For example, "acb dfe" is an anagram of "abc def", but "def cab" and "adc bef" are not. Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: s = "too hot" Output: 18 Explanation: Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht". Example 2: Input: s = "aa" Output: 1 Explanation: There is only one anagram possible for the given string.   Constraints: 1 <= s.length <= 100000 s consists of lowercase English letters and spaces ' '. There is single space between consecutive words.
class Solution(object): def countAnagrams(self, s): """ :type s: str :rtype: int """ r = 1 cs = [0]*26 mod = 1000000007 n = len(s) ft, ift = [1]*(n+1), [1]*(n+1) def expit(b, e): r = 1 while e: if e&1: r*=b r%=mod b*=b b%=mod e>>=1 return r for i in range(1, n+1): ft[i] = (ft[i-1]*i)%mod ift[i] = expit(ft[i], mod-2) for w in s.split(): for k in range(26): cs[k]=0 n = len(w) for c in w: c=ord(c)-ord('a') cs[c]+=1 v=ft[n] for k in range(26): v*=ift[cs[k]] v%=mod r*=v r%=mod return r
2c29ac
6b2c44
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.   Example 1: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". Example 2: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". Example 3: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".   Constraints: 1 <= pattern.length, queries.length <= 100 1 <= queries[i].length <= 100 queries[i] and pattern consist of English letters.
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: def is_subseq(query, pattern): idx, n = 0, len(pattern) for ch in query: if ch == pattern[idx]: idx += 1 if idx == n: return True return False def caps(word): return sum(ch.isupper() for ch in word) c = caps(pattern) return [True if (is_subseq(word, pattern) and caps(word) == c) else False for word in queries]
a96eb8
6b2c44
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.   Example 1: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". Example 2: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". Example 3: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".   Constraints: 1 <= pattern.length, queries.length <= 100 1 <= queries[i].length <= 100 queries[i] and pattern consist of English letters.
class Solution(object): def camelMatch(self, queries, pattern): """ :type queries: List[str] :type pattern: str :rtype: List[bool] """ def preprocess(word): lft_low=[] up_low=[] idx=0 while idx<len(word): if idx==0: while idx<len(word) and word[idx].islower(): lft_low.append(word[idx]) idx+=1 if idx<len(word): tmpId=idx+1 tmp=[] while tmpId<len(word) and word[tmpId].islower(): tmp.append(word[tmpId]) tmpId+=1 up_low.append([word[idx],tmp]) idx=tmpId return [lft_low,up_low] def contain(A,B): if len(B)==0: return True idx=0 for a in A: if B[idx]==a: idx+=1 if idx==len(B): return True return False lft_low, up_low=preprocess(pattern) def match(query): lft_low_q,up_low_q=preprocess(query) if not contain(lft_low_q,lft_low): return False if len(up_low_q)!=len(up_low): return False for i in range(len(up_low)): if up_low_q[i][0]!=up_low[i][0] or not contain(up_low_q[i][1],up_low[i][1]): return False return True ans=[] for query in queries: ans.append(match(query)) return ans
7b27c0
2c0509
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.   Example 1: Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. Example 2: Input: trees = [[1,2],[2,2],[4,2]] Output: [[4,2],[2,2],[1,2]] Explanation: The fence forms a line that passes through all the trees.   Constraints: 1 <= trees.length <= 3000 trees[i].length == 2 0 <= xi, yi <= 100 All the given positions are unique.
# Definition for a point. # class Point(object): # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution(object): def outerTrees(self, A): def ccw(p, q, r): return +( q.x*p.y + r.x*q.y +p.x*r.y > q.x*r.y + p.x*q.y + r.x*p.y ) def ccc(p, q, r): return ( q.x*p.y + r.x*q.y +p.x*r.y == q.x*r.y + p.x*q.y + r.x*p.y ) def convex(A): A.sort(key = lambda p: (p.x, p.y)) upper = A[:2] for point in A[2:]: upper.append(point) while len(upper) > 2 and not ccw(*upper[-3:]): upper.pop(-2) A = A[::-1] lower = A[:2] for point in A[2:]: lower.append(point) while len(lower) > 2 and not ccw(*lower[-3:]): lower.pop(-2) #print [(p.x,p.y) for p in upper] #print [(p.x,p.y) for p in lower] return upper + lower[1:-1] B = convex(A) def onpoly(B, r): for p, q in zip(B, B[1:]+B[:1]): if ccc(p,q,r): return 1 return 0 ans = [] for r in A: if onpoly(B, r): ans.append(r) return ans
cb96a1
2c0509
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.   Example 1: Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. Example 2: Input: trees = [[1,2],[2,2],[4,2]] Output: [[4,2],[2,2],[1,2]] Explanation: The fence forms a line that passes through all the trees.   Constraints: 1 <= trees.length <= 3000 trees[i].length == 2 0 <= xi, yi <= 100 All the given positions are unique.
class Solution: def outerTrees(self, points): """ :type points: List[Point] :rtype: List[Point] """ newpoints = [] for i in points: newpoints.append((i.x,i.y)) newpoints.sort() if len(newpoints) <= 1: return [list(newpoints[0])] def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Build lower hull lower = [] for p in newpoints: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(newpoints): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the beginning of the other list. return list(set(lower[:-1] + upper[:-1]))
b60b8d
1fffc0
On day 1, one person discovers a secret. You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 6, delay = 2, forget = 4 Output: 5 Explanation: Day 1: Suppose the first person is named A. (1 person) Day 2: A is the only person who knows the secret. (1 person) Day 3: A shares the secret with a new person, B. (2 people) Day 4: A shares the secret with a new person, C. (3 people) Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people) Day 6: B shares the secret with E, and C shares the secret with F. (5 people) Example 2: Input: n = 4, delay = 1, forget = 3 Output: 6 Explanation: Day 1: The first person is named A. (1 person) Day 2: A shares the secret with B. (2 people) Day 3: A and B share the secret with 2 new people, C and D. (4 people) Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)   Constraints: 2 <= n <= 1000 1 <= delay < forget <= n
class Solution: def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int: dp = [0]*(n+5) dp[1] = 1 psa = [0]*(n+5) psa[1] = 1 for i in range(2, n+1): x, y = max(0, i-forget+1), i-delay if x <= y: dp[i] = psa[y]-psa[x-1] dp[i] %= 1000000007 psa[i] = (dp[i]+psa[i-1]) % 1000000007 return (psa[n]-psa[n-forget])% 1000000007
1c79ee
1fffc0
On day 1, one person discovers a secret. You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 6, delay = 2, forget = 4 Output: 5 Explanation: Day 1: Suppose the first person is named A. (1 person) Day 2: A is the only person who knows the secret. (1 person) Day 3: A shares the secret with a new person, B. (2 people) Day 4: A shares the secret with a new person, C. (3 people) Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people) Day 6: B shares the secret with E, and C shares the secret with F. (5 people) Example 2: Input: n = 4, delay = 1, forget = 3 Output: 6 Explanation: Day 1: The first person is named A. (1 person) Day 2: A shares the secret with B. (2 people) Day 3: A and B share the secret with 2 new people, C and D. (4 people) Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)   Constraints: 2 <= n <= 1000 1 <= delay < forget <= n
class Solution(object): def peopleAwareOfSecret(self, n, delay, forget): """ :type n: int :type delay: int :type forget: int :rtype: int """ d, s, r = [0, 1] + [0] * (n - 1), 0, 0 for i in range(2, n + 1): s, d[i] = (s + (d[i - delay] if i > delay else 0) - (d[i - forget] if i > forget else 0)+ 1000000007) % 1000000007, (s + (d[i - delay] if i > delay else 0) - (d[i - forget] if i > forget else 0)+ 1000000007) % 1000000007 for i in range(n, n - forget, -1): r = (r + d[i]) % 1000000007 return r
d7e790
f504b1
You are given two integers height and width representing a garden of size height x width. You are also given: an array tree where tree = [treer, treec] is the position of the tree in the garden, an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden, and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden. The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell. Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one. The distance is the number of moves. Example 1: Input: height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]] Output: 12 Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance. Example 2: Input: height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]] Output: 3 Constraints: 1 <= height, width <= 100 tree.length == 2 squirrel.length == 2 1 <= nuts.length <= 5000 nuts[i].length == 2 0 <= treer, squirrelr, nutir <= height 0 <= treec, squirrelc, nutic <= width
class Solution(object): def minDistance(self, height, width, tree, squirrel, nuts): """ :type height: int :type width: int :type tree: List[int] :type squirrel: List[int] :type nuts: List[List[int]] :rtype: int """ def taxi((a,b),(c,d)): return abs(a-c) + abs(b-d) S = 0 for nut in nuts: S += 2 * taxi(tree, nut) A = 1e9 for nut in nuts: A = min(A, taxi(squirrel, nut) - taxi(nut, tree)) return S+A
22b4f2
f504b1
You are given two integers height and width representing a garden of size height x width. You are also given: an array tree where tree = [treer, treec] is the position of the tree in the garden, an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden, and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden. The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell. Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one. The distance is the number of moves. Example 1: Input: height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]] Output: 12 Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance. Example 2: Input: height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]] Output: 3 Constraints: 1 <= height, width <= 100 tree.length == 2 squirrel.length == 2 1 <= nuts.length <= 5000 nuts[i].length == 2 0 <= treer, squirrelr, nutir <= height 0 <= treec, squirrelc, nutic <= width
class Solution: def minDistance(self, height, width, tree, squirrel, nuts): """ :type height: int :type width: int :type tree: List[int] :type squirrel: List[int] :type nuts: List[List[int]] :rtype: int """ def d(t,n): return abs(t[0]-n[0])+abs(t[1]-n[1]) dis=[d(tree,i) for i in nuts] dissum=sum(dis)*2 return min(dissum-dis[i]+d(squirrel,nuts[i]) for i in range(len(nuts)))
90cc69
9d992c
You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through, 1 means the cell contains a cherry that you can pick up and pass through, or -1 means the cell contains a thorn that blocks your way. Return the maximum number of cherries you can collect by following the rules below: Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1). After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells. When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0. If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.   Example 1: Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]] Output: 5 Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2). 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]]. Then, the player went left, up, up, left to return home, picking up one more cherry. The total number of cherries picked up is 5, and this is the maximum possible. Example 2: Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]] Output: 0   Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 grid[i][j] is -1, 0, or 1. grid[0][0] != -1 grid[n - 1][n - 1] != -1
class Solution(object): def cherryPickup(self, grid): """ :type grid: List[List[int]] :rtype: int """ n = len(grid) cur = [[grid[0][0]]] for l in range(1, n): pre, cur = cur, [[-1 for j in range(l + 1)] for i in range(l + 1)] for i in range(l + 1): for j in range(i, l + 1): m = -1 for ii in [i - 1, i]: for jj in [j - 1, j]: if 0 <= ii < l and 0 <= jj < l: m = max(m, pre[ii][jj]) if m >= 0 and grid[l - i][i] >= 0 and grid[l - j][j] >= 0: cur[i][j] = m + grid[l - i][i] + grid[l - j][j] if i != j else m + grid[l - i][i] else: cur[i][j] = -1 #print cur for l in range(n - 2, -1, -1): pre, cur = cur, [[-1 for j in range(l + 1)] for i in range(l + 1)] for i in range(l + 1): for j in range(i, l + 1): m = -1 for ii in [i + 1, i]: for jj in [j + 1, j]: m = max(m, pre[ii][jj]) if m >= 0 and grid[n - 1 - i][n - 1 - l + i] >= 0 and grid[n - 1 - j][n - 1 - l + j] >= 0: cur[i][j] = m + grid[n - 1 - i][n - 1 - l + i] + grid[n - 1 - j][n - 1 - l + j] if i != j else m + grid[n - 1 - i][n - 1 - l + i] else: cur[i][j] = -1 #print cur return max(cur[0][0], 0)
da75d3
9d992c
You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through, 1 means the cell contains a cherry that you can pick up and pass through, or -1 means the cell contains a thorn that blocks your way. Return the maximum number of cherries you can collect by following the rules below: Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1). After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells. When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0. If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.   Example 1: Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]] Output: 5 Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2). 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]]. Then, the player went left, up, up, left to return home, picking up one more cherry. The total number of cherries picked up is 5, and this is the maximum possible. Example 2: Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]] Output: 0   Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 grid[i][j] is -1, 0, or 1. grid[0][0] != -1 grid[n - 1][n - 1] != -1
class Solution: def cherryPickup(self, grid): """ :type grid: List[List[int]] :rtype: int """ # dynamic programming # dp[i1][j1][i2][j2] stores the maximum cherry can pick # by starting from (i1, j1), (i2, j2) and goes to (n - 1, n - 1) # base case dp[n-1,n-1,n-1,n-1] = R[n-1] # R = -inf if R = 0 N = len(grid) for i in range(N): for j in range(N): if grid[i][j] == -1: grid[i][j] = float('-inf') cache = dict() def helper(i1, j1, i2, j2): if (i1, j1, i2, j2) in cache: return cache[(i1, j1, i2, j2)] if (i1, j1, i2, j2) == (N - 1, N - 1, N - 1, N - 1): rtn = grid[N - 1][N - 1] cache[(i1, j1, i2, j2)] = rtn return rtn if i1 >= N or j1 >= N or i2 >= N or j2 >= N or grid[i1][j1] < 0 or grid[i2][j2] < 0: rtn = float('-inf') cache[(i1, j1, i2, j2)] = rtn return rtn # Need to consider different cases if i1 == i2 and j1 == j2: rtn = grid[i1][j1] rtn += max(helper(i1 + 1, j1, i2 + 1, j2), helper(i1 + 1, j1, i2, j2 + 1), helper(i1, j1 + 1, i2 + 1, j2), helper(i1, j1 + 1, i2, j2 + 1)) cache[(i1, j1, i2, j2)] = rtn return rtn if i1 <= i2 and j1 <= j2: # i1, j1 might cross i2, j2 rtn = grid[i1][j1] + max(helper(i1 + 1, j1, i2, j2), helper(i1, j1 + 1, i2, j2)) cache[(i1, j1, i2, j2)] = rtn return rtn if i1 >= i2 and j1 >= j2: # i2, j2 might cross i1, j1 rtn = grid[i2][j2] + max(helper(i1, j1, i2 + 1, j2), helper(i1, j1, i2, j2 + 1)) cache[(i1, j1, i2, j2)] = rtn return rtn rtn = grid[i1][j1] + grid[i2][j2] rtn += max(helper(i1 + 1, j1, i2 + 1, j2), helper(i1 + 1, j1, i2, j2 + 1), helper(i1, j1 + 1, i2 + 1, j2), helper(i1, j1 + 1, i2, j2 + 1)) cache[(i1, j1, i2, j2)] = rtn return rtn rtn = helper(0, 0, 0, 0) return max(rtn, 0)
31599f
284cfe
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1). You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1). Return true if it is possible to make the matrix disconnect or false otherwise. Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.   Example 1: Input: grid = [[1,1,1],[1,0,0],[1,1,1]] Output: true Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: false Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 1
class Solution: def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: R = len(grid) C = len(grid[0]) gfrom = [[False] * C for _ in range(R)] gfrom[R - 1][C - 1] = True for i in range(R - 1, -1, -1): for j in range(C - 1, -1, -1): if i == R - 1 and j == C - 1: continue if grid[i][j] == 0: continue if i + 1 < R and gfrom[i + 1][j]: gfrom[i][j] = True if j + 1 < C and gfrom[i][j + 1]: gfrom[i][j] = True gto = [[False] * C for _ in range(R)] gto[0][0] = True for i in range(R): for j in range(C): if i == 0 and j == 0: continue if grid[i][j] == 0: continue if i >= 1 and gto[i - 1][j]: gto[i][j] = True if j >= 1 and gto[i][j - 1]: gto[i][j] = True if not gfrom[0][0]: return True x, y, path1 = 0, 0, [] while y != R - 1 or x != C - 1: if x + y > 0: path1.append((y, x)) if x + 1 < C and gfrom[y][x + 1]: x += 1 else: y += 1 x, y, path2 = 0, 0, [] while y != R - 1 or x != C - 1: if x + y > 0: path2.append((y, x)) if y + 1 < R and gfrom[y + 1][x]: y += 1 else: x += 1 return (set(path1) & set(path2))
6c3d49
284cfe
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1). You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1). Return true if it is possible to make the matrix disconnect or false otherwise. Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.   Example 1: Input: grid = [[1,1,1],[1,0,0],[1,1,1]] Output: true Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: false Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 1
class Solution(object): def isPossibleToCutPath(self, grid): """ :type grid: List[List[int]] :rtype: bool """ n = len(grid) m = len(grid[0]) dp = [[0 for k in range(0, m)] for i in range(0, n)] dp1 = [[0 for k in range(0, m)] for i in range(0, n)] dp[0][0] = 1 dp1[n - 1][m - 1] = 1 for i in range(0, n): for k in range(0, m): if grid[i][k] == 1: if i - 1 >= 0: dp[i][k] += dp[i - 1][k] if k - 1 >= 0: dp[i][k] += dp[i][k - 1] i = n - 1 while i >= 0: k = m - 1 while k >= 0: if grid[i][k] == 1: if i + 1 < n: dp1[i][k] += dp1[i + 1][k] if k + 1 < m: dp1[i][k] += dp1[i][k + 1] k = k - 1 i = i - 1 if dp[n - 1][m - 1] == 0: return True # print(dp) for i in range(0, n): for k in range(0, m): if dp[i][k] * dp1[i][k] == dp[n - 1][m - 1] and (i, k) != (0, 0) and (i, k) != (n - 1, m - 1): return True return False
894e16
aa04a8
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).   Example 1: Input: root = [5,2,-3] Output: [2,-3,4] Example 2: Input: root = [5,2,-5] Output: [2]   Constraints: The number of nodes in the tree is in the range [1, 10000]. -100000 <= 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 findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] """ dic = {} def calculate(node, dic): if node.left == None and node.right == None: total = node.val else: total = node.val if node.left: total += calculate(node.left, dic) if node.right: total += calculate(node.right, dic) if total in dic: dic[total] += 1 else: dic[total] = 1 return total if not root: return [] calculate(root, dic) result = [] max_value = 0 for key in dic: value = dic[key] max_value = max(max_value, value) for key in dic: if dic[key] == max_value: result.append(key) return result
3aacb3
bb391d
Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums. For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST. Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: nums = [2,1,3] Output: 1 Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST. Example 2: Input: nums = [3,4,5,1,2] Output: 5 Explanation: The following 5 arrays will yield the same BST: [3,1,2,4,5] [3,1,4,2,5] [3,1,4,5,2] [3,4,1,2,5] [3,4,1,5,2] Example 3: Input: nums = [1,2,3] Output: 0 Explanation: There are no other orderings of nums that will yield the same BST.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= nums.length All integers in nums are distinct.
from math import factorial as fact class Solution: def numOfWays(self, nums: List[int]) -> int: MOD = (10**9)+7 def helper(nums): if len(nums) == 0: return 1 # we have to keep the first element the same first = nums[0] smaller = [el for el in nums if el<first] larger = [el for el in nums if el>first] weaves = choose(len(nums)-1,len(smaller)) # len(nums) choose len(smaller) #print(smaller,larger,weaves) return (weaves*helper(smaller)*helper(larger))%MOD def choose(a,b): return fact(a)//(fact(b)*fact(a-b)) return helper(nums)-1
a103ae
bb391d
Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums. For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST. Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: nums = [2,1,3] Output: 1 Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST. Example 2: Input: nums = [3,4,5,1,2] Output: 5 Explanation: The following 5 arrays will yield the same BST: [3,1,2,4,5] [3,1,4,2,5] [3,1,4,5,2] [3,4,1,2,5] [3,4,1,5,2] Example 3: Input: nums = [1,2,3] Output: 0 Explanation: There are no other orderings of nums that will yield the same BST.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= nums.length All integers in nums are distinct.
class Solution(object): def numOfWays(self, nums): """ :type nums: List[int] :rtype: int """ mod = 10**9 + 7 n = len(nums) c = [[1]] for i in xrange(n): cc = c[-1] + [1] for j in xrange(i, 0, -1): cc[j] += cc[j-1] if cc[j] >= mod: cc[j] -= mod c.append(cc) def _ways(arr): if not arr: # empty tree return 1 root = arr[0] lhs = [i for i in arr if i < root] rhs = [i for i in arr if i > root] return (_ways(lhs) * _ways(rhs) * c[len(arr)-1][len(lhs)]) % mod return (_ways(nums) - 1) % mod
350bab
da9ca3
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa. Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.   Example 1: Input: s = "111000" Output: 2 Explanation: Use the first operation two times to make s = "100011". Then, use the second operation on the third and sixth elements to make s = "101010". Example 2: Input: s = "010" Output: 0 Explanation: The string is already alternating. Example 3: Input: s = "1110" Output: 1 Explanation: Use the second operation on the second element to make s = "1010".   Constraints: 1 <= s.length <= 100000 s[i] is either '0' or '1'.
class Solution: def minFlips(self, s: str) -> int: n = len(s) t = s + s a = '01' * n b = '10' * n ans = n da = 0 db = 0 for i in range(n * 2): if t[i] != a[i]: da += 1 if t[i] != b[i]: db += 1 if i >= n: if t[i - n] != a[i - n]: da -= 1 if t[i - n] != b[i - n]: db -= 1 if i >= n - 1: ans = min(ans, da, db) return ans
7721a1
da9ca3
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa. Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.   Example 1: Input: s = "111000" Output: 2 Explanation: Use the first operation two times to make s = "100011". Then, use the second operation on the third and sixth elements to make s = "101010". Example 2: Input: s = "010" Output: 0 Explanation: The string is already alternating. Example 3: Input: s = "1110" Output: 1 Explanation: Use the second operation on the second element to make s = "1010".   Constraints: 1 <= s.length <= 100000 s[i] is either '0' or '1'.
class Solution(object): def minFlips(self, s): """ :type s: str :rtype: int """ n = len(s) cost = [0] * (n+1) for i in xrange(n): cost[i+1] = cost[i] + ((i & 1) ^ (ord(s[i]) & 1)) r = min(cost[n], n-cost[n]) if n & 1: for i in xrange(1, n): r = min(r, cost[i]+(n-i)-(cost[n]-cost[i])) r = min(r, (i-cost[i])+(cost[n]-cost[i])) return r
c5b30b
15e1d2
You are given an integer array arr. In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal. Return the minimum number of moves needed to remove all numbers from the array. Example 1: Input: arr = [1,2] Output: 2 Example 2: Input: arr = [1,3,4,1,5] Output: 3 Explanation: Remove [4] then remove [1,3,1] then remove [5]. Constraints: 1 <= arr.length <= 100 1 <= arr[i] <= 20
class Solution(object): def minimumMoves(self, arr): return self.minStepToDeleteString(arr) def minStepToDeleteString(self, A): N = len(A) dp = [[0 for x in xrange(N + 1)] for y in xrange(N + 1)] for l in range(1, N + 1): i = 0 j = l - 1 while j < N: if (l == 1): dp[i][j] = 1 else: dp[i][j] = 1 + dp[i + 1][j] if (A[i] == A[i + 1]): dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]) for K in range(i + 2, j + 1): if (A[i] == A[K]): dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]) i += 1 j += 1 return dp[0][N - 1]
f1c239
15e1d2
You are given an integer array arr. In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal. Return the minimum number of moves needed to remove all numbers from the array. Example 1: Input: arr = [1,2] Output: 2 Example 2: Input: arr = [1,3,4,1,5] Output: 3 Explanation: Remove [4] then remove [1,3,1] then remove [5]. Constraints: 1 <= arr.length <= 100 1 <= arr[i] <= 20
import functools class Solution: def minimumMoves(self, arr: List[int]) -> int: @functools.lru_cache(None) def compute(i, j): if i > j: return 0 elif i == j: return 1 else: ans = 1 + compute(i + 1, j) for i1 in range(i + 1, j + 1): if arr[i1] == arr[i]: ans = min(ans, (compute(i + 1, i1 - 1) if i + 1 < i1 else 1) + compute(i1 + 1, j)) return ans return compute(0, len(arr) - 1)
7855c4
87c25a
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7. Player 2 competes against player 6. Player 4 automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.   Example 1: Input: n = 11, firstPlayer = 2, secondPlayer = 4 Output: [3,4] Explanation: One possible scenario which leads to the earliest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 2, 3, 4, 5, 6, 11 Third round: 2, 3, 4 One possible scenario which leads to the latest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 1, 2, 3, 4, 5, 6 Third round: 1, 2, 4 Fourth round: 2, 4 Example 2: Input: n = 5, firstPlayer = 1, secondPlayer = 5 Output: [1,1] Explanation: The players numbered 1 and 5 compete in the first round. There is no way to make them compete in any other round.   Constraints: 2 <= n <= 28 1 <= firstPlayer < secondPlayer <= n
class Solution: def earliestAndLatest(self, num: int, first: int, second: int) -> List[int]: @cache def earliest(n, f, s): if f+s == n-1: return 1 matches = n//2 ans = 10000000 for win in range(2**matches): l = [1 for i in range(n)] for i in range(matches): if win&(1<<i): l[i] = 1 l[n-1-i] = 0 else: l[i] = 0 l[n-1-i] = 1 #print(win, l) if l[f] and l[s]: for i in range(1, n): l[i] += l[i-1] ans = min(ans, earliest(n-matches, l[f]-1, l[s]-1)+1) return ans @cache def latest(n, f, s): if f+s == n-1: return 1 matches = n//2 ans = -10000000 for win in range(2**matches): l = [1 for i in range(n)] for i in range(matches): if win&(1<<i): l[i] = 1 l[n-1-i] = 0 else: l[i] = 0 l[n-1-i] = 1 if l[f] and l[s]: for i in range(1, n): l[i] += l[i-1] #print(n, f, s, l) ans = max(ans, latest(n-matches, l[f]-1, l[s]-1)+1) return ans return [earliest(num, first-1, second-1), latest(num, first-1, second-1)]
5b892b
87c25a
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7. Player 2 competes against player 6. Player 4 automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.   Example 1: Input: n = 11, firstPlayer = 2, secondPlayer = 4 Output: [3,4] Explanation: One possible scenario which leads to the earliest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 2, 3, 4, 5, 6, 11 Third round: 2, 3, 4 One possible scenario which leads to the latest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 1, 2, 3, 4, 5, 6 Third round: 1, 2, 4 Fourth round: 2, 4 Example 2: Input: n = 5, firstPlayer = 1, secondPlayer = 5 Output: [1,1] Explanation: The players numbered 1 and 5 compete in the first round. There is no way to make them compete in any other round.   Constraints: 2 <= n <= 28 1 <= firstPlayer < secondPlayer <= n
class Solution(object): def earliestAndLatest(self, n, firstPlayer, secondPlayer): """ :type n: int :type firstPlayer: int :type secondPlayer: int :rtype: List[int] """ m1={} m2={} def conv(a): s="" for i in a: s+=str(i)+'$' return s def func(arr): arr.sort() s=conv(arr) if m1.get(s,-1)!=-1: return [m1[s],m2[s]] b=[[]] minn=10**18 maxx=0 for i in range(len(arr)/2): c=[] for j in b: if arr[i]==firstPlayer and arr[len(arr)-i-1]==secondPlayer: m1[s]=1 m2[s]=1 return [1,1] elif arr[i]==firstPlayer or arr[i]==secondPlayer: c.append(j+[arr[i]]) elif arr[len(arr)-i-1]==firstPlayer or arr[len(arr)-i-1]==secondPlayer: c.append(j+[arr[len(arr)-i-1]]) else: c.append(j+[arr[i]]) c.append(j+[arr[len(arr)-i-1]]) b=c[:] if len(arr)%2==1: for j in range(len(b)): b[j].append(arr[len(arr)/2]) for j in range(len(b)): out=func(b[j]) minn=min(minn,out[0]+1) maxx=max(maxx,out[1]+1) m1[s]=minn m2[s]=maxx return [m1[s],m2[s]] return func([i for i in range(1,n+1)])
31adcd
8cc9ba
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.   Example 1: Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.   Constraints: 1 <= s.length <= 10000 s consists of only lowercase English letters. 1 <= k <= 100000
import collections class Solution(object): def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ if s == "": return 0 count = collections.Counter(s) if min(count.values()) >= k: return len(s) p = "" m = 0 for c in s: if count[c] >= k: p = p + c else: if p != "": m = max(m, self.longestSubstring(p, k)) p = "" m = max(m, self.longestSubstring(p, k)) return m
9fdbca
044d30
You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path). The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9] Output: 30 Explanation: Valid paths: [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1) [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2) The maximum is obtained with the path in green [2,4,6,8,10]. Example 2: Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100] Output: 109 Explanation: Maximum sum is obtained with the path [1,3,5,100]. Example 3: Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] Output: 40 Explanation: There are no common elements between nums1 and nums2. Maximum sum is obtained with the path [6,7,8,9,10].   Constraints: 1 <= nums1.length, nums2.length <= 100000 1 <= nums1[i], nums2[i] <= 10^7 nums1 and nums2 are strictly increasing.
class Solution: def maxSum(self, nums1: List[int], nums2: List[int]) -> int: t = [] for i in nums1: t.append((i, 0)) for i in nums2: t.append((i, 1)) t = sorted(t) n = len(t) f = [0] * n i = 0 fp = [0, 0] while i < n: if i + 1 < n and t[i][0] == t[i + 1][0]: fp = [max(fp) + t[i][0]] * 2 i += 2 else: fp[t[i][1]] += t[i][0] i += 1 return max(fp) % int(1e9 + 7)
6d716b
044d30
You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path). The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9] Output: 30 Explanation: Valid paths: [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1) [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2) The maximum is obtained with the path in green [2,4,6,8,10]. Example 2: Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100] Output: 109 Explanation: Maximum sum is obtained with the path [1,3,5,100]. Example 3: Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] Output: 40 Explanation: There are no common elements between nums1 and nums2. Maximum sum is obtained with the path [6,7,8,9,10].   Constraints: 1 <= nums1.length, nums2.length <= 100000 1 <= nums1[i], nums2[i] <= 10^7 nums1 and nums2 are strictly increasing.
from collections import defaultdict, Counter class Solution(object): def maxSum(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ mod = 10**9 + 7 adj = defaultdict(list) best = Counter() s = set() for a in nums1, nums2: best[a[0]] = a[0] n = len(a) s.update(a) for i in xrange(n-1): adj[a[i]].append(a[i+1]) for u in sorted(s): for v in adj[u]: best[v] = max(best[v], best[u]+v) r = max(best[nums1[-1]], best[nums2[-1]]) return r % mod
15dc18
4a2cdf
You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,1,0], k = 1 Output: 2 Explanation: Flip nums[0], then flip nums[2]. Example 2: Input: nums = [1,1,0], k = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]. Example 3: Input: nums = [0,0,0,1,0,1,1,0], k = 3 Output: 3 Explanation: Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]   Constraints: 1 <= nums.length <= 100000 1 <= k <= nums.length
import collections class Solution: def minKBitFlips(self, A: 'List[int]', K: 'int') -> 'int': a = A n = len(a) k = K ans = 0 cnt = 0 mark = collections.deque() for i in range(n - k + 1): while cnt > 0 and i - mark[0] >= k: cnt -= 1 mark.popleft() if cnt % 2 == 0: if a[i] == 0: cnt += 1 ans += 1 mark.append(i) a[i] = 1 else: pass else: if a[i] == 0: a[i] = 1 pass else: cnt += 1 ans += 1 mark.append(i) # print(i, a, mark) for i in range(n - k + 1, n): while cnt > 0 and i - mark[0] >= k: cnt -= 1 mark.popleft() if cnt % 2 == 0 and a[i] == 0: return -1 if cnt % 2 == 1 and a[i] == 1: return -1 return ans
decb6f
4a2cdf
You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,1,0], k = 1 Output: 2 Explanation: Flip nums[0], then flip nums[2]. Example 2: Input: nums = [1,1,0], k = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]. Example 3: Input: nums = [0,0,0,1,0,1,1,0], k = 3 Output: 3 Explanation: Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]   Constraints: 1 <= nums.length <= 100000 1 <= k <= nums.length
class Solution(object): def minKBitFlips(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ n = len(A) cnt = 0 flips = collections.deque() for i in range(n - K + 1): if (int(A[i]) + len(flips)) % 2 == 0: cnt += 1 flips.append(i + K - 1) if flips and i == flips[0]: flips.popleft() for i in range(n - K + 1, n): if (int(A[i]) + len(flips)) % 2 == 0: return -1 if flips and i == flips[0]: flips.popleft() return cnt
97c5a1
435fc8
You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Count all trailing zeros in the product and remove them. Let us denote this count as C. For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf> denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged. For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567. Finally, represent the product as a string "<pre>...<suf>eC". For example, 12345678987600000 will be represented as "12345...89876e5". Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].   Example 1: Input: left = 1, right = 4 Output: "24e0" Explanation: The product is 1 × 2 × 3 × 4 = 24. There are no trailing zeros, so 24 remains the same. The abbreviation will end with "e0". Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further. Thus, the final representation is "24e0". Example 2: Input: left = 2, right = 11 Output: "399168e2" Explanation: The product is 39916800. There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with "e2". The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further. Hence, the abbreviated product is "399168e2". Example 3: Input: left = 371, right = 375 Output: "7219856259e3" Explanation: The product is 7219856259000.   Constraints: 1 <= left <= right <= 10000
class Solution: def abbreviateProduct(self, left: int, right: int) -> str: cur = 1 C = 0 ok = True for x in range(left, right + 1): cur *= x while cur%10 == 0: C += 1 cur //= 10 if cur > 10**10: ok = False cur %= 10**6 if ok: return str(cur) + "e" + str(C) else: suff = str(cur)[-5:].zfill(5) + "e" + str(C) cur = 1 for x in range(left, right + 1): cur *= x while cur>10**6: cur /= 10 pref = str(cur)[:5] return pref + "..." + suff
cb8986
435fc8
You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Count all trailing zeros in the product and remove them. Let us denote this count as C. For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf> denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged. For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567. Finally, represent the product as a string "<pre>...<suf>eC". For example, 12345678987600000 will be represented as "12345...89876e5". Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].   Example 1: Input: left = 1, right = 4 Output: "24e0" Explanation: The product is 1 × 2 × 3 × 4 = 24. There are no trailing zeros, so 24 remains the same. The abbreviation will end with "e0". Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further. Thus, the final representation is "24e0". Example 2: Input: left = 2, right = 11 Output: "399168e2" Explanation: The product is 39916800. There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with "e2". The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further. Hence, the abbreviated product is "399168e2". Example 3: Input: left = 371, right = 375 Output: "7219856259e3" Explanation: The product is 7219856259000.   Constraints: 1 <= left <= right <= 10000
class Solution(object): def abbreviateProduct(self, left, right): """ :type left: int :type right: int :rtype: str """ def countZero(left, right): count2, count5 = 0, 0 for x in range(left, right + 1): while x%2 == 0: count2 += 1 x /= 2 while x%5 == 0: count5 += 1 x /= 5 return min(count2, count5) def calLastFive(left, right, zeros): mod = 100000 res = 1 count2, count5 = zeros, zeros tmp, maxi = 1, 10**10 for x in range(left, right + 1): while x%2 == 0 and count2 > 0: x /= 2 count2 -= 1 while x%5 == 0 and count5 > 0: x /= 5 count5 -= 1 res = (res*x)%mod tmp = tmp*x if tmp >= maxi: tmp = maxi + 1 return res, tmp v = countZero(left, right) lastFives, prods = calLastFive(left, right, v) maxi = 10**10 if prods < maxi: return str(prods) + "e" + str(v) else: sumLog10 = 0 for x in range(left, right + 1): sumLog10 += log10(x) sumLog10 -= floor(sumLog10) firstFives = int(floor(10**(sumLog10 + 4))) first = str(firstFives) last = str(lastFives) while len(last) < 5: last = "0" + last return first + "..." + last + "e" + str(v)
7e6e28
2c55ef
You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree.   Example 1: Input: root = [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown. Example 2: Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.   Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val == 0
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from functools import lru_cache import sys sys.setrecursionlimit(2000) class Solution: def minCameraCover(self, root): """ :type root: TreeNode :rtype: int """ @lru_cache(None) def get(root, has_in_parent, force): if root is None: return 0 result = get(root.left, True, False) + get(root.right, True, False) + 1 if has_in_parent: result = min(result, get(root.left, False, False) + get(root.right, False, False)) else: if not force: if root.left: result = min(result, get(root.left, False, True) + get(root.right, False, False)) if root.right: result = min(result, get(root.right, False, True) + get(root.left, False, False)) return result return get(root, False, False)
8970af
2c55ef
You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree.   Example 1: Input: root = [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown. Example 2: Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.   Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val == 0
# 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 minCameraCover(self, root): """ :type root: TreeNode :rtype: int """ topo = [] q = [root] while q: topo.extend(q) q = [v for u in q for v in (u.left, u.right) if v] c0 = {None:0} # min cover without camera on node c1 = {None:1} # min cover with camera on node c2 = {None:0} # min cover of children for node in reversed(topo): c0[node] = min(c0[node.left] + c1[node.right], c1[node.left] + c0[node.right], c1[node.left] + c1[node.right]) c1[node] = 1 + c2[node.left] + c2[node.right] c2[node] = min(c0[node], c1[node], min(c0[node.left], c1[node.left]) + min(c0[node.right], c1[node.right])) return min(c0[root], c1[root])
76b99d
0ae9b0
An array nums of length n is beautiful if: nums is a permutation of the integers in the range [1, n]. For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.   Example 1: Input: n = 4 Output: [2,1,4,3] Example 2: Input: n = 5 Output: [3,1,2,5,4]   Constraints: 1 <= n <= 1000
class Solution: def beautifulArray(self, N): """ :type N: int :rtype: List[int] """ if N==1: return [1] else: l=self.beautifulArray(N//2) r=self.beautifulArray(N-N//2) return [x*2 for x in l]+[x*2-1 for x in r]
eec6ee
0ae9b0
An array nums of length n is beautiful if: nums is a permutation of the integers in the range [1, n]. For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.   Example 1: Input: n = 4 Output: [2,1,4,3] Example 2: Input: n = 5 Output: [3,1,2,5,4]   Constraints: 1 <= n <= 1000
class Solution(object): def beautifulArray(self, n): def fill(low, high, nums): if low > high: return if low == high: seq[low] = nums[0] return odds = [] evens = [] for i, num in enumerate(nums): if i & 1: odds.append(num) else: evens.append(num) fill(low, low + len(evens) - 1, evens) fill(low + len(evens), high, odds) seq = [None] * n nums = [i+1 for i in range(n)] fill(0, n-1, nums) return seq
636052
a33c32
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 10^9 + 7. Note that you need to maximize the answer before taking the mod and not after taking it.   Example 1: Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) Example 2: Input: root = [1,null,2,3,4,null,null,5,6] Output: 90 Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)   Constraints: The number of nodes in the tree is in the range [2, 5 * 10000]. 1 <= Node.val <= 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 maxProduct(self, root): MOD = 10**9 + 7 self.s = 0 def dfs(node): if node: self.s += node.val dfs(node.left) dfs(node.right) dfs(root) self.ans = float('-inf') def dfs2(node): if not node: return 0 st = node.val + dfs2(node.left) + dfs2(node.right) cand = st * (self.s - st) if cand > self.ans: self.ans = cand return st dfs2(root) return self.ans % MOD
e04322
a33c32
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 10^9 + 7. Note that you need to maximize the answer before taking the mod and not after taking it.   Example 1: Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) Example 2: Input: root = [1,null,2,3,4,null,null,5,6] Output: 90 Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)   Constraints: The number of nodes in the tree is in the range [2, 5 * 10000]. 1 <= Node.val <= 10000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxProduct(self, root: TreeNode) -> int: def tot(node): if not node: return 0 return tot(node.left) + tot(node.right) + node.val def dfs(node, s): if not node: return 0, 0 p1, q1 = dfs(node.left, s) p2, q2 = dfs(node.right, s) p = p1 + p2 + node.val return p, max(q1, q2, p * (s - p)) s = tot(root) return dfs(root, s)[1] % 1000000007
0c1cf4
f2a469
(This problem is an interactive problem.) Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship. You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary. Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle. Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. Example : Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] Output: 3 Explanation: From [0,0] to [4,4] we can count 3 ships within the range. Example 2: Input: ans = [[1,1],[2,2],[3,3]], topRight = [1000,1000], bottomLeft = [0,0] Output: 3 Constraints: On the input ships is only given to initialize the map internally. You must solve this problem "blindfolded". In other words, you must find the answer using the given hasShips API, without knowing the ships position. 0 <= bottomLeft[0] <= topRight[0] <= 1000 0 <= bottomLeft[1] <= topRight[1] <= 1000 topRight != bottomLeft
# """ # This is Sea's API interface. # You should not implement it, or speculate about its implementation # """ #class Sea(object): # def hasShips(self, topRight, bottomLeft): # """ # :type topRight: Point # :type bottomLeft: Point # :rtype bool # """ # #class Point(object): # def __init__(self, x, y): # self.x = x # self.y = y class Solution(object): def countShips(self, sea, topRight, bottomLeft): """ :type sea: Sea :type topRight: Point :type bottomLeft: Point :rtype: integer """ def query(x1, y1, x2, y2): return 1 if sea.hasShips(Point(x2, y2), Point(x1, y1)) else 0 def search(x1, y1, x2, y2): if x1==x2 and y1==y2: return query(x1, y1, x2, y2) ans = 0 if x2 - x1 >= y2 - y1: xm = (x1 + x2) / 2 #x1..xm , xm+1..x2 q1 = query(x1, y1, xm, y2) q2 = query(xm+1, y1, x2, y2) if q1: ans += search(x1, y1, xm, y2) if q2: ans += search(xm+1, y1, x2, y2) else: ym = (y1+y2)/2 q1 = query(x1,y1,x2,ym) q2 = query(x1,ym+1,x2,y2) if q1: ans += search(x1, y1, x2, ym) if q2: ans += search(x1, ym+1, x2, y2) return ans return search(bottomLeft.x, bottomLeft.y, topRight.x, topRight.y)
18fe1b
f2a469
(This problem is an interactive problem.) Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship. You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary. Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle. Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. Example : Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] Output: 3 Explanation: From [0,0] to [4,4] we can count 3 ships within the range. Example 2: Input: ans = [[1,1],[2,2],[3,3]], topRight = [1000,1000], bottomLeft = [0,0] Output: 3 Constraints: On the input ships is only given to initialize the map internally. You must solve this problem "blindfolded". In other words, you must find the answer using the given hasShips API, without knowing the ships position. 0 <= bottomLeft[0] <= topRight[0] <= 1000 0 <= bottomLeft[1] <= topRight[1] <= 1000 topRight != bottomLeft
# """ # This is Sea's API interface. # You should not implement it, or speculate about its implementation # """ #class Sea(object): # def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool: # #class Point(object): # def __init__(self, x: int, y: int): # self.x = x # self.y = y class Solution(object): def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int: if not sea.hasShips(topRight, bottomLeft): return 0 x0, y0 = bottomLeft.x, bottomLeft.y x1, y1 = topRight.x, topRight.y if x0 == x1 and y0 == y1: return 1 xm = (x0 + x1) // 2 ym = (y0 + y1) // 2 tot = self.countShips(sea, Point(xm, ym), bottomLeft) if xm < x1: tot += self.countShips(sea, Point(x1, ym), Point(xm + 1, y0)) if ym < y1: tot += self.countShips(sea, Point(xm, y1), Point(x0, ym + 1)) if xm < x1 and ym <y1: tot += self.countShips(sea, topRight, Point(xm + 1, ym + 1)) return tot
f3352e
bd0019
You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of times: Pick any element from arr and increase or decrease it by 1. Return the minimum number of operations such that the sum of each subarray of length k is equal. A subarray is a contiguous part of the array.   Example 1: Input: arr = [1,4,1,3], k = 2 Output: 1 Explanation: we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 Example 2: Input: arr = [2,5,5,7], k = 3 Output: 5 Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15   Constraints: 1 <= k <= arr.length <= 100000 1 <= arr[i] <= 10^9
class Solution(object): def makeSubKSumEqual(self, arr, k): """ :type arr: List[int] :type k: int :rtype: int """ n = len(arr) def gcd(a, b): if b == 0: return a return gcd(b, a % b) g = gcd(n, k) data = [[] for i in range(g)] for i in range(n): data[i % g].append(arr[i]) ans = 0 for i in range(g): d = sorted(data[i]) p = d[len(d) // 2] for _d in d: ans += abs(_d - p) return ans
561ef6
bd0019
You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of times: Pick any element from arr and increase or decrease it by 1. Return the minimum number of operations such that the sum of each subarray of length k is equal. A subarray is a contiguous part of the array.   Example 1: Input: arr = [1,4,1,3], k = 2 Output: 1 Explanation: we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 Example 2: Input: arr = [2,5,5,7], k = 3 Output: 5 Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15   Constraints: 1 <= k <= arr.length <= 100000 1 <= arr[i] <= 10^9
class Solution: def makeSubKSumEqual(self, arr: List[int], k: int) -> int: def solve(a): a.sort() mid = a[len(a) // 2] res = 0 for x in a: res += abs(x - mid) return res n = len(arr) cycle = gcd(n, k) ans = 0 for i in range(cycle): ans += solve(arr[i::cycle]) return ans
a87cb6
fa2454
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.   Example 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets. Example 2: Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. Example 3: Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets.   Constraints: 1 <= triplets.length <= 100000 triplets[i].length == target.length == 3 1 <= ai, bi, ci, x, y, z <= 1000
class Solution: def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: a = b = c = 0 for i in triplets: if all(i[j]<=target[j] for j in range(3)): a = max(a, i[0]) b = max(b, i[1]) c = max(c, i[2]) return a==target[0] and b==target[1] and c==target[2]
98c452
fa2454
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.   Example 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets. Example 2: Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. Example 3: Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets.   Constraints: 1 <= triplets.length <= 100000 triplets[i].length == target.length == 3 1 <= ai, bi, ci, x, y, z <= 1000
class Solution(object): def mergeTriplets(self, triplets, target): """ :type triplets: List[List[int]] :type target: List[int] :rtype: bool """ arr=triplets for i in range(3): nr=[] for j in arr: if j[i]<=target[i]: nr.append(j) arr=nr[:] ans=[0,0,0] for i in arr: for j in range(3): ans[j]=max(ans[j],i[j]) return ans==target
ad1e66
4f88b4
You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s.   Example 1: Input: s = "3242415" Output: 5 Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps. Example 2: Input: s = "12345678" Output: 1 Example 3: Input: s = "213123" Output: 6 Explanation: "213123" is the longest awesome substring, we can form the palindrome "2^31132" with some swaps.   Constraints: 1 <= s.length <= 100000 s consists only of digits.
class Solution(object): def longestAwesome(self, S): P = [0] for c in S: x = int(c) P.append(P[-1]) P[-1] ^= 1 << x first = {} # q ^ p == 0 or 1 legal = {0} ans = 0 for x in xrange(10): legal.add(1 << x) # print("!", P) for j, q in enumerate(P): for leg in legal: ideal = q ^ leg i = first.get(ideal, None) if i is not None: cand = j - i if cand>ans:ans=cand first.setdefault(q, j) # print("!", first) return ans
942d33
4f88b4
You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s.   Example 1: Input: s = "3242415" Output: 5 Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps. Example 2: Input: s = "12345678" Output: 1 Example 3: Input: s = "213123" Output: 6 Explanation: "213123" is the longest awesome substring, we can form the palindrome "2^31132" with some swaps.   Constraints: 1 <= s.length <= 100000 s consists only of digits.
class Solution: def longestAwesome(self, s: str) -> int: now = 0 f = {} f[0] = -1 ret = 0 for i in range(len(s)): x = int(s[i]) now ^= (1 << x) if now not in f: f[now] = i ret = max(i - f[now], ret) for j in range(10): tmp = now ^ (1 << j) if tmp in f: ret = max(i - f[tmp], ret) return ret
8cd515
addc64
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.   Example 1: Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 Output: [0,1,2,3,5] Explanation: At time 0, person 0 shares the secret with person 1. At time 5, person 1 shares the secret with person 2. At time 8, person 2 shares the secret with person 3. At time 10, person 1 shares the secret with person 5.​​​​ Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. Example 2: Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 Output: [0,1,3] Explanation: At time 0, person 0 shares the secret with person 3. At time 2, neither person 1 nor person 2 know the secret. At time 3, person 3 shares the secret with person 0 and person 1. Thus, people 0, 1, and 3 know the secret after all the meetings. Example 3: Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 Output: [0,1,2,3,4] Explanation: At time 0, person 0 shares the secret with person 1. At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. Note that person 2 can share the secret at the same time as receiving it. At time 2, person 3 shares the secret with person 4. Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.   Constraints: 2 <= n <= 100000 1 <= meetings.length <= 100000 meetings[i].length == 3 0 <= xi, yi <= n - 1 xi != yi 1 <= timei <= 100000 1 <= firstPerson <= n - 1
class Solution: def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: from collections import defaultdict m = defaultdict(list) for i, j, k in meetings: m[k].append((i, j)) know_secret = {0, firstPerson} for _, ms in sorted(m.items()): border = set() adj_list = defaultdict(set) for i, j in ms: if i in know_secret: border.add(i) if j in know_secret: border.add(j) adj_list[i].add(j) adj_list[j].add(i) visited = set() while border: i = border.pop() if i in visited: continue visited.add(i) know_secret.add(i) for j in adj_list[i]: border.add(j) return list(know_secret)