sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
ff718e
e03afc
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array.   Example 1: Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. Example 2: Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. Example 3: Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= p <= 10^9
INF = 1 << 60 class Solution: def minSubarray(self, A: List[int], p: int) -> int: idx = {} n = len(A) S = [0] * (n + 1) for i in range(n): S[i + 1] = S[i] + A[i] s = S[-1] % p if s == 0: return 0 ans = INF for i, v in enumerate(S): l = (v - s) % p if l in idx: ans = min(ans, i - idx[l]) idx[v % p] = i if ans == INF or ans == n: ans = -1 return ans
c8e796
e03afc
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array.   Example 1: Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. Example 2: Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. Example 3: Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= p <= 10^9
class Solution(object): def minSubarray(self, nums, p): """ :type nums: List[int] :type p: int :rtype: int """ s = sum(nums) % p if s==0: return 0 lp = {0:-1} n = len(nums) i, c=0, 0 rc = -1 while i<n: c += nums[i] c %= p # c-x = s ev = (c-s+p)%p if ev in lp: cc = i-lp[ev] if rc<0 or rc>cc: rc=cc lp[c] = i i+=1 if rc==n: rc=-1 return rc
bdea0d
02d433
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Every song is played at least once. A song can only be played again only if k other songs have been played. Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 3, goal = 3, k = 1 Output: 6 Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. Example 2: Input: n = 2, goal = 3, k = 0 Output: 6 Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. Example 3: Input: n = 2, goal = 3, k = 1 Output: 2 Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].   Constraints: 0 <= k < n <= goal <= 100
class Solution(object): def numMusicPlaylists(self, N, L, K): """ :type N: int :type L: int :type K: int :rtype: int """ M = 10**9 + 7 # ways(t, p) = ways to play p different songs in t time # ways(t, p) = ways(t-1, p-1) * (N-p) [NEW SONG] # + ways(t-1, p) * max(p-K, 0) # 1 0 0 # 0 3 ways = [1] + [0]*N for _ in xrange(L): ways = [0] + [(ways[p-1]*(N-p+1) + ways[p]*max(p-K,0)) % M for p in xrange(1,N+1)] return ways[-1]
01abb5
02d433
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Every song is played at least once. A song can only be played again only if k other songs have been played. Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 3, goal = 3, k = 1 Output: 6 Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. Example 2: Input: n = 2, goal = 3, k = 0 Output: 6 Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. Example 3: Input: n = 2, goal = 3, k = 1 Output: 2 Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].   Constraints: 0 <= k < n <= goal <= 100
class Solution: def numMusicPlaylists(self, N, L, K): """ :type N: int :type L: int :type K: int :rtype: int """ mod = 10 ** 9 + 7 dp = [[0 for _ in range(N + 1)] for _ in range(L + 1)] dp[0][0] = 1 for i in range(1, L + 1): for j in range(1, N + 1): dp[i][j] = (dp[i][j] + dp[i - 1][j - 1] * (N - j + 1) % mod) % mod if j > K: dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - K) % mod) % mod return dp[L][N]
7bacc4
3211bc
You are given a 0-indexed integer array nums of length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime. For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1. Return the smallest index i at which the array can be split validly or -1 if there is no such split. Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.   Example 1: Input: nums = [4,7,8,15,3,5] Output: 2 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. The only valid split is at index 2. Example 2: Input: nums = [4,7,15,8,3,5] Output: -1 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. There is no valid split.   Constraints: n == nums.length 1 <= n <= 10000 1 <= nums[i] <= 1000000
M = 10 ** 6 primes = [] is_prime = [True] * (M + 1) min_prime = list(range(M + 1)) for i in range(2, M + 1): if is_prime[i]: primes.append(i) for p in primes: if i * p > M: break is_prime[i * p] = False min_prime[i * p] = p if i % p == 0: break def fac(a): c = Counter() while a > 1: b = min_prime[a] a //= b c[b] += 1 return c class Solution: def findValidSplit(self, nums: List[int]) -> int: n = len(nums) l = Counter() r = Counter() for a in nums: r += fac(a) cnt = 0 for i in range(n-1): items = fac(nums[i]).items() for k, v in items: if l[k] == 0 and r[k] > 0: cnt += 1 l[k] += v for k, v in items: if l[k] > 0 and r[k] == v: cnt -= 1 r[k] -= v if cnt == 0: return i return -1
ce06cb
3211bc
You are given a 0-indexed integer array nums of length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime. For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1. Return the smallest index i at which the array can be split validly or -1 if there is no such split. Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.   Example 1: Input: nums = [4,7,8,15,3,5] Output: 2 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. The only valid split is at index 2. Example 2: Input: nums = [4,7,15,8,3,5] Output: -1 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. There is no valid split.   Constraints: n == nums.length 1 <= n <= 10000 1 <= nums[i] <= 1000000
class Solution(object): def findValidSplit(self, nums): """ :type nums: List[int] :rtype: int """ m, n = defaultdict(int), defaultdict(int) for i in range(len(nums)): x = nums[i] for j in range(2, int(sqrt(x)) + 1): while not x % j: n[j], x = n[j] + 1, x / j n[x] += 1 if x > 1 else 0 for i in range(len(nums) - 1): for j in range(2, int(sqrt(nums[i])) + 1): while not nums[i] % j: n[j], m[j], nums[i] = n[j] - 1, m[j] + 1, nums[i] / j n[nums[i]], m[nums[i]], f = n[nums[i]] - (1 if nums[i] > 1 else 0), m[nums[i]] + (1 if nums[i] > 1 else 0), 1 for x in m.keys(): f &= not n[x] if f: return i return -1
6b73eb
24c104
There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti. Implement the Graph class: Graph(int n, int[][] edges) initializes the object with n nodes and the given edges. addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one. int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.   Example 1: Input ["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] Output [null, 6, -1, null, 6] Explanation Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.   Constraints: 1 <= n <= 100 0 <= edges.length <= n * (n - 1) edges[i].length == edge.length == 3 0 <= fromi, toi, from, to, node1, node2 <= n - 1 1 <= edgeCosti, edgeCost <= 10^6 There are no repeated edges and no self-loops in the graph at any point. At most 100 calls will be made for addEdge. At most 100 calls will be made for shortestPath.
class Graph: def __init__(self, n: int, edges: List[List[int]]): self.n = n self.graph = defaultdict(list) for edge in edges: self.addEdge(edge) def addEdge(self, edge: List[int]) -> None: x, y, z = edge self.graph[x].append((y, z)) def shortestPath(self, node1: int, node2: int) -> int: START_NODE = node1 distances = [inf] * self.n distances[START_NODE] = 0 heap = [(0, START_NODE)] while heap: cur_dist, cur_node = heappop(heap) if cur_node == node2: return cur_dist if cur_dist > distances[cur_node]: continue for nei, w in self.graph[cur_node]: dist = cur_dist + w if dist < distances[nei]: distances[nei] = dist heappush(heap, (dist, nei)) return -1 # Your Graph object will be instantiated and called as such: # obj = Graph(n, edges) # obj.addEdge(edge) # param_2 = obj.shortestPath(node1,node2)
123965
24c104
There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti. Implement the Graph class: Graph(int n, int[][] edges) initializes the object with n nodes and the given edges. addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one. int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.   Example 1: Input ["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] Output [null, 6, -1, null, 6] Explanation Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.   Constraints: 1 <= n <= 100 0 <= edges.length <= n * (n - 1) edges[i].length == edge.length == 3 0 <= fromi, toi, from, to, node1, node2 <= n - 1 1 <= edgeCosti, edgeCost <= 10^6 There are no repeated edges and no self-loops in the graph at any point. At most 100 calls will be made for addEdge. At most 100 calls will be made for shortestPath.
class Graph(object): def __init__(self, n, edges): """ :type n: int :type edges: List[List[int]] """ nei = [set() for _ in range(n)] for a, b, c in edges: nei[a].add((b,c)) self.nei = nei self.dd = [0]*n self.n = n def addEdge(self, edge): """ :type edge: List[int] :rtype: None """ a, b, c = edge self.nei[a].add((b,c)) def shortestPath(self, node1, node2): """ :type node1: int :type node2: int :rtype: int """ a, b = node1, node2 if a==b: return 0 dd = self.dd n = self.n for i in range(n): dd[i]=0x7ffffffff dd[a]=0 h = [(0, a)] nei = self.nei mk = [False]*n while True: while h: d, i = h[0] if not mk[i]: break heappop(h) if not h: break d, i = heappop(h) mk[i]=True for x, c in nei[i]: nd = c+d if dd[x]>nd: dd[x]=nd heappush(h, (nd, x)) if not mk[b]: return -1 return dd[b] # Your Graph object will be instantiated and called as such: # obj = Graph(n, edges) # obj.addEdge(edge) # param_2 = obj.shortestPath(node1,node2)
82e7a8
9336a6
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 10^9 + 7.   Example 1: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 Output: 60 Explanation: We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60. Example 2: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 Output: 68 Explanation: This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. Example 3: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 Output: 72   Constraints: 1 <= k <= n <= 100000 speed.length == n efficiency.length == n 1 <= speed[i] <= 100000 1 <= efficiency[i] <= 10^8
class Solution(object): def maxPerformance(self, N, S, E, K): #n, speed, efficiency, k): """ :type n: int :type speed: List[int] :type efficiency: List[int] :type k: int :rtype: int """ MOD = 10**9 + 7 # max (sum S_i) * (min E_i) , at most K guys people = zip(E, S) people.sort(reverse=True) ans = 0 pq = [] pqsum = 0 for e, s in people: # now considering min effic is e heapq.heappush(pq, s) pqsum += s while len(pq) > K: pqsum -= heapq.heappop(pq) cand = pqsum * e if cand>ans: ans=cand return ans % MOD
904f2d
9336a6
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 10^9 + 7.   Example 1: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 Output: 60 Explanation: We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60. Example 2: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 Output: 68 Explanation: This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. Example 3: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 Output: 72   Constraints: 1 <= k <= n <= 100000 speed.length == n efficiency.length == n 1 <= speed[i] <= 100000 1 <= efficiency[i] <= 10^8
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: # minimum efficiency among their engineers ses = [(s, e) for s, e in zip(speed, efficiency)] ses.sort(key=lambda x : (-x[1], x[0])) speed_sum = 0 window = [] mx = 0 for s, e in ses: heapq.heappush(window, s) speed_sum += s while len(window) > k: speed_sum -= heapq.heappop(window) mx = max(mx, e * speed_sum) return mx % 1000000007
415993
6e9a1b
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.   Example 1: Input: encoded = [3,1] Output: [1,2,3] Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3]   Constraints: 3 <= n < 100000 n is odd. encoded.length == n - 1
class Solution(object): def decode(self, A): n = len(A) + 1 a = 0 for i in xrange(1, n + 1): a ^= i for i in A[::-2]: a ^= i res = [a] for a in A: res.append(res[-1] ^ a) return res
7fb7f4
6e9a1b
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.   Example 1: Input: encoded = [3,1] Output: [1,2,3] Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3]   Constraints: 3 <= n < 100000 n is odd. encoded.length == n - 1
class Solution: def decode(self, a: List[int]) -> List[int]: n=len(a)+1 s=0 for i in range(1,n+1): s^=i p=0 for i in range(n-1): p^=a[i] a[i]=p s^=a[i] # print(n,a) # print(s) b=[s] for x in a: b.append(x^s) return b
9a4929
22e3c5
You are given a positive integer k. You are also given: a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. The two arrays contain integers from 1 to k. You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0. The matrix should also satisfy the following conditions: The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1. The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1. Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.   Example 1: Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] Output: [[3,0,0],[0,0,1],[0,2,0]] Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. The row conditions are the following: - Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. - Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. The column conditions are the following: - Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. - Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. Note that there may be multiple correct answers. Example 2: Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] Output: [] Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. No matrix can satisfy all the conditions, so we return the empty matrix.   Constraints: 2 <= k <= 400 1 <= rowConditions.length, colConditions.length <= 10000 rowConditions[i].length == colConditions[i].length == 2 1 <= abovei, belowi, lefti, righti <= k abovei != belowi lefti != righti
def toposort(graph): res, found = [], [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: res.append(~node) elif not found[node]: found[node] = 1 stack.append(~node) stack += graph[node] # cycle check for node in res: if any(found[nei] for nei in graph[node]): return None found[node] = 0 return res[::-1] class Solution: def buildMatrix(self, k: int, above_conditions: List[List[int]], left_conditions: List[List[int]]) -> List[List[int]]: above = [[] for _ in range(k)] for x, y in above_conditions: above[x - 1].append(y - 1) left = [[] for _ in range(k)] for x, y in left_conditions: left[x - 1].append(y - 1) above_order, left_order = toposort(above), toposort(left) if above_order is None or left_order is None: return [] return [ [j + 1 if j == k else 0 for k in left_order] for i, j in enumerate(above_order) ]
3fac99
22e3c5
You are given a positive integer k. You are also given: a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. The two arrays contain integers from 1 to k. You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0. The matrix should also satisfy the following conditions: The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1. The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1. Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.   Example 1: Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] Output: [[3,0,0],[0,0,1],[0,2,0]] Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. The row conditions are the following: - Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. - Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. The column conditions are the following: - Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. - Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. Note that there may be multiple correct answers. Example 2: Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] Output: [] Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. No matrix can satisfy all the conditions, so we return the empty matrix.   Constraints: 2 <= k <= 400 1 <= rowConditions.length, colConditions.length <= 10000 rowConditions[i].length == colConditions[i].length == 2 1 <= abovei, belowi, lefti, righti <= k abovei != belowi lefti != righti
class Solution(object): def buildMatrix(self, k, rowConditions, colConditions): """ :type k: int :type rowConditions: List[List[int]] :type colConditions: List[List[int]] :rtype: List[List[int]] """ def s(c): g, p, q, i, r = [[] for _ in range(k + 1)], [0] * (k + 1), deque(), 0, [0] * k for d, e in c: g[d].append(e) p[e] += 1 for j in range(1, k + 1): if not p[j]: q.append(j) while len(q): r[i], i = q.popleft(), i + 1 for c in g[r[i - 1]]: p[c] -= 1 if not p[c]: q.append(c) return r if i == k else None r, a, b, i = [[0] * k for _ in range(k)], s(rowConditions), s(colConditions), [0] * (k + 1) if not a or not b: return [] for j in range(len(b)): i[b[j]] = j for j in range(len(a)): r[j][i[a[j]]] = a[j] return r
0c03cf
627b0d
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.   Example 1: Input: target = [5,1,3], arr = [9,4,2,3,4] Output: 2 Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. Example 2: Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] Output: 3   Constraints: 1 <= target.length, arr.length <= 100000 1 <= target[i], arr[i] <= 10^9 target contains no duplicates.
from collections import defaultdict class Solution(object): def minOperations(self, target, arr): """ :type target: List[int] :type arr: List[int] :rtype: int """ # sort arr by target order to transform # longest common subsequence -> longest increasing subsequence # use whatever to make this n log n. m = len(target) d = {} for i, v in enumerate(target): assert v not in d d[v] = i 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 v in arr: if v not in d: continue i = d[v] _upd(i, _get(i) + 1) return m - max(fen)
9950d3
627b0d
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.   Example 1: Input: target = [5,1,3], arr = [9,4,2,3,4] Output: 2 Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. Example 2: Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] Output: 3   Constraints: 1 <= target.length, arr.length <= 100000 1 <= target[i], arr[i] <= 10^9 target contains no duplicates.
class Solution: def minOperations(self, target: List[int], arr: List[int]) -> int: dic = {} for i, num in enumerate(target): dic[num] = i n = len(arr) narr = [] for i in range(n): if arr[i] in dic: narr.append(dic[arr[i]]) res = [] for num in narr: idx = bisect.bisect_left(res, num) if idx == len(res): res.append(num) else: res[idx] = num return len(target) - len(res)
646482
2744e4
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).   Example 1: Input: grid = [[0,0,1],[1,1,0],[1,0,0]] Output: 3 Example 2: Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]] Output: -1 Explanation: All rows are similar, swaps have no effect on the grid. Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,1]] Output: 0   Constraints: n == grid.length == grid[i].length 1 <= n <= 200 grid[i][j] is either 0 or 1
class Solution: def minSwaps(self, grid: List[List[int]]) -> int: n = len(grid) zv = [-1] * n for i in range(n): for j in range(n): if grid[i][j] > 0: zv[i] = j for idx, val in enumerate(sorted(zv)): if val > idx: return -1 ans = 0 for i in range(n): if zv[i] <= i: continue t = zv[i] j = i + 1 while zv[j] > i: zv[j], t = t, zv[j] j += 1 zv[i], zv[j] = zv[j], t ans += j - i return ans
a7b042
2744e4
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).   Example 1: Input: grid = [[0,0,1],[1,1,0],[1,0,0]] Output: 3 Example 2: Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]] Output: -1 Explanation: All rows are similar, swaps have no effect on the grid. Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,1]] Output: 0   Constraints: n == grid.length == grid[i].length 1 <= n <= 200 grid[i][j] is either 0 or 1
class Solution(object): def minSwaps(self, grid): """ :type grid: List[List[int]] :rtype: int """ n = len(grid) a = [0]*n for i, row in enumerate(grid): for j in reversed(row): if j == 1: break a[i] += 1 r = 0 for i in xrange(n): need = n-1-i if a[i] >= need: continue for j in xrange(i+1, n): if a[j] >= need: break else: return -1 r += j - i for k in xrange(j, i, -1): a[k] = a[k-1] return r
20cebd
3b1f75
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 100000.   Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc" Example 2: Input: s = "3[a2[c]]" Output: "accaccacc" Example 3: Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef"   Constraints: 1 <= s.length <= 30 s consists of lowercase English letters, digits, and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1, 300].
class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ kstack=[-1] sstack=[""] k=0 for i in xrange(len(s)): if s[i]>='0' and s[i]<='9': k=k*10+int(s[i]) elif s[i]=='[': kstack.append(k) sstack.append("") k=0 elif s[i]==']': tk,ts=kstack.pop(),sstack.pop() for j in xrange(tk): sstack[-1]+=ts else: sstack[-1]+=s[i] return sstack[-1]
6a9899
8d9c13
You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure. You always start to construct the left child node of the parent first if it exists. Example 1: Input: s = "4(2(3)(1))(6(5))" Output: [4,2,6,3,1,5] Example 2: Input: s = "4(2(3)(1))(6(5)(7))" Output: [4,2,6,3,1,5,7] Example 3: Input: s = "-4(2(3)(1))(6(5)(7))" Output: [-4,2,6,3,1,5,7] Constraints: 0 <= s.length <= 3 * 10000 s consists of digits, '(', ')', and '-' only.
# 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 str2tree(self, s): if not s: return None if '(' in s: ix = s.index('(') root = TreeNode(int(s[:ix])) s = s[ix:] else: root = TreeNode(int(s)) return root b = 0 for i, x in enumerate(s): if x == '(': b+=1 if x == ')': b-=1 if b == 0: break else: return root root.left = self.str2tree(s[1:i]) s = s[i+1:] if not s: return root root.right = self.str2tree(s[1:-1]) return root
559918
1a9e1a
Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal, or anti-diagonal. Example 1: Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]] Output: 3 Example 2: Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]] Output: 4 Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 10000 1 <= m * n <= 10000 mat[i][j] is either 0 or 1.
class Solution(object): def longestLine(self, M): """ :type M: List[List[int]] :rtype: int """ if not M or not M[0]: return 0 def f(stream): curr = best = 0 for c in stream: curr = (curr + 1) if c else 0 best = max(best, curr) return best def diagonals(M): r, c = len(M), len(M[0]) d1, d2 = {}, {} for i in xrange(r): for j in xrange(c): d1.setdefault(i+j,[]).append(M[i][j]) d2.setdefault(i-j,[]).append(M[i][j]) return d1.values() + d2.values() return max(map(f, M) + map(f, zip(*M)) + map(f, diagonals(M)))
7b3235
c287be
You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray, return -1. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,3,4,3,1], threshold = 6 Output: 3 Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2. Note that this is the only valid subarray. Example 2: Input: nums = [6,5,6,5,8], threshold = 7 Output: 1 Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned. Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions. Therefore, 2, 3, 4, or 5 may also be returned.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], threshold <= 10^9
class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: n = len(nums) parent = [i for i in range(n)] sz = [1 for i in range(n)] def root(x): if x == parent[x]: return x parent[x] = root(parent[x]) return parent[x] def join(x, y): x, y = root(x), root(y) if x == y: return if sz[x] > sz[y]: x, y = y, x parent[x] = y sz[y] += sz[x] x = [(nums[i], i) for i in range(n)] x.sort(reverse=True) s = set() for e, i in x: s.add(i) if i-1 in s: join(i-1, i) if i+1 in s: join(i, i+1) cur = sz[root(i)] if threshold < e*cur: return cur return -1
f9767e
c287be
You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray, return -1. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,3,4,3,1], threshold = 6 Output: 3 Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2. Note that this is the only valid subarray. Example 2: Input: nums = [6,5,6,5,8], threshold = 7 Output: 1 Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned. Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions. Therefore, 2, 3, 4, or 5 may also be returned.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i], threshold <= 10^9
class Solution(object): def validSubarraySize(self, nums, threshold): """ :type nums: List[int] :type threshold: int :rtype: int """ n=len(nums) if n>threshold: return n l=[[float('-inf'),-1]] for i in range(n): while l[-1][0]>=nums[i]: del l[-1] l.append([nums[i],i]) for j in range(len(l)-1,0,-1): if l[j][0]>float(threshold)/(i-l[j-1][1]): return i-l[j-1][1] return -1
5c77a1
047405
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie. Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.   Example 1: Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]] Output: 10 Explanation: There are 2 contaminated regions. On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is: On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. Example 2: Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]] Output: 4 Explanation: Even though there is only one cell saved, there are 4 walls built. Notice that walls are only built on the shared boundary of two different cells. Example 3: Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]] Output: 13 Explanation: The region on the left only builds two new walls.   Constraints: m == isInfected.length n == isInfected[i].length 1 <= m, n <= 50 isInfected[i][j] is either 0 or 1. There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.
class Solution(object): def containVirus(self, grid): """ :type grid: List[List[int]] :rtype: int """ res = 0 self.walls = {} while True: lst = self.findRegions(grid) if not lst: return res for i, j in lst: for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if (i, j, ii, jj) not in self.walls and 0 <= ii < len(grid) and 0 <= jj < len(grid[0]) and grid[ii][jj] == 0: res += 1 self.walls[(i, j, ii, jj)] = 1 self.walls[(ii, jj, i, j)] = 1 # print i, j, ii, jj # print 'aaa' for i, j in lst: grid[i][j] = 2 self.spread(grid) def findRegions(self, grid): tmp = [] num = -1 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: lst, affect = self.findRegion(grid, i, j) num1 = len(set(affect)) if num1 > num: tmp = lst num = num1 for i in range(len(grid)): for j in range(len(grid[0])): grid[i][j] %= 10 return tmp def findRegion(self, grid, i, j): if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]): return [], [] if grid[i][j] == 0: return [], [(i, j)] if grid[i][j] != 1: return [], [] res = [(i, j)] affect = [] grid[i][j] += 10 for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if (i, j, ii, jj) not in self.walls: res1, a1 = self.findRegion(grid, ii, jj) res += res1 affect += a1 return res, affect def spread(self, grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if (i, j, ii, jj) not in self.walls and 0 <= ii < len(grid) and 0 <= jj < len(grid[0]) and grid[ii][jj] == 0: grid[ii][jj] = 11 for i in range(len(grid)): for j in range(len(grid[0])): grid[i][j] %= 10
03f663
047405
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie. Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.   Example 1: Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]] Output: 10 Explanation: There are 2 contaminated regions. On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is: On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. Example 2: Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]] Output: 4 Explanation: Even though there is only one cell saved, there are 4 walls built. Notice that walls are only built on the shared boundary of two different cells. Example 3: Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]] Output: 13 Explanation: The region on the left only builds two new walls.   Constraints: m == isInfected.length n == isInfected[i].length 1 <= m, n <= 50 isInfected[i][j] is either 0 or 1. There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.
from copy import deepcopy class Solution: def containVirus(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) a = grid for i in range(m): for j in range(n): if a[i][j] == 0: a[i][j] = 'S' elif a[i][j] == 1: a[i][j] = 'C' n_walls = 0 while True: #print(''.join(''.join(b) + '\n' for b in a)) #print('-----------------------------------') max_contam = (0, (-1, -1)) if sum(sum(1 for x in b if x == 'S') for b in a) == 0: break for i in range(m): for j in range(n): if a[i][j] != 'C': continue #a = deepcopy(orig_a) stack = [(i, j)] contams = set() oi, oj = i, j while stack: i, j = stack.pop() if a[i][j] == 'S': contams.add((i, j)) continue elif a[i][j] != 'C': continue a[i][j] = 'X' stack.append((i, j + 1)) if j + 1 < n else 0 stack.append((i, j - 1)) if j > 0 else 0 stack.append((i + 1, j)) if i + 1 < m else 0 stack.append((i - 1, j)) if i > 0 else 0 max_contam = max(max_contam, (len(contams), (oi, oj))) if max_contam[0] == 0 or max_contam[0] == m * n: break #print(max_contam) #print(''.join(''.join(b) + '\n' for b in a)) #print('-----------------------------------') for i in range(m): for j in range(n): if a[i][j] == 'X': a[i][j] = 'C' for i in [max_contam[1][0]]: for j in [max_contam[1][1]]: more_walls = 0 if a[i][j] != 'C': continue #a = deepcopy(orig_a) stack = [(i, j)] contams = set() while stack: i, j = stack.pop() if a[i][j] == 'S': more_walls += 1 contams.add((i, j)) continue elif a[i][j] != 'C': continue a[i][j] = 'W' stack.append((i, j + 1)) if j + 1 < n else 0 stack.append((i, j - 1)) if j > 0 else 0 stack.append((i + 1, j)) if i + 1 < m else 0 stack.append((i - 1, j)) if i > 0 else 0 #print(more_walls) #print(''.join(''.join(b) + '\n' for b in a)) #print('-----------------------------------') n_walls += more_walls a1 = deepcopy(a) for i in range(m): for j in range(n): if a[i][j] == 'C': if j + 1 < n and a[i][j + 1] == 'S': a1[i][j + 1] = 'C' if j > 0 and a[i][j - 1] == 'S': a1[i][j - 1] = 'C' if i + 1 < m and a[i + 1][j] == 'S': a1[i + 1][j] = 'C' if i > 0 and a[i - 1][j] == 'S': a1[i - 1][j] = 'C' a = a1 return n_walls
09b69e
382246
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: Input: target = [3,1,1,2] Output: 4 Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] Example 3: Input: target = [3,1,5,4,2] Output: 7 Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].   Constraints: 1 <= target.length <= 100000 1 <= target[i] <= 100000
class Solution(object): def minNumberOperations(self, A): res = 0 for a,b in zip([0] + A, A): res += max(0, b - a) return res
e7d5c2
382246
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: Input: target = [3,1,1,2] Output: 4 Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] Example 3: Input: target = [3,1,5,4,2] Output: 7 Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].   Constraints: 1 <= target.length <= 100000 1 <= target[i] <= 100000
class Solution: def minNumberOperations(self, target: List[int]) -> int: target.append(0) return sum([target[i]-target[i-1] for i in range(len(target)) if target[i]>target[i-1]])
114526
beae67
Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "0110", n = 3 Output: true Example 2: Input: s = "0110", n = 4 Output: false   Constraints: 1 <= s.length <= 1000 s[i] is either '0' or '1'. 1 <= n <= 10^9
class Solution: def queryString(self, S: str, N: int) -> bool: if N > (len(S) * (len(S) + 1) // 2): return False ok = [False] * (N + 1) ok[0] = True for i in range(len(S)): num = 0 for j in range(i, len(S)): num = num * 2 + int(S[j] == '1') if num > N: break ok[num] = True return all(ok)
d5b67f
beae67
Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "0110", n = 3 Output: true Example 2: Input: s = "0110", n = 4 Output: false   Constraints: 1 <= s.length <= 1000 s[i] is either '0' or '1'. 1 <= n <= 10^9
class Solution(object): def queryString(self, S, N): """ :type S: str :type N: int :rtype: bool """ seen = set() S = map(int, S) n = len(S) for i in range(n): c = 0 for j in range(i, n): c *= 2 c += S[j] if c > N: break seen.add(c) seen.discard(0) return len(seen) == N
67095e
d9c799
Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The rank is an integer starting from 1. If two elements p and q are in the same row or column, then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q) The rank should be as small as possible. The test cases are generated so that answer is unique under the given rules.   Example 1: Input: matrix = [[1,2],[3,4]] Output: [[1,2],[2,3]] Explanation: The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. Example 2: Input: matrix = [[7,7],[7,7]] Output: [[1,1],[1,1]] Example 3: Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]] Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 500 -10^9 <= matrix[row][col] <= 10^9
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek # https://www.youtube.com/watch?v=VLwVU3Bi0Ek class Solution: def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: ret = [row[:] for row in matrix] order = sorted([(matrix[i][j],i,j) for i in range(len(matrix)) for j in range(len(matrix[0]))]) row,col=[0]*len(matrix),[0]*len(matrix[0]) idx = 0 def get_groups(lst): # take list of ij dic = defaultdict(list) # group by i i_dic = defaultdict(list) j_dic = defaultdict(list) for idx in range(len(lst)): i_dic[lst[idx][0]].append(idx) for idx in range(len(lst)): j_dic[lst[idx][1]].append(idx) for entry in i_dic.values(): for idx in range(len(entry)-1): dic[entry[idx]].append(entry[idx+1]) dic[entry[idx+1]].append(entry[idx]) for entry in j_dic.values(): for idx in range(len(entry)-1): dic[entry[idx]].append(entry[idx+1]) dic[entry[idx+1]].append(entry[idx]) # print(dic) ret = [] seen = set() def dfs(idx): if idx in seen: return seen.add(idx) ret[-1].append(lst[idx]) for nxt in dic[idx]: dfs(nxt) for idx in range(len(lst)): if idx in seen: continue ret.append([]) dfs(idx) return ret while idx < len(order): val = order[idx][0] # they all get the same shit locs = [] while idx < len(order) and order[idx][0] == val: i,j=order[idx][1],order[idx][2] # new_val = max(new_val,row[i]+1,col[j]+1) locs.append([i,j]) idx += 1 # figure out new val for these by group groups = get_groups(locs) # print(groups) for grp in groups: new_val = 1 for i,j in grp: new_val = max(new_val,row[i]+1,col[j]+1) for i,j in grp: ret[i][j] = new_val row[i] = new_val col[j] = new_val return ret # 1 2 # 3 3 # 1 2 # 3 3
62673c
d9c799
Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The rank is an integer starting from 1. If two elements p and q are in the same row or column, then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q) The rank should be as small as possible. The test cases are generated so that answer is unique under the given rules.   Example 1: Input: matrix = [[1,2],[3,4]] Output: [[1,2],[2,3]] Explanation: The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. Example 2: Input: matrix = [[7,7],[7,7]] Output: [[1,1],[1,1]] Example 3: Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]] Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 500 -10^9 <= matrix[row][col] <= 10^9
from collections import defaultdict, Counter, deque class Solution(object): def matrixRankTransform(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ arr = matrix n, m = len(arr), len(arr[0]) loc = defaultdict(list) adj = defaultdict(list) for i, row in enumerate(arr): for j, val in enumerate(row): loc[(0,i,val)].append((i,j)) loc[(1,j,val)].append((i,j)) adj[(0,i,val)].append((1,j,val)) adj[(1,j,val)].append((0,i,val)) comp = {} comp_id = 0 for i, row in enumerate(arr): for j, val in enumerate(row): src = (0,i,val) if src in comp: continue q = deque() q.append(src) comp[src] = comp_id while q: u = q.popleft() for v in adj[u]: if v in comp: continue q.append(v) comp[v] = comp_id comp_id += 1 dep = [[] for _ in xrange(comp_id)] deg = [0]*comp_id for i in xrange(n): s = sorted(set(arr[i][j] for j in xrange(m))) for k in xrange(1, len(s)): src = comp[(0,i,s[k-1])] dst = comp[(0,i,s[k])] dep[src].append(dst) deg[dst] += 1 for j in xrange(m): s = sorted(set(arr[i][j] for i in xrange(n))) for k in xrange(1, len(s)): src = comp[(1,j,s[k-1])] dst = comp[(1,j,s[k])] dep[src].append(dst) deg[dst] += 1 q = [u for u in xrange(comp_id) if deg[u] == 0] rank = 1 comp_rank = [0]*comp_id while q: qq = [] for u in q: comp_rank[u] = rank for v in dep[u]: deg[v] -= 1 if deg[v] == 0: qq.append(v) q = qq rank += 1 res = [[0]*m for _ in xrange(n)] for i, row in enumerate(arr): for j, val in enumerate(row): res[i][j] = comp_rank[comp[(0,i,val)]] return res
26f102
778561
Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted. A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes. Example 1: Input: root = [5,6,1] Output: 6.00000 Explanation: For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4. For the node with value = 6 we have an average of 6 / 1 = 6. For the node with value = 1 we have an average of 1 / 1 = 1. So the answer is 6 which is the maximum. Example 2: Input: root = [0,null,1] Output: 1.00000 Constraints: The number of nodes in the tree is in the range [1, 10000]. 0 <= Node.val <= 100000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maximumAverageSubtree(self, root: TreeNode) -> float: ans = 0 def dfs(node): nonlocal ans if not node: return 0, 0 nl, sl = dfs(node.left) nr, sr = dfs(node.right) nc, sc = nl + nr + 1, sl + sr + node.val ans = max(ans, sc / nc) return nc, sc dfs(root) return ans
350d92
778561
Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted. A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes. Example 1: Input: root = [5,6,1] Output: 6.00000 Explanation: For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4. For the node with value = 6 we have an average of 6 / 1 = 6. For the node with value = 1 we have an average of 1 / 1 = 1. So the answer is 6 which is the maximum. Example 2: Input: root = [0,null,1] Output: 1.00000 Constraints: The number of nodes in the tree is in the range [1, 10000]. 0 <= 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 maximumAverageSubtree(self, root): """ :type root: TreeNode :rtype: float """ self.res = -float('inf') def helper(root): if not root: return [0, 0] n1,s1 = helper(root.left) n2,s2 = helper(root.right) n = n1+n2+1 s = s1+s2+root.val # print root.val,n,s self.res = max(self.res, s*1.0/n) return [n,s] helper(root) return self.res
0a1cc5
4a6420
A sequence x1, x2, ..., xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].   Example 1: Input: arr = [1,2,3,4,5,6,7,8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8]. Example 2: Input: arr = [1,3,7,11,12,14,18] Output: 3 Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].   Constraints: 3 <= arr.length <= 1000 1 <= arr[i] < arr[i + 1] <= 10^9
class Solution(object): def lenLongestFibSubseq(self, A): """ :type A: List[int] :rtype: int """ if len(A) < 3: return 0 s = set(A) def f(i, j): r = 2 a = A[i] b = A[j] while a + b in s: a, b, r = b, a + b, r + 1 return r r = max(f(i, j) for j in xrange(1, len(A)) for i in xrange(j)) return r if r >= 3 else 0
1bbb39
4a6420
A sequence x1, x2, ..., xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].   Example 1: Input: arr = [1,2,3,4,5,6,7,8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8]. Example 2: Input: arr = [1,3,7,11,12,14,18] Output: 3 Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].   Constraints: 3 <= arr.length <= 1000 1 <= arr[i] < arr[i + 1] <= 10^9
class Solution: def lenLongestFibSubseq(self, A): """ :type A: List[int] :rtype: int """ ans=0 dp=[{} for _ in range(len(A))] for i in range(1,len(A)): for j in range(i): tmp=A[i]-A[j] if tmp in dp[j]: dp[i][A[j]]=dp[j][tmp]+1 ans=max(ans,dp[i][A[j]]) else: dp[i][A[j]]=2 return ans
b99730
a59f35
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order.   Example 1: Input: nums = [10,6,5,8] Output: [10,8] Explanation: - 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. - 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. - 5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned. Example 2: Input: nums = [1,3,5,3] Output: [1,5] Explanation: - 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. - 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. - 3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 1000000
class Solution: def findLonely(self, nums: List[int]) -> List[int]: cnt = collections.Counter(nums) ans = [] for num in cnt: if cnt[num] == 1 and (num - 1) not in cnt and (num + 1) not in cnt: ans.append(num) return ans
ddd31d
a59f35
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order.   Example 1: Input: nums = [10,6,5,8] Output: [10,8] Explanation: - 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. - 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. - 5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned. Example 2: Input: nums = [1,3,5,3] Output: [1,5] Explanation: - 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. - 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. - 3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 1000000
from collections import Counter class Solution(object): def findLonely(self, nums): """ :type nums: List[int] :rtype: List[int] """ c = Counter(nums) return [k for k, v in c.iteritems() if v==1 and (k-1) not in c and (k+1) not in c]
ab6938
9c014d
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom. You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid. Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.   Example 1: Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"] Output: true Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1. There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed. Example 2: Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"] Output: false Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.   Constraints: 2 <= bottom.length <= 6 0 <= allowed.length <= 216 allowed[i].length == 3 The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}. All the values of allowed are unique.
class Solution: def pyramidTransition(self, bottom, allowed): """ :type bottom: str :type allowed: List[str] :rtype: bool """ def helper(layer): if len(layer) <= 1: return True new_set = [""] for i in range(len(layer)-1): prev_set = new_set new_set = [] if len(prev_set) == 0: break d, e = layer[i], layer[i+1] if (d, e) not in options: return False for top in options[(d, e)]: for poss in prev_set: new_set.append(poss + top) prev_set = new_set for item in prev_set: if helper(item): return True return False options = {} for d, e, a in allowed: options.setdefault((d,e), []) options[(d, e)].append(a) return helper(bottom)
91e6ea
9c014d
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom. You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid. Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.   Example 1: Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"] Output: true Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1. There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed. Example 2: Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"] Output: false Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.   Constraints: 2 <= bottom.length <= 6 0 <= allowed.length <= 216 allowed[i].length == 3 The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}. All the values of allowed are unique.
class Solution(object): def pyramidTransition(self, bottom, allowed): """ :type bottom: str :type allowed: List[str] :rtype: bool """ colors = [[0 for i in xrange(7)] for j in xrange(7)] for pair in allowed: a, b, c = [x for x in pair] a, b = ord(a) - ord('A'), ord(b) - ord('A') colors[a][b] |= 1 << (ord(c) - ord('A')) row = [1 << (ord(x) - ord('A')) for x in bottom] for i in xrange(1, len(row)): nextRows = [] for j in xrange(len(row) - 1): vals = 0 for v1 in xrange(7): if not row[j] & (1 << v1): continue for v2 in xrange(7): if row[j + 1] & (1 << v2): vals |= colors[v1][v2] if vals == 0: return False nextRows.append(vals) row = nextRows return True
0fc51a
344904
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of the element nums[k] of index = k. The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. We stop adding right before a duplicate element occurs in s[k]. Return the longest length of a set s[k].   Example 1: Input: nums = [5,4,0,3,1,6,2] Output: 4 Explanation: nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. One of the longest sets s[k]: s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} Example 2: Input: nums = [0,1,2] Output: 1   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] < nums.length All the values of nums are unique.
class Solution(object): def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) vis = [False] * n cycle = [None] * n longest = 1 for i in range(n): x = i cur = 0 while not vis[x]: cur += 1 vis[x] = True x = nums[x] longest = max(longest, cur) return longest
1e8679
344904
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of the element nums[k] of index = k. The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. We stop adding right before a duplicate element occurs in s[k]. Return the longest length of a set s[k].   Example 1: Input: nums = [5,4,0,3,1,6,2] Output: 4 Explanation: nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. One of the longest sets s[k]: s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} Example 2: Input: nums = [0,1,2] Output: 1   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] < nums.length All the values of nums are unique.
class Solution: def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 visited = [False] * len(nums) for i in range(len(nums)): if visited[i]: continue j = i count = 0 while not visited[j]: visited[j] = True j = nums[j] count += 1 ans = max(ans, count) return ans
65e3a1
c31942
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor.   Example 1: Input: n = 3 Output: 3 Explanation: The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 2: Input: n = 4 Output: 3 Explanation: The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 3: Input: n = 10 Output: 6 Explanation: The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side.   Constraints: 1 <= n <= 10^9
class Solution(object): def minimumBoxes(self, n): """ :type n: int :rtype: int """ s = 1 count = 0 res = 0 while count < n: for i in range(1,s+1): count += i res += 1 # print s,i,count,res if count >=n: break s+=1 return res
8bd2f6
c31942
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor.   Example 1: Input: n = 3 Output: 3 Explanation: The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 2: Input: n = 4 Output: 3 Explanation: The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 3: Input: n = 10 Output: 6 Explanation: The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side.   Constraints: 1 <= n <= 10^9
class Solution: def minimumBoxes(self, n: int) -> int: base, m = 0, 0 for i in range(1, 9999999) : if m + (base + i) <= n : base += i m += base else : break new_base = 0 for j in range(1, i+1) : if m + j <= n : new_base += 1 m += j else : break if not m == n : new_base += 1 return base + new_base
8700e2
9a061d
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid). The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.   Example 1: Input: code = "<DIV>This is the first line <![CDATA[<div>]]></DIV>" Output: true Explanation: The code is wrapped in a closed tag : <DIV> and </DIV>. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. Example 2: Input: code = "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>" Output: true Explanation: We first separate the code into : start_tag|tag_content|end_tag. start_tag -> "<DIV>" end_tag -> "</DIV>" tag_content could also be separated into : text1|cdata|text2. text1 -> ">> ![cdata[]] " cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>" text2 -> "]]>>]" The reason why start_tag is NOT "<DIV>>>" is because of the rule 6. The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7. Example 3: Input: code = "<A> <B> </A> </B>" Output: false Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.   Constraints: 1 <= code.length <= 500 code consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '.
import re TAG_RE = re.compile(r'\A[A-Z]{1,9}\Z') class Solution(object): def isValid(self, code): """ :type code: str :rtype: bool """ s = [] h = False i, n = 0, len(code) while i < n: j = code.find('<', i) if j < 0: break # no more < k = code.find('>', j) if k < 0: return False # unmatched < tag = code[j+1:k] if tag.startswith('![CDATA['): k = code.find(']]>', j) if k < 0: return False # unmatched CDATA i = k + 3 continue if tag.startswith('/'): if not s or tag[1:] != s.pop(): return False # mismatching /TAG if not s and k + 1 < n: return False # code not wrapped in valid closed tag. else: if not TAG_RE.match(tag): return False # invalid TAG if not s and j > 0: return False # code not wrapped in valid closed tag. s.append(tag) h = True i = k + 1 return h and not s
a1cb42
9a061d
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid). The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.   Example 1: Input: code = "<DIV>This is the first line <![CDATA[<div>]]></DIV>" Output: true Explanation: The code is wrapped in a closed tag : <DIV> and </DIV>. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. Example 2: Input: code = "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>" Output: true Explanation: We first separate the code into : start_tag|tag_content|end_tag. start_tag -> "<DIV>" end_tag -> "</DIV>" tag_content could also be separated into : text1|cdata|text2. text1 -> ">> ![cdata[]] " cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>" text2 -> "]]>>]" The reason why start_tag is NOT "<DIV>>>" is because of the rule 6. The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7. Example 3: Input: code = "<A> <B> </A> </B>" Output: false Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.   Constraints: 1 <= code.length <= 500 code consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '.
def is_valid_ending_with(s, i, j, tag): closed_tag = '</' + tag + '>' if not s.endswith(closed_tag, i, j): return False # Skip parsing the tag. i += len(tag) + 2 max_i = j - len(closed_tag) tag_stack = [] while i != max_i: if s[i].isspace() or s[i].isalnum() or s[i] in '>/![]': pass elif s[i] == '<': if i + 1 >= max_i: return False if s[i + 1] == '/': # Closing tag end_i = s.find('>', i + 1, max_i) if end_i == -1: return False just_closed = s[i + 2:end_i] if not tag_stack or tag_stack[-1] != just_closed: return False tag_stack.pop() i = end_i elif s[i + 1] == '!': # CDATA if s.startswith('<![CDATA[', i, max_i): end_i = s.find(']]>', i, max_i) if end_i == -1: return False i = end_i + 2 else: return False else: # Opening tag inner_tag = digest_tag(s, i, max_i) if inner_tag is None: return False tag_stack.append(inner_tag) i += len(inner_tag) + 1 i += 1 return not tag_stack def digest_tag(s, i, j): if not s.startswith('<', i, j): return None tag = [] for o in range(1, 10): p = i + o if p >= j: return None if s[p].isupper(): tag.append(s[p]) elif s[p] == '>': break else: return None if not tag: return None return ''.join(tag) class Solution(object): def isValid(self, code): """ :type code: str :rtype: bool """ tag = digest_tag(code, 0, len(code)) if tag is None: return False return is_valid_ending_with(code, 0, len(code), tag)
ec78c3
2e80d2
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.   Example 1: Input: target = 1, startFuel = 1, stations = [] Output: 0 Explanation: We can reach the target without refueling. Example 2: Input: target = 100, startFuel = 1, stations = [[10,100]] Output: -1 Explanation: We can not reach the target (or even the first gas station). Example 3: Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] Output: 2 Explanation: We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. Then, we drive from position 10 to position 60 (expending 50 liters of fuel), and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. We made 2 refueling stops along the way, so we return 2.   Constraints: 1 <= target, startFuel <= 10^9 0 <= stations.length <= 500 1 <= positioni < positioni+1 < target 1 <= fueli < 10^9
class Solution: def minRefuelStops(self, target, startFuel, stations): """ :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int """ d = collections.defaultdict(int) d[0] = startFuel for dist, fuel in stations: dd = collections.defaultdict(int) stopsNum = 0 while stopsNum in d: if d[stopsNum] >= dist: dd[stopsNum + 1] = d[stopsNum] + fuel stopsNum += 1 for i, j in d.items(): dd[i] = max(d[i], dd[i]) d = dd stopsNum = 0 while stopsNum in d: if d[stopsNum] >= target: return stopsNum stopsNum += 1 return -1
800535
2e80d2
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.   Example 1: Input: target = 1, startFuel = 1, stations = [] Output: 0 Explanation: We can reach the target without refueling. Example 2: Input: target = 100, startFuel = 1, stations = [[10,100]] Output: -1 Explanation: We can not reach the target (or even the first gas station). Example 3: Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] Output: 2 Explanation: We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. Then, we drive from position 10 to position 60 (expending 50 liters of fuel), and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. We made 2 refueling stops along the way, so we return 2.   Constraints: 1 <= target, startFuel <= 10^9 0 <= stations.length <= 500 1 <= positioni < positioni+1 < target 1 <= fueli < 10^9
class Solution(object): def minRefuelStops(self, target, startFuel, stations): """ :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int """ cur = startFuel hq = [] ans = 0 for x in stations: if x[0] <= cur: heapq.heappush(hq, (-x[1], x[0])) else: while hq: f, p = heapq.heappop(hq) #print cur, x, f, p cur -= f ans += 1 if cur > x[0]: break if cur < x[0]: return -1 heapq.heappush(hq, (-x[1], x[0])) if cur >= target: return ans while cur < target and hq: f, p = heapq.heappop(hq) #print cur, x, f, p cur -= f ans += 1 if cur >= target: break if cur < target: return -1 return ans
c95e3e
8a5a6c
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 Output: 20 Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2. Example 2: Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 Output: 29 Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2. Example 3: Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 Output: 31 Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.   Constraints: 1 <= firstLen, secondLen <= 1000 2 <= firstLen + secondLen <= 1000 firstLen + secondLen <= nums.length <= 1000 0 <= nums[i] <= 1000
class Solution(object): def maxSumTwoNoOverlap(self, A, L, M): """ :type A: List[int] :type L: int :type M: int :rtype: int """ pre = [0] n = len(A) for i in range(n): pre.append(pre[i] + A[i]) def is_ok(i,j): return i+L<=n and j+M<=n and (j>=i+L or i>=j+M) ret = None for i in range(n): for j in range(n): if is_ok(i, j): ret = max(ret, pre[i+L]-pre[i] + pre[j+M]-pre[j]) return ret
41385b
8a5a6c
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array.   Example 1: Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 Output: 20 Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2. Example 2: Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 Output: 29 Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2. Example 3: Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 Output: 31 Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.   Constraints: 1 <= firstLen, secondLen <= 1000 2 <= firstLen + secondLen <= 1000 firstLen + secondLen <= nums.length <= 1000 0 <= nums[i] <= 1000
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: def f(a, b): ret = 0 for i in range(a - 1, n - b): for j in range(i + b, n): ret = max(ret, ps[i + 1] - ps[i + 1 - a] + ps[j + 1] - ps[j + 1 - b]) return ret n = len(A) ps = [0] * (n + 1) for i, j in enumerate(A): ps[i + 1] = ps[i] + j return max(f(L, M), f(M, L)) if M != L else f(M, L)
4ac8ef
5b9f9e
We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order. (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length. Example 1: Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]] Output: [[3,4]] Explanation: There are a total of three employees, and all common free time intervals would be [-inf, 1], [3, 4], [10, inf]. We discard any intervals that contain inf as they aren't finite. Example 2: Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]] Output: [[5,6],[7,9]] Constraints: 1 <= schedule.length , schedule[i].length <= 50 0 <= schedule[i].start < schedule[i].end <= 10^8
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def employeeFreeTime(self, avails): """ :type avails: List[List[Interval]] :rtype: List[Interval] """ schedule = [] for lst in avails: if lst: schedule.append((lst[0].start, lst)) heapq.heapify(schedule) freetimes = [] lastend = 0 if schedule: lastend = schedule[0][0] while schedule: newstart, newlist = heapq.heappop(schedule) if newstart > lastend: freetimes.append((lastend, newstart)) lastsch = newlist.pop(0) lastend = max(lastend, lastsch.end) if newlist: heapq.heappush(schedule, (newlist[0].start, newlist)) return freetimes
084bb3
5b9f9e
We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order. (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length. Example 1: Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]] Output: [[3,4]] Explanation: There are a total of three employees, and all common free time intervals would be [-inf, 1], [3, 4], [10, inf]. We discard any intervals that contain inf as they aren't finite. Example 2: Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]] Output: [[5,6],[7,9]] Constraints: 1 <= schedule.length , schedule[i].length <= 50 0 <= schedule[i].start < schedule[i].end <= 10^8
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def employeeFreeTime(self, avails): """ :type avails: List[List[Interval]] :rtype: List[Interval] """ it = heapq.merge(*avails, key=lambda x: x.start) answer = [] start = None for interval in it: if start is not None and interval.start > start: answer.append(Interval(start, interval.start)) start = max(start, interval.end) if start is not None else interval.end return answer #[ # [[7,24],[29,33],[45,57],[66,69],[94,99]], # [[6,24],[43,49],[56,59],[61,75],[80,81]], # [[5,16],[18,26],[33,36],[39,57],[65,74]], # [[9,16],[27,35],[40,55],[68,71],[78,81]], # [[0,25],[29,31],[40,47],[57,87],[91,94]]]
214726
9892be
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: lower[i] = arr[i] - k, for every index i where 0 <= i < n higher[i] = arr[i] + k, for every index i where 0 <= i < n Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr.   Example 1: Input: nums = [2,10,6,4,8,12] Output: [3,7,11] Explanation: If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12]. Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums. Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. Example 2: Input: nums = [1,1,3,3] Output: [2,2] Explanation: If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3]. Combining lower and higher gives us [1,1,3,3], which is equal to nums. Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0. This is invalid since k must be positive. Example 3: Input: nums = [5,435] Output: [220] Explanation: The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].   Constraints: 2 * n == nums.length 1 <= n <= 1000 1 <= nums[i] <= 10^9 The test cases are generated such that there exists at least one valid array arr.
from collections import Counter class Solution(object): def recoverArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ a = sorted(nums) n = len(a) // 2 def check(k): c = Counter() r = [] for val in a: if c[val] > 0: c[val] -= 1 else: r.append(val+k) c[val+2*k] += 1 return r if len(r) == n and sum(c.itervalues()) == 0 else None for v in a: if v==a[0] or (v-a[0])%2!=0: continue k = (v-a[0]) >> 1 r = check(k) if r is not None: return r
a11355
9892be
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: lower[i] = arr[i] - k, for every index i where 0 <= i < n higher[i] = arr[i] + k, for every index i where 0 <= i < n Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr.   Example 1: Input: nums = [2,10,6,4,8,12] Output: [3,7,11] Explanation: If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12]. Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums. Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. Example 2: Input: nums = [1,1,3,3] Output: [2,2] Explanation: If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3]. Combining lower and higher gives us [1,1,3,3], which is equal to nums. Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0. This is invalid since k must be positive. Example 3: Input: nums = [5,435] Output: [220] Explanation: The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].   Constraints: 2 * n == nums.length 1 <= n <= 1000 1 <= nums[i] <= 10^9 The test cases are generated such that there exists at least one valid array arr.
class Solution: def recoverArray(self, nums: List[int]) -> List[int]: nums = sorted(nums) start = nums[0] for nstart in nums[1:] : if (nstart - start) % 2 == 1 or nstart == start: continue dt = (nstart - start) // 2 counter = collections.Counter(nums) mark = True to_ret_t = [] for vt in nums : if counter[vt] == 0 : continue if counter[vt + dt*2] == 0: mark = False break counter[vt] -= 1 counter[vt+dt*2] -= 1 to_ret_t.append(vt+dt) if mark : return to_ret_t
ce6574
1ae06f
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: arr = [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7.   Constraints: 1 <= arr.length <= 5 * 10000 0 <= arr[i] <= 10^9
class Solution(object): def subarrayBitwiseORs(self, A): """ :type A: List[int] :rtype: int """ ans = set([A[0]]) prev = set([A[0]]) for i in range(1, len(A)): newSet = set(num|A[i] for num in prev) newSet.add(A[i]) ans |= newSet prev = newSet # print ans return len(ans)
7cd965
1ae06f
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: arr = [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7.   Constraints: 1 <= arr.length <= 5 * 10000 0 <= arr[i] <= 10^9
class Solution: def subarrayBitwiseORs(self, A): """ :type A: List[int] :rtype: int """ n = len(A) q = [] s = {-1} for x in A: q += [x] q = [x | y for y in q] q = list(set(q)) #print(q) #s.union(q) #print(s) for y in q: s.add(y) return len(s) - 1
9d8024
28a478
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). The test cases are generated so that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [44,22,33,11,1], threshold = 5 Output: 44   Constraints: 1 <= nums.length <= 5 * 10000 1 <= nums[i] <= 1000000 nums.length <= threshold <= 1000000
class Solution(object): def smallestDivisor(self, A, T): N = len(A) def f(d): s = 0 for x in A: s += (x-1) // d + 1 return s <= T lo, hi = 1, 10**20 while lo<hi: mi = (lo+hi) // 2 if f(mi): hi = mi else: lo = mi + 1 return lo
c4e77a
28a478
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). The test cases are generated so that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [44,22,33,11,1], threshold = 5 Output: 44   Constraints: 1 <= nums.length <= 5 * 10000 1 <= nums[i] <= 1000000 nums.length <= threshold <= 1000000
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: l, r, ans = 1, max(nums) + 1, None while l <= r: mid = (l + r) // 2 cur = sum(x // mid + (1 if x % mid != 0 else 0) for x in nums) if cur <= threshold: ans = mid r = mid - 1 else: l = mid + 1 return ans
f90dd4
f8a923
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. The prefix and the suffix should not intersect at any index. The characters from the prefix and suffix must be the same. Delete both the prefix and the suffix. Return the minimum length of s after performing the above operation any number of times (possibly zero times).   Example 1: Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is. Example 2: Input: s = "cabaabac" Output: 0 Explanation: An optimal sequence of operations is: - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". - Take prefix = "a" and suffix = "a" and remove them, s = "baab". - Take prefix = "b" and suffix = "b" and remove them, s = "aa". - Take prefix = "a" and suffix = "a" and remove them, s = "". Example 3: Input: s = "aabccabba" Output: 3 Explanation: An optimal sequence of operations is: - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". - Take prefix = "b" and suffix = "bb" and remove them, s = "cca".   Constraints: 1 <= s.length <= 100000 s only consists of characters 'a', 'b', and 'c'.
class Solution(object): def minimumLength(self, s): """ :type s: str :rtype: int """ st=0 end=len(s)-1 while s[st]==s[end] and st<end: i=st while s[st]==s[i] and st<end: st+=1 while s[end]==s[i] and st<=end: end-=1 return end-st+1
6b546c
f8a923
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. The prefix and the suffix should not intersect at any index. The characters from the prefix and suffix must be the same. Delete both the prefix and the suffix. Return the minimum length of s after performing the above operation any number of times (possibly zero times).   Example 1: Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is. Example 2: Input: s = "cabaabac" Output: 0 Explanation: An optimal sequence of operations is: - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". - Take prefix = "a" and suffix = "a" and remove them, s = "baab". - Take prefix = "b" and suffix = "b" and remove them, s = "aa". - Take prefix = "a" and suffix = "a" and remove them, s = "". Example 3: Input: s = "aabccabba" Output: 3 Explanation: An optimal sequence of operations is: - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". - Take prefix = "b" and suffix = "bb" and remove them, s = "cca".   Constraints: 1 <= s.length <= 100000 s only consists of characters 'a', 'b', and 'c'.
class Solution: def minimumLength(self, s: str) -> int: i = 0 j = len(s) - 1 while i < j and s[i] == s[j]: c = s[i] while i < j and s[i] == c: i += 1 while i <= j and s[j] == c: j -= 1 return j - i + 1
10a23c
f8a9ad
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.   Example 1: Input: finalSum = 12 Output: [2,4,6] Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8). (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. Note that [2,6,4], [6,2,4], etc. are also accepted. Example 2: Input: finalSum = 7 Output: [] Explanation: There are no valid splits for the given finalSum. Thus, we return an empty array. Example 3: Input: finalSum = 28 Output: [6,8,2,12] Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.   Constraints: 1 <= finalSum <= 10^10
class Solution: def maximumEvenSplit(self, f: int) -> List[int]: if f%2: return [] f //= 2 s = 0 c = [] x = 1 while x+s <= f: c.append(x) s += x x += 1 c[-1] += f-s return [i*2 for i in c]
c69f97
f8a9ad
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.   Example 1: Input: finalSum = 12 Output: [2,4,6] Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8). (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. Note that [2,6,4], [6,2,4], etc. are also accepted. Example 2: Input: finalSum = 7 Output: [] Explanation: There are no valid splits for the given finalSum. Thus, we return an empty array. Example 3: Input: finalSum = 28 Output: [6,8,2,12] Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.   Constraints: 1 <= finalSum <= 10^10
class Solution(object): def maximumEvenSplit(self, finalSum): """ :type finalSum: int :rtype: List[int] """ if finalSum & 1 == 1: return [] else: res = [] n = int(math.sqrt(finalSum)) t = n * (n + 1) if t <= finalSum: res = [2 * i for i in range(1, n + 1)] res[-1] += finalSum - t else: res = [2 * i for i in range(1, n)] res[-1] += finalSum - n * (n - 1) return res
d193bb
85a4cf
You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters.   Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3. Example 2: Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6. Example 3: Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.   Constraints: 1 <= text.length <= 2 * 10000 text consist of lowercase English characters only.
class Solution(object): def maxRepOpt1(self, s): s = 'AB' + s + 'YZ' n = len(s) cnt = collections.Counter(s) pre = [0] * n cur = 0 for i in range(1, n): if s[i] == s[i - 1]: cur += 1 else: cur = 0 pre[i] = cur post = [0] * n cur = 0 for i in range(n - 2, -1, -1): if s[i] == s[i + 1]: cur += 1 else: cur = 0 post[i] = cur res = 1 for i in range(1, n - 1): tmp = 0 if pre[i - 1] + 1 < cnt[s[i - 1]]: tmp1 = pre[i - 1] + 2 else: tmp1 = pre[i - 1] + 1 if post[i + 1] + 1 < cnt[s[i + 1]]: tmp2 = post[i + 1] + 2 else: tmp2 = post[i + 1] + 1 tmp = max(tmp1, tmp2) if s[i - 1] == s[i + 1]: if pre[i - 1] + post[i + 1] + 2 < cnt[s[i + 1]]: tmp3 = pre[i - 1] + post[i + 1] + 3 else: tmp3 = pre[i - 1] + post[i + 1] + 2 tmp = max(tmp, tmp3) res = max(res, tmp) return res """ :type text: str :rtype: int """
d28de1
85a4cf
You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters.   Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3. Example 2: Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6. Example 3: Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.   Constraints: 1 <= text.length <= 2 * 10000 text consist of lowercase English characters only.
class Solution: def maxRepOpt1(self, text: str) -> int: stack = [['!',0]] for i in text: if i != stack[-1][0]: stack += [[i,1]] else: stack[-1][1] += 1 stack = stack[1:] res = 0 cnt = collections.defaultdict(int) for i in stack: cnt[i[0]] += 1 for i in range(1,len(stack)-1): if stack[i][1] == 1 and stack[i-1][0] == stack[i+1][0] and cnt[stack[i-1][0]] >= 3: res = max(res,stack[i-1][1]+stack[i+1][1]+1) if stack[i][1] == 1 and stack[i-1][0] == stack[i+1][0] and cnt[stack[i-1][0]] == 2: res = max(res,stack[i-1][1]+stack[i+1][1]) for i in range(len(stack)): if cnt[stack[i][0]] >= 2: res = max(res,stack[i][1]+1) else: res = max(res,stack[i][1]) return res
c22f1f
cbcad3
You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.   Example 1: Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 Output: 3 Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: [x, _, _, _, _] // we can only make one bouquet. After day 2: [x, _, _, _, x] // we can only make two bouquets. After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. Example 2: Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 Output: -1 Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. Example 3: Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 Output: 12 Explanation: We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: [x, x, x, x, _, x, x] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: [x, x, x, x, x, x, x] It is obvious that we can make two bouquets in different ways.   Constraints: bloomDay.length == n 1 <= n <= 100000 1 <= bloomDay[i] <= 10^9 1 <= m <= 1000000 1 <= k <= n
class Solution(object): def minDays(self, bloomDay, M, K): """ :type bloomDay: List[int] :type m: int :type k: int :rtype: int """ events = [] for i, t in enumerate(bloomDay, 1): events.append((t, i)) events.sort() def possible(J): # events[..J] used seen = set() for j in xrange(J + 1): x = events[j][1] seen.add(x) live = sorted(seen) anchor = 0 made = 0 for i, x in enumerate(live): if i == len(live) - 1 or live[i+1] != x + 1: # group: [anchor, i] length = i - anchor + 1 made += length // K anchor = i + 1 return made >= M lo, hi = 0, len(events) while lo < hi: mi = lo + hi >> 1 if not possible(mi): lo = mi + 1 else: hi = mi if lo == len(events) : return -1 return events[lo][0]
e43682
cbcad3
You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.   Example 1: Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 Output: 3 Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: [x, _, _, _, _] // we can only make one bouquet. After day 2: [x, _, _, _, x] // we can only make two bouquets. After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. Example 2: Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 Output: -1 Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. Example 3: Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 Output: 12 Explanation: We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: [x, x, x, x, _, x, x] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: [x, x, x, x, x, x, x] It is obvious that we can make two bouquets in different ways.   Constraints: bloomDay.length == n 1 <= n <= 100000 1 <= bloomDay[i] <= 10^9 1 <= m <= 1000000 1 <= k <= n
class Solution: def minDays(self, a: List[int], mm: int, k: int) -> int: if mm*k>len(a): return -1 def chk(d): ans=0 cnt=0 for x in a: if x>d: cnt=0 continue cnt+=1 if cnt==k: ans+=1 cnt=0 return ans>=mm l,r=-1,max(a)+1 while r-l>1: m=(l+r)//2 if chk(m): r=m else: l=m return r
7b0545
3e0aca
Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward.   Example 1: Input: s = "zzazz" Output: 0 Explanation: The string "zzazz" is already palindrome we do not need any insertions. Example 2: Input: s = "mbadm" Output: 2 Explanation: String can be "mbdadbm" or "mdbabdm". Example 3: Input: s = "leetcode" Output: 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel".   Constraints: 1 <= s.length <= 500 s consists of lowercase English letters.
from functools import lru_cache class Solution: def minInsertions(self, s: str) -> int: INF = float('inf') @lru_cache(None) def dp(i, j): if i > j: return INF elif i == j: return 0 elif i == j-1: return +(s[i] != s[j]) elif s[i] == s[j]: return dp(i+1, j-1) else: return min(dp(i, j-1), dp(i+1, j)) + 1 return dp(0, len(s) - 1)
c5abd5
3e0aca
Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward.   Example 1: Input: s = "zzazz" Output: 0 Explanation: The string "zzazz" is already palindrome we do not need any insertions. Example 2: Input: s = "mbadm" Output: 2 Explanation: String can be "mbdadbm" or "mdbabdm". Example 3: Input: s = "leetcode" Output: 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel".   Constraints: 1 <= s.length <= 500 s consists of lowercase English letters.
class Solution(object): def minInsertions(self, s): """ :type s: str :rtype: int """ n = len(s) f = [[0]*(n+1), [0]*n] for k in xrange(2, n+1): f.append([f[k-2][i+1] if s[i]==s[i+k-1] else 1 + min(f[k-1][i], f[k-1][i+1]) for i in xrange(1+n-k)]) return f[-1][-1]
2c6741
11bdb9
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.   Example 1: Input: favorite = [2,2,1,2] Output: 3 Explanation: The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table. All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously. Note that the company can also invite employees 1, 2, and 3, and give them their desired seats. The maximum number of employees that can be invited to the meeting is 3. Example 2: Input: favorite = [1,2,0] Output: 3 Explanation: Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee. The seating arrangement will be the same as that in the figure given in example 1: - Employee 0 will sit between employees 2 and 1. - Employee 1 will sit between employees 0 and 2. - Employee 2 will sit between employees 1 and 0. The maximum number of employees that can be invited to the meeting is 3. Example 3: Input: favorite = [3,0,1,4,1] Output: 4 Explanation: The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table. Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken. So the company leaves them out of the meeting. The maximum number of employees that can be invited to the meeting is 4.   Constraints: n == favorite.length 2 <= n <= 100000 0 <= favorite[i] <= n - 1 favorite[i] != i
class Solution: def maximumInvitations(self, f: List[int]) -> int: # functional graph # either table consists of one cycle # or multiple (two chains + cycle of two) # bidirectional edges edges = defaultdict(list) n = len(f) for i in range(n): edges[f[i]].append(i) edges[i].append(f[i]) seen = [False]*n self.l = 0 def dfs(v, p, d): self.l = max(self.l, d) seen[v] = True for i in edges[v]: if i != p and not seen[i]: dfs(i, v, d+1) total = 0 best = 0 for i in range(n): if seen[i]: continue if f[f[i]] == i: # cycle of two self.l = 0 dfs(i, f[i], 0) cur = self.l self.l = 0 dfs(f[i], i, 0) cur += self.l total += cur+2 for i in range(n): if not seen[i]: dfs(i, i, 0) l = [i] j = i cur = 0 s = set() s.add(i) while True: j = f[j] if j in s: while True: cur += 1 if l.pop() == j: break best = max(best, cur) break s.add(j) l.append(j) return max(total, best)
7ebbc7
11bdb9
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.   Example 1: Input: favorite = [2,2,1,2] Output: 3 Explanation: The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table. All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously. Note that the company can also invite employees 1, 2, and 3, and give them their desired seats. The maximum number of employees that can be invited to the meeting is 3. Example 2: Input: favorite = [1,2,0] Output: 3 Explanation: Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee. The seating arrangement will be the same as that in the figure given in example 1: - Employee 0 will sit between employees 2 and 1. - Employee 1 will sit between employees 0 and 2. - Employee 2 will sit between employees 1 and 0. The maximum number of employees that can be invited to the meeting is 3. Example 3: Input: favorite = [3,0,1,4,1] Output: 4 Explanation: The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table. Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken. So the company leaves them out of the meeting. The maximum number of employees that can be invited to the meeting is 4.   Constraints: n == favorite.length 2 <= n <= 100000 0 <= favorite[i] <= n - 1 favorite[i] != i
from collections import Counter class Solution(object): def maximumInvitations(self, favorite): """ :type favorite: List[int] :rtype: int """ a = favorite n = len(a) hl = [None]*n cl = [None]*n cs = [None]*n ctl = Counter() for i in xrange(n): if cs[i] is not None: continue u = i t = {} path = [] while True: if u in t: tu = t[u] clen = len(path) - tu for j in xrange(tu): hl[path[j]] = tu - j cs[path[j]] = u cl[path[j]] = clen for j in xrange(tu, len(path)): hl[path[j]] = 0 cs[path[j]] = path[j] cl[path[j]] = clen ctl[u] = max(ctl[u], tu) break if cs[u] is not None: l = len(path) for j in xrange(l): hl[path[j]] = hl[u]+l-j cs[path[j]] = cs[u] cl[path[j]] = cl[u] ctl[cs[u]] = max(ctl[cs[u]], hl[u]+l) break t[u] = len(path) path.append(u) u = a[u] r1 = max(cl) r2 = 0 for i in xrange(n): if cs[i] == i and cl[i] == 2 and i < a[i]: r2 += ctl[i] + ctl[a[i]] + 2 return max(r1, r2)
828be2
c605d7
You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively. A containing set is an array nums where each interval from intervals has at least two integers in nums. For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets. Return the minimum possible size of a containing set.   Example 1: Input: intervals = [[1,3],[3,7],[8,9]] Output: 5 Explanation: let nums = [2, 3, 4, 8, 9]. It can be shown that there cannot be any containing array of size 4. Example 2: Input: intervals = [[1,3],[1,4],[2,5],[3,5]] Output: 3 Explanation: let nums = [2, 3, 4]. It can be shown that there cannot be any containing array of size 2. Example 3: Input: intervals = [[1,2],[2,3],[2,4],[4,5]] Output: 5 Explanation: let nums = [1, 2, 3, 4, 5]. It can be shown that there cannot be any containing array of size 4.   Constraints: 1 <= intervals.length <= 3000 intervals[i].length == 2 0 <= starti < endi <= 10^8
class Solution: def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ def verifyTwo(start, end): found_one = False found_two = False for i in result: if i >= start and i <= end: if not found_one: found_one = True else: found_two = True return if not found_two: if end not in result: result.add(end) elif end-1 not in result: result.add(end-1) elif start not in result: result.add(start) else: result.add(start+1) intervals.sort(key=lambda x: x[1]) result = set() end = -float('inf') for interval in intervals: if interval[0] > end: result.add(interval[1]) end = interval[1] for start, end in intervals: verifyTwo(start, end) # print(result) return len(result)
23d1d6
c605d7
You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively. A containing set is an array nums where each interval from intervals has at least two integers in nums. For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets. Return the minimum possible size of a containing set.   Example 1: Input: intervals = [[1,3],[3,7],[8,9]] Output: 5 Explanation: let nums = [2, 3, 4, 8, 9]. It can be shown that there cannot be any containing array of size 4. Example 2: Input: intervals = [[1,3],[1,4],[2,5],[3,5]] Output: 3 Explanation: let nums = [2, 3, 4]. It can be shown that there cannot be any containing array of size 2. Example 3: Input: intervals = [[1,2],[2,3],[2,4],[4,5]] Output: 5 Explanation: let nums = [1, 2, 3, 4, 5]. It can be shown that there cannot be any containing array of size 4.   Constraints: 1 <= intervals.length <= 3000 intervals[i].length == 2 0 <= starti < endi <= 10^8
class Solution(object): def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda x: x[1]) s = [intervals[0][1] - 1, intervals[0][1]] for i in xrange(1, len(intervals)): st, e = intervals[i] if s[-1] >= st and s[-2] >= st: continue if s[-1] >= st: s += [e] else: s += [e - 1, e] return len(s)
697dd7
6015d1
In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0). Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot. The value of |x| is defined as: x if x >= 0 -x if x < 0   Example 1: Input: neededApples = 1 Output: 8 Explanation: A square plot of side length 1 does not contain any apples. However, a square plot of side length 2 has 12 apples inside (as depicted in the image above). The perimeter is 2 * 4 = 8. Example 2: Input: neededApples = 13 Output: 16 Example 3: Input: neededApples = 1000000000 Output: 5040   Constraints: 1 <= neededApples <= 10^15
class Solution: def minimumPerimeter(self, neededApples: int) -> int: low, high = 1, 10**7 while low != high: mid = (low+high) >> 1 a = mid*(mid+1)*(2*mid+1)*2 if a < neededApples: low = mid+1 else: high = mid return low*8
89330c
6015d1
In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0). Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot. The value of |x| is defined as: x if x >= 0 -x if x < 0   Example 1: Input: neededApples = 1 Output: 8 Explanation: A square plot of side length 1 does not contain any apples. However, a square plot of side length 2 has 12 apples inside (as depicted in the image above). The perimeter is 2 * 4 = 8. Example 2: Input: neededApples = 13 Output: 16 Example 3: Input: neededApples = 1000000000 Output: 5040   Constraints: 1 <= neededApples <= 10^15
class Solution(object): def minimumPerimeter(self, neededApples): """ :type neededApples: int :rtype: int """ cur = 1 while True: apples = 2 * cur apples *= cur + 1 apples *= (2 * cur + 1) if apples >= neededApples: return 8 * cur cur += 1
f3e8c1
2b0886
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums = [6,1,4,1]. Choosing to remove index 4 results in nums = [6,1,7,4]. An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair.   Example 1: Input: nums = [2,1,6,4] Output: 1 Explanation: Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. Example 2: Input: nums = [1,1,1] Output: 3 Explanation: You can remove any index and the remaining array is fair. Example 3: Input: nums = [1,2,3] Output: 0 Explanation: You cannot make a fair array after removing any index.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10000
class Solution: def waysToMakeFair(self, nums: List[int]) -> int: sums = [0] for i,n in enumerate(nums): sums.append(sums[-1]-n if i%2 else sums[-1]+n) # print(sums) cnt = 0 for i,n in enumerate(nums): if sums[i] == sums[-1]-sums[i+1]: cnt+=1 return cnt
299f10
2b0886
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums = [6,1,4,1]. Choosing to remove index 4 results in nums = [6,1,7,4]. An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair.   Example 1: Input: nums = [2,1,6,4] Output: 1 Explanation: Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. Example 2: Input: nums = [1,1,1] Output: 3 Explanation: You can remove any index and the remaining array is fair. Example 3: Input: nums = [1,2,3] Output: 0 Explanation: You cannot make a fair array after removing any index.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10000
class Solution(object): def waysToMakeFair(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) odd_pre = [0] * n even_pre = [0] * n odd_suf = [0] * n even_suf = [0] * n for i in range(n): if i % 2 == 1: odd_pre[i] = odd_pre[i - 1] + nums[i] even_pre[i] = even_pre[i - 1] else: odd_pre[i] = odd_pre[i - 1] if i else 0 even_pre[i] = even_pre[i - 1] + nums[i] if i else nums[i] for i in range(n - 1, -1, -1): if i % 2 == 1: odd_suf[i] = odd_suf[i + 1] + nums[i] if i < n - 1 else nums[i] even_suf[i] = even_suf[i + 1] if i < n - 1 else 0 else: odd_suf[i] = odd_suf[i + 1] if i < n - 1 else 0 even_suf[i] = even_suf[i + 1] + nums[i] if i < n - 1 else nums[i] ans = 0 for i in range(n): odd_sum = 0 even_sum = 0 if i > 0: odd_sum += odd_pre[i - 1] even_sum += even_pre[i - 1] if i < n - 1: odd_sum += even_suf[i + 1] even_sum += odd_suf[i + 1] if even_sum == odd_sum: ans += 1 return ans
22bc13
994ae0
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers. Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.   Example 1: Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11] Output: [1,2,2,2] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival. Example 2: Input: flowers = [[1,10],[3,3]], poeple = [3,3,2] Output: [2,2,1] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival.   Constraints: 1 <= flowers.length <= 5 * 10000 flowers[i].length == 2 1 <= starti <= endi <= 10^9 1 <= people.length <= 5 * 10000 1 <= people[i] <= 10^9
class Solution(object): def fullBloomFlowers(self, flowers, persons): """ :type flowers: List[List[int]] :type persons: List[int] :rtype: List[int] """ events = [] for fs, fe in flowers: events.append((fs, 1, -1)) events.append((fe + 1, -1, -1)) for i, p in enumerate(persons): events.append((p, 2, i)) events.sort() now = 0 ans = [0] * len(persons) for ts, inc, idx in events: if idx == -1: now += inc else: ans[idx] = now return ans
f59fbf
994ae0
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers. Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.   Example 1: Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11] Output: [1,2,2,2] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival. Example 2: Input: flowers = [[1,10],[3,3]], poeple = [3,3,2] Output: [2,2,1] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival.   Constraints: 1 <= flowers.length <= 5 * 10000 flowers[i].length == 2 1 <= starti <= endi <= 10^9 1 <= people.length <= 5 * 10000 1 <= people[i] <= 10^9
class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: to_ret = [None]*len(persons) persons = sorted([[t, i] for i, t in enumerate(persons)]) flowers = sorted(flowers) heap = [] pf = 0 for t, it in persons : while pf < len(flowers) and flowers[pf][0] <= t : heapq.heappush(heap, flowers[pf][1]) pf += 1 while len(heap) > 0 and heap[0] < t : heapq.heappop(heap) to_ret[it] = len(heap) return to_ret
bac86c
a93d84
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".   Example 1: Input: cost = [4,3,2,5,6,7,2,5,5], target = 9 Output: "7772" Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number. Digit cost 1 -> 4 2 -> 3 3 -> 2 4 -> 5 5 -> 6 6 -> 7 7 -> 2 8 -> 5 9 -> 5 Example 2: Input: cost = [7,6,5,5,5,6,8,7,8], target = 12 Output: "85" Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12. Example 3: Input: cost = [2,4,6,2,4,6,4,4,4], target = 5 Output: "0" Explanation: It is impossible to paint any integer with total cost equal to target.   Constraints: cost.length == 9 1 <= cost[i], target <= 5000
class Solution: def largestNumber(self, cost: List[int], target: int) -> str: # 背包问题 self.cost = cost from functools import lru_cache @lru_cache(None) def mylarge(target: int) -> str: if target<0: return None if target==0: return '' large = None for i,x in enumerate(self.cost): # i+1 -> cost == x y = mylarge(target-x) if y==None:continue s1 = str(i+1) + y s2 = y + str(i+1) if int(s1)>int(s2): now = s1 else: now = s2 if large==None or int(now)>int(large): large = now return large ss = mylarge(target) if ss == None: return '0' if len(ss)<1: return '0' return ss
a4d703
a93d84
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".   Example 1: Input: cost = [4,3,2,5,6,7,2,5,5], target = 9 Output: "7772" Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number. Digit cost 1 -> 4 2 -> 3 3 -> 2 4 -> 5 5 -> 6 6 -> 7 7 -> 2 8 -> 5 9 -> 5 Example 2: Input: cost = [7,6,5,5,5,6,8,7,8], target = 12 Output: "85" Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12. Example 3: Input: cost = [2,4,6,2,4,6,4,4,4], target = 5 Output: "0" Explanation: It is impossible to paint any integer with total cost equal to target.   Constraints: cost.length == 9 1 <= cost[i], target <= 5000
class Solution(object): def largestNumber(self, cost, target): """ :type cost: List[int] :type target: int :rtype: str """ cost=[0]+cost a,s,d=[0]*(target+1),[0]*(target+1),[0]*(target+1) d[0]=1 for i in range(1,target+1): for j in range(9,0,-1): jj=i-cost[j] if jj>=0 and d[jj]: if not d[i] or a[jj]>a[i]-1: d[i]=1 a[i]=a[jj]+1 s[i]=j if not d[-1]: return '0' ans,i=[],target while i: ans.append(str(s[i])) i-=cost[s[i]] return ''.join(ans)
45195b
ea5f85
Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10] Example 2: Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83 Example 3: Input: arr = [1], k = 1 Output: 1   Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 10^9 1 <= k <= arr.length
class Solution: def maxSumAfterPartitioning(self, A: List[int], K: int) -> int: ans = [] for i, n in enumerate(A): if i < K: ans.append(max(A[:i + 1]) * (i + 1)) else: cur = 0 for j in range(i - K + 1, i + 1): cur = max(cur, ans[j - 1] + max(A[j: i + 1]) * (i - j + 1)) ans.append(cur) print(ans) return ans[-1]
f3bc22
ea5f85
Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.   Example 1: Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10] Example 2: Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83 Example 3: Input: arr = [1], k = 1 Output: 1   Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 10^9 1 <= k <= arr.length
class Solution(object): def maxSumAfterPartitioning(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ max_range = dict() n = len(A) for i in xrange(n): for j in xrange(i, n): if j == i: max_range[(i, j)] = A[i] else: max_range[(i, j)] = max(A[j], max_range[(i, j - 1)]) dp = dict() for i in xrange(n): if i == 0: dp[i] = A[0] else: if i + 1 <= K: dp[i] = max_range[(0, i)] * (i + 1) else: dp[i] = 0 for j in xrange(i - K, i): if j >= 0: dp[i] = max(dp[i], dp[j] + max_range[(j + 1, i)] * (i - j)) return dp[n - 1]
64f48a
11feb0
You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0. You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: prevRoom = [-1,0,1] Output: 1 Explanation: There is only one way to build the additional rooms: 0 → 1 → 2 Example 2: Input: prevRoom = [-1,0,0,1,2] Output: 6 Explanation: The 6 ways are: 0 → 1 → 3 → 2 → 4 0 → 2 → 4 → 1 → 3 0 → 1 → 2 → 3 → 4 0 → 1 → 2 → 4 → 3 0 → 2 → 1 → 3 → 4 0 → 2 → 1 → 4 → 3   Constraints: n == prevRoom.length 2 <= n <= 100000 prevRoom[0] == -1 0 <= prevRoom[i] < n for all 1 <= i < n Every room is reachable from room 0 once all the rooms are built.
MAX_N = 2 * 10 ** 5 + 1 MOD = 10 ** 9 + 7 assert MAX_N < MOD def modInverse(a, p=MOD): return pow(a, p - 2, p) # Precompute all factorials: i! fact = [1] for i in range(1, MAX_N + 1): fact.append((fact[-1] * i) % MOD) # Precompute all inverse factorials: 1 / i! invFact = [0] * (MAX_N + 1) invFact[MAX_N] = modInverse(fact[MAX_N], MOD) for i in range(MAX_N - 1, -1, -1): invFact[i] = (invFact[i + 1] * (i + 1)) % MOD # assert fact[i] * invFact[i] % MOD == 1 def nCr(n, r): # mod'd if n < r: return 0 return (fact[n] * invFact[r] * invFact[n - r]) % MOD class Solution: def waysToBuildRooms(self, parent: List[int]) -> int: N = len(parent) graph = [[] for i in range(N)] for u, p in enumerate(parent): if p != -1: graph[p].append(u) MOD = 10 ** 9 + 7 def dp(node): ans = 1 total = 0 for child in graph[node]: count, ways = dp(child) total += count ans *= ways ans *= invFact[count] ans %= MOD ans *= fact[total] ans %= MOD return total + 1, ans return dp(0)[1]
a1d4e7
11feb0
You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0. You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: prevRoom = [-1,0,1] Output: 1 Explanation: There is only one way to build the additional rooms: 0 → 1 → 2 Example 2: Input: prevRoom = [-1,0,0,1,2] Output: 6 Explanation: The 6 ways are: 0 → 1 → 3 → 2 → 4 0 → 2 → 4 → 1 → 3 0 → 1 → 2 → 3 → 4 0 → 1 → 2 → 4 → 3 0 → 2 → 1 → 3 → 4 0 → 2 → 1 → 4 → 3   Constraints: n == prevRoom.length 2 <= n <= 100000 prevRoom[0] == -1 0 <= prevRoom[i] < n for all 1 <= i < n Every room is reachable from room 0 once all the rooms are built.
class Solution(object): def fsm(self, a, b, c): ans = 1 while b > 0: if b & 1: ans = ans * a % c a = a * a % c b = b >> 1 return ans def C(self, n, m): return self.frac[n] * self.revfrac[m] % self.mo * self.revfrac[n-m] % self.mo def Dfs(self, x): for e in self.E[x]: self.Dfs(e) self.number[x] += self.number[e] tot = self.number[x] for e in self.E[x]: self.f[x] = self.f[x] * self.f[e] % self.mo * self.C(tot, self.number[e]) % self.mo tot -= self.number[e] self.number[x] += 1 def waysToBuildRooms(self, prevRoom): """ :type prevRoom: List[int] :rtype: int """ self.mo = int(1e9+7) n = len(prevRoom) self.frac = [1] * (n+1) self.revfrac = [1] * (n+1) for i in range(1, n+1): self.frac[i] = self.frac[i-1] * i % self.mo self.revfrac[n] = self.fsm(self.frac[n], self.mo - 2, self.mo) for i in range(n-1, 0, -1): self.revfrac[i] = self.revfrac[i+1] * (i+1) % self.mo self.number = [0] * (n+1) self.f = [1] * (n+1) self.E = dict() for i in range(n): self.E[i] = [] for i in range(n): if prevRoom[i] != -1: self.E[prevRoom[i]].append(i) self.Dfs(0) return self.f[0] % self.mo
2283d1
eb8f49
There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected. You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops. Return true if it is possible to make the degree of each node in the graph even, otherwise return false. The degree of a node is the number of edges connected to it.   Example 1: Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]] Output: true Explanation: The above diagram shows a valid way of adding an edge. Every node in the resulting graph is connected to an even number of edges. Example 2: Input: n = 4, edges = [[1,2],[3,4]] Output: true Explanation: The above diagram shows a valid way of adding two edges. Example 3: Input: n = 4, edges = [[1,2],[1,3],[1,4]] Output: false Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.   Constraints: 3 <= n <= 100000 2 <= edges.length <= 100000 edges[i].length == 2 1 <= ai, bi <= n ai != bi There are no repeated edges.
import sys sys.setrecursionlimit(10 ** 9) """ // END NO SAD // REMEMBER CLEAR GLOBAL STATE // REMEMBER READ THE PROBLEM STATEMENT AND DON'T SOLVE A DIFFERENT PROBLEM // REMEMBER LOOK FOR RANDOM UNINTUITIVE DETAILS IN THE PROBLEM // remember hidden T factor of 1e2 // read the bounds for stupid cases // did you restart your editor // pushing back vectors is garbage, preinitialize them // function calls are not free // unordered naive is faster than lb vector standard """ class Solution: def isPossible(self, n: int, edges: List[List[int]]) -> bool: g = [] for _ in range(n): g.append(set()) for x, y in edges: x -= 1 y -= 1 g[x].add(y) g[y].add(x) odd = [] for i in range(n): if len(g[i]) % 2: odd.append(i) if len(odd) == 0: return True if len(odd) > 4: return False if len(odd) == 2: a = odd[0] b = odd[1] if b not in g[a]: return True for i in range(n): if i == a or i == b: continue if a not in g[i] and b not in g[i]: return True return False if len(odd) == 4: a = odd[0] b = odd[1] c = odd[2] d = odd[3] if b not in g[a] and d not in g[c]: return True if c not in g[a] and d not in g[b]: return True if d not in g[a] and b not in g[c]: return True return False
c1fae8
eb8f49
There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected. You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops. Return true if it is possible to make the degree of each node in the graph even, otherwise return false. The degree of a node is the number of edges connected to it.   Example 1: Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]] Output: true Explanation: The above diagram shows a valid way of adding an edge. Every node in the resulting graph is connected to an even number of edges. Example 2: Input: n = 4, edges = [[1,2],[3,4]] Output: true Explanation: The above diagram shows a valid way of adding two edges. Example 3: Input: n = 4, edges = [[1,2],[1,3],[1,4]] Output: false Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.   Constraints: 3 <= n <= 100000 2 <= edges.length <= 100000 edges[i].length == 2 1 <= ai, bi <= n ai != bi There are no repeated edges.
class Solution(object): def isPossible(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ d, g, o = [0] * (n + 1), defaultdict(set), [] for e, f in edges: d[e], d[f] = d[e] + 1, d[f] + 1 g[e].add(f) g[f].add(e) for i in range(1, n + 1): if d[i] % 2: o.append(i) if len(o) % 2 or len(o) > 4: return False if not len(o): return True if len(o) == 2: if not o[1] in g[o[0]]: return True for i in range(1, n + 1): if not i in g[o[0]] and not i in g[o[1]]: return True return False return not o[1] in g[o[0]] and not o[3] in g[o[2]] or not o[2] in g[o[0]] and not o[3] in g[o[1]] or not o[3] in g[o[0]] and not o[2] in g[o[1]]
a4c19e
6b98b1
You are given a stream of points on the X-Y plane. Design an algorithm that: Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area. An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class: DetectSquares() Initializes the object with an empty data structure. void add(int[] point) Adds a new point point = [x, y] to the data structure. int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.   Example 1: Input ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] Output [null, null, null, null, 1, 0, null, 2] Explanation DetectSquares detectSquares = new DetectSquares(); detectSquares.add([3, 10]); detectSquares.add([11, 2]); detectSquares.add([3, 2]); detectSquares.count([11, 10]); // return 1. You can choose: // - The first, second, and third points detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. detectSquares.add([11, 2]); // Adding duplicate points is allowed. detectSquares.count([11, 10]); // return 2. You can choose: // - The first, second, and third points // - The first, third, and fourth points   Constraints: point.length == 2 0 <= x, y <= 1000 At most 3000 calls in total will be made to add and count.
from collections import defaultdict from typing import List class DetectSquares: def __init__(self): self.x = defaultdict(set) self.cnt = defaultdict(int) def add(self, point: List[int]) -> None: x, y = point self.x[x].add(y) self.cnt[(x, y)] += 1 def count(self, point: List[int]) -> int: x, y = point ans = 0 for i in self.x[x]: if y == i: continue ans += self.cnt[(x, i)] * self.cnt[(x + y - i, y)] * self.cnt[(x + y - i, i)] + self.cnt[(x, i)] * self.cnt[(x - y + i, y)] * self.cnt[(x - y + i, i)] return ans # Your DetectSquares object will be instantiated and called as such: # obj = DetectSquares() # obj.add(point) # param_2 = obj.count(point)
539049
6b98b1
You are given a stream of points on the X-Y plane. Design an algorithm that: Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area. An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class: DetectSquares() Initializes the object with an empty data structure. void add(int[] point) Adds a new point point = [x, y] to the data structure. int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.   Example 1: Input ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] Output [null, null, null, null, 1, 0, null, 2] Explanation DetectSquares detectSquares = new DetectSquares(); detectSquares.add([3, 10]); detectSquares.add([11, 2]); detectSquares.add([3, 2]); detectSquares.count([11, 10]); // return 1. You can choose: // - The first, second, and third points detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. detectSquares.add([11, 2]); // Adding duplicate points is allowed. detectSquares.count([11, 10]); // return 2. You can choose: // - The first, second, and third points // - The first, third, and fourth points   Constraints: point.length == 2 0 <= x, y <= 1000 At most 3000 calls in total will be made to add and count.
from collections import Counter class DetectSquares(object): def __init__(self): self._c = Counter() def add(self, point): """ :type point: List[int] :rtype: None """ self._c[tuple(point)] += 1 def count(self, point): """ :type point: List[int] :rtype: int """ px, py = point r = 0 for x, y in self._c: if x == px or y == py or abs(x-px) != abs(y-py): continue r += self._c[(x,y)] * self._c[(px,y)] * self._c[(x,py)] return r # Your DetectSquares object will be instantiated and called as such: # obj = DetectSquares() # obj.add(point) # param_2 = obj.count(point)
1a10ce
ef5d54
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.   Example 1: Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5] Output: 34 Explanation: You can choose all the players. Example 2: Input: scores = [4,5,6,5], ages = [2,1,2,1] Output: 16 Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. Example 3: Input: scores = [1,2,3,5], ages = [8,9,10,1] Output: 6 Explanation: It is best to choose the first 3 players.   Constraints: 1 <= scores.length, ages.length <= 1000 scores.length == ages.length 1 <= scores[i] <= 1000000 1 <= ages[i] <= 1000
class Solution(object): def bestTeamScore(self, scores, ages): """ :type scores: List[int] :type ages: List[int] :rtype: int """ a = [score for _, score in sorted((age, score) for age, score in zip(ages, scores))] n = len(a) f = a[:] for i in xrange(n): for j in xrange(i): if a[j] <= a[i]: f[i] = max(f[i], a[i] + f[j]) return max(f)
910541
ef5d54
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.   Example 1: Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5] Output: 34 Explanation: You can choose all the players. Example 2: Input: scores = [4,5,6,5], ages = [2,1,2,1] Output: 16 Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. Example 3: Input: scores = [1,2,3,5], ages = [8,9,10,1] Output: 6 Explanation: It is best to choose the first 3 players.   Constraints: 1 <= scores.length, ages.length <= 1000 scores.length == ages.length 1 <= scores[i] <= 1000000 1 <= ages[i] <= 1000
class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: n = len(scores) arr = [(ages[i], scores[i]) for i in range(n)] arr.sort() dp = [0 for i in range(n)] for i in range(n): for j in range(0, i): if arr[j][1] <= arr[i][1]: dp[i] = max(dp[i], dp[j]) dp[i] += arr[i][1] return max(dp)
c3fa69
996a9d
You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river. A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once. The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps. More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump is |stones[i] - stones[j]|. The cost of a path is the maximum length of a jump among all jumps in the path. Return the minimum cost of a path for the frog.   Example 1: Input: stones = [0,2,5,6,7] Output: 5 Explanation: The above figure represents one of the optimal paths the frog can take. The cost of this path is 5, which is the maximum length of a jump. Since it is not possible to achieve a cost of less than 5, we return it. Example 2: Input: stones = [0,3,9] Output: 9 Explanation: The frog can jump directly to the last stone and come back to the first stone. In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9. It can be shown that this is the minimum achievable cost.   Constraints: 2 <= stones.length <= 100000 0 <= stones[i] <= 10^9 stones[0] == 0 stones is sorted in a strictly increasing order.
class Solution: def maxJump(self, stones: List[int]) -> int: to_ret = stones[1]-stones[0] for i in range(2, len(stones)) : to_ret = max(to_ret, stones[i]-stones[i-2]) return to_ret
333cd9
996a9d
You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river. A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once. The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps. More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump is |stones[i] - stones[j]|. The cost of a path is the maximum length of a jump among all jumps in the path. Return the minimum cost of a path for the frog.   Example 1: Input: stones = [0,2,5,6,7] Output: 5 Explanation: The above figure represents one of the optimal paths the frog can take. The cost of this path is 5, which is the maximum length of a jump. Since it is not possible to achieve a cost of less than 5, we return it. Example 2: Input: stones = [0,3,9] Output: 9 Explanation: The frog can jump directly to the last stone and come back to the first stone. In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9. It can be shown that this is the minimum achievable cost.   Constraints: 2 <= stones.length <= 100000 0 <= stones[i] <= 10^9 stones[0] == 0 stones is sorted in a strictly increasing order.
class Solution(object): def maxJump(self, stones): """ :type stones: List[int] :rtype: int """ re=stones[1]-stones[0] for i in range(len(stones)-2): re=max(re,stones[i+2]-stones[i]) return re
671baa
c20426
You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick. You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining. Return the minimum cost of connecting all the given sticks into one stick in this way. Example 1: Input: sticks = [2,4,3] Output: 14 Explanation: You start with sticks = [2,4,3]. 1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4]. 2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9]. There is only one stick left, so you are done. The total cost is 5 + 9 = 14. Example 2: Input: sticks = [1,8,3,5] Output: 30 Explanation: You start with sticks = [1,8,3,5]. 1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5]. 2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8]. 3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17]. There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30. Example 3: Input: sticks = [5] Output: 0 Explanation: There is only one stick, so you don't need to do anything. The total cost is 0. Constraints: 1 <= sticks.length <= 10000 1 <= sticks[i] <= 10000
class Solution: def connectSticks(self, s: List[int]) -> int: heapq.heapify(s) ret = 0 while len(s) > 1: a, b = heapq.heappop(s), heapq.heappop(s) ret += a + b heapq.heappush(s, a + b) return ret
5afa8b
c20426
You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick. You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining. Return the minimum cost of connecting all the given sticks into one stick in this way. Example 1: Input: sticks = [2,4,3] Output: 14 Explanation: You start with sticks = [2,4,3]. 1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4]. 2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9]. There is only one stick left, so you are done. The total cost is 5 + 9 = 14. Example 2: Input: sticks = [1,8,3,5] Output: 30 Explanation: You start with sticks = [1,8,3,5]. 1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5]. 2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8]. 3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17]. There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30. Example 3: Input: sticks = [5] Output: 0 Explanation: There is only one stick, so you don't need to do anything. The total cost is 0. Constraints: 1 <= sticks.length <= 10000 1 <= sticks[i] <= 10000
import heapq class Solution(object): def connectSticks(self, sticks): """ :type sticks: List[int] :rtype: int """ heapq.heapify(sticks) res = 0 while len(sticks)>1: p1 = heapq.heappop(sticks) p2 = heapq.heappop(sticks) res+=p1+p2 heapq.heappush(sticks,p1+p2) return res
ef0bc1
390936
You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj). The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi). Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point. The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.   Example 1: Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]] Output: [2,1] Explanation: The first rectangle contains no points. The second rectangle contains only the point (2, 1). The third rectangle contains the points (2, 1) and (1, 4). The number of rectangles that contain the point (2, 1) is 2. The number of rectangles that contain the point (1, 4) is 1. Therefore, we return [2, 1]. Example 2: Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]] Output: [1,3] Explanation: The first rectangle contains only the point (1, 1). The second rectangle contains only the point (1, 1). The third rectangle contains the points (1, 3) and (1, 1). The number of rectangles that contain the point (1, 3) is 1. The number of rectangles that contain the point (1, 1) is 3. Therefore, we return [1, 3].   Constraints: 1 <= rectangles.length, points.length <= 5 * 10000 rectangles[i].length == points[j].length == 2 1 <= li, xj <= 10^9 1 <= hi, yj <= 100 All the rectangles are unique. All the points are unique.
class Solution(object): def countRectangles(self, rectangles, points): """ :type rectangles: List[List[int]] :type points: List[List[int]] :rtype: List[int] """ rectangles.sort() rectangles.reverse() queries = [] for i, p in enumerate(points): queries.append((p[0], p[1], i)) queries.sort() queries.reverse() dp = [0] * 105 ans = [0] * len(points) pp = 0 for px, py, i in queries: while pp < len(rectangles) and rectangles[pp][0] >= px: for j in range(rectangles[pp][1] + 1): dp[j] += 1 pp += 1 ans[i] = dp[py] return ans
8af571
390936
You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj). The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi). Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point. The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.   Example 1: Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]] Output: [2,1] Explanation: The first rectangle contains no points. The second rectangle contains only the point (2, 1). The third rectangle contains the points (2, 1) and (1, 4). The number of rectangles that contain the point (2, 1) is 2. The number of rectangles that contain the point (1, 4) is 1. Therefore, we return [2, 1]. Example 2: Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]] Output: [1,3] Explanation: The first rectangle contains only the point (1, 1). The second rectangle contains only the point (1, 1). The third rectangle contains the points (1, 3) and (1, 1). The number of rectangles that contain the point (1, 3) is 1. The number of rectangles that contain the point (1, 1) is 3. Therefore, we return [1, 3].   Constraints: 1 <= rectangles.length, points.length <= 5 * 10000 rectangles[i].length == points[j].length == 2 1 <= li, xj <= 10^9 1 <= hi, yj <= 100 All the rectangles are unique. All the points are unique.
class Solution: def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: to_ret = [None]*len(points) points = sorted([t+[i] for i, t in enumerate(points)]) rectangles = sorted(rectangles) # print(points) # print(rectangles) prec = len(rectangles) - 1 y_list = [] for px, py, pi in points[::-1] : while prec >= 0 and rectangles[prec][0] >= px : ppp = bisect.bisect(y_list, rectangles[prec][1]) y_list.insert(ppp, rectangles[prec][1]) prec -= 1 ps = bisect.bisect(y_list, py-.1) to_ret[pi] = len(y_list) - ps return to_ret
d78906
a71856
You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks.   Example 1: Input: tasks = [[1,2],[2,4],[4,8]] Output: 8 Explanation: Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. Example 2: Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]] Output: 32 Explanation: Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. Example 3: Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]] Output: 27 Explanation: Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6.   Constraints: 1 <= tasks.length <= 100000 1 <= actual​i <= minimumi <= 10000
class Solution: def minimumEffort(self, tasks: List[List[int]]) -> int: tasks.sort(key = lambda x: x[1]-x[0]) cur = 0 for dec,req in tasks: cur+=dec if cur<req:cur = req return cur
3a5df7
a71856
You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks.   Example 1: Input: tasks = [[1,2],[2,4],[4,8]] Output: 8 Explanation: Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. Example 2: Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]] Output: 32 Explanation: Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. Example 3: Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]] Output: 27 Explanation: Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6.   Constraints: 1 <= tasks.length <= 100000 1 <= actual​i <= minimumi <= 10000
class Solution(object): def minimumEffort(self, tasks): tasks.sort(key=lambda t: t[0] - t[1]) ans = R = max(r for a,r in tasks) for a,r in tasks: if R < r: d = r-R ans += d R += d R -= a return ans
1fc522
e736ec
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.   Example 1: Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]] Output: 2 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. Example 2: Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]] Output: 1 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. Example 3: Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]] Output: 3 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3.   Constraints: 2 <= row, col <= 2 * 10000 4 <= row * col <= 2 * 10000 cells.length == row * col 1 <= ri <= row 1 <= ci <= col All the values of cells are unique.
class Solution: def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: low, high = 0, row*col a = [[0 for i in range(col)] for j in range(row)] for i in range(row*col): a[cells[i][0]-1][cells[i][1]-1] = i+1 while low != high: mid = (low+high+1) >> 1 seen = [[False for i in range(col)] for j in range(row)] def dfs(x, y): seen[x][y] = True for i, j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if 0<=i<row and 0<=j<col and a[i][j] > mid and not seen[i][j]: dfs(i, j) for i in range(col): if a[0][i] > mid and not seen[0][i]: dfs(0, i) if any(seen[-1]): low = mid else: high = mid-1 return low
dd4583
e736ec
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.   Example 1: Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]] Output: 2 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. Example 2: Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]] Output: 1 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. Example 3: Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]] Output: 3 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3.   Constraints: 2 <= row, col <= 2 * 10000 4 <= row * col <= 2 * 10000 cells.length == row * col 1 <= ri <= row 1 <= ci <= col All the values of cells are unique.
class Solution(object): def latestDayToCross(self, row, col, cells): """ :type row: int :type col: int :type cells: List[List[int]] :rtype: int """ f = [[-1]*col for _ in xrange(row)] for t in xrange(row*col): r, c = cells[t] f[r-1][c-1] = t def test(day): vis = [[False]*col for _ in xrange(row)] q = [] def _consider(r, c): if r < 0 or c < 0 or r >= row or c >= col or vis[r][c] or f[r][c] < day: return q.append((r, c)) vis[r][c] = True for j in xrange(col): _consider(0, j) while q: r, c = q.pop() _consider(r-1, c) _consider(r+1, c) _consider(r, c-1) _consider(r, c+1) return any(vis[row-1]) x, y = 0, len(cells) while x + 1 < y: z = (x + y) >> 1 if test(z): x = z else: y = z return x
0bc704
37ab89
You are given two numeric strings num1 and num2 and two integers max_sum and min_sum. We denote an integer x to be good if: num1 <= x <= num2 min_sum <= digit_sum(x) <= max_sum. Return the number of good integers. Since the answer may be large, return it modulo 109 + 7. Note that digit_sum(x) denotes the sum of the digits of x.   Example 1: Input: num1 = "1", num2 = "12", min_sum = 1, max_sum = 8 Output: 11 Explanation: There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. Example 2: Input: num1 = "1", num2 = "5", min_sum = 1, max_sum = 5 Output: 5 Explanation: The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.   Constraints: 1 <= num1 <= num2 <= 1022 1 <= min_sum <= max_sum <= 400
class Solution: def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int: def f(size, digit_sum): @cache def dp(i, curr, lower): if curr > digit_sum: return 0 if i == len(size): return 1 ans = 0 if lower: for num in range(10): ans += dp(i + 1, curr + num, lower) else: for num in range(1 + int(size[i])): ans += dp(i + 1, curr + num, num < int(size[i])) return ans % MOD size = str(size) return dp(0, 0, False) MOD = 10 ** 9 + 7 num1 = int(num1) num2 = int(num2) return (f(num2, max_sum) - f(num1 - 1, max_sum) - f(num2, min_sum - 1) + f(num1 - 1, min_sum - 1)) % MOD