sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
8ec7bf
895341
You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a subarray that satisfies the following conditions: The minimum value in the subarray is equal to minK. The maximum value in the subarray is equal to maxK. Return the number of fixed-bound subarrays. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5 Output: 2 Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. Example 2: Input: nums = [1,1,1,1], minK = 1, maxK = 1 Output: 10 Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.   Constraints: 2 <= nums.length <= 100000 1 <= nums[i], minK, maxK <= 1000000
from typing import List, Tuple, Optional from collections import defaultdict, Counter from sortedcontainers import SortedList MOD = int(1e9 + 7) INF = int(1e20) class Solution: def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: n = len(nums) res, left = 0, 0 pos1, pos2 = -1, -1 for right in range(n): if nums[right] == minK: pos1 = right if nums[right] == maxK: pos2 = right if nums[right] < minK or nums[right] > maxK: left = right + 1 res += max(0, min(pos1, pos2) - left + 1) return res
3c39a5
895341
You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a subarray that satisfies the following conditions: The minimum value in the subarray is equal to minK. The maximum value in the subarray is equal to maxK. Return the number of fixed-bound subarrays. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5 Output: 2 Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. Example 2: Input: nums = [1,1,1,1], minK = 1, maxK = 1 Output: 10 Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.   Constraints: 2 <= nums.length <= 100000 1 <= nums[i], minK, maxK <= 1000000
class Solution(object): def countSubarrays(self, nums, minK, maxK): """ :type nums: List[int] :type minK: int :type maxK: int :rtype: int """ l, m, n, t = -1, -1, -1, 0 for i in range(len(nums)): m, l, n, t = i if nums[i] == minK else m, i if nums[i] == maxK else l, i if nums[i] < minK or nums[i] > maxK else n, t + max(0, min(i if nums[i] == minK else m, i if nums[i] == maxK else l) - (i if nums[i] < minK or nums[i] > maxK else n)) return t
c1caa4
975678
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome.   Example 1: Input: s = "aabb" Output: 2 Explanation: We can obtain two palindromes from s, "abba" and "baab". - We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba". - We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab". Thus, the minimum number of moves needed to make s a palindrome is 2. Example 2: Input: s = "letelt" Output: 2 Explanation: One of the palindromes we can obtain from s in 2 moves is "lettel". One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel". Other palindromes such as "tleelt" can also be obtained in 2 moves. It can be shown that it is not possible to obtain a palindrome in less than 2 moves.   Constraints: 1 <= s.length <= 2000 s consists only of lowercase English letters. s can be converted to a palindrome using a finite number of moves.
class BIT: def __init__(self, n): self.n = n self.bit = [0]*(self.n+1) # 1-indexed def init(self, init_val): for i, v in enumerate(init_val): self.add(i, v) def add(self, i, x): # i: 0-indexed i += 1 # to 1-indexed while i <= self.n: self.bit[i] += x i += (i & -i) def sum(self, i, j): # return sum of [i, j) # i, j: 0-indexed return self._sum(j) - self._sum(i) def _sum(self, i): # return sum of [0, i) # i: 0-indexed res = 0 while i > 0: res += self.bit[i] i -= i & (-i) return res def lower_bound(self, x): s = 0 pos = 0 depth = self.n.bit_length() v = 1 << depth for i in range(depth, -1, -1): k = pos + v if k <= self.n and s + self.bit[k] < x: s += self.bit[k] pos += v v >>= 1 return pos def __str__(self): # for debug arr = [self.sum(i,i+1) for i in range(self.n)] return str(arr) class Solution: def minMovesToMakePalindrome(self, s: str) -> int: S = list(s) S = [ord(c)-ord('a') for c in S] n = len(S) C = [[] for i in range(26)] for i, c in enumerate(S): C[c].append(i) o = 0 for c in range(26): if len(C[c])%2 == 1: o += 1 #if o > 1: #print(-1) #exit() L = [] M = [] R = [] for c in range(26): if len(C[c])%2 == 0: for j in range(len(C[c])): i = C[c][j] if j < len(C[c])//2: L.append(i) else: R.append(i) else: for j in range(len(C[c])): i = C[c][j] if j < len(C[c])//2: L.append(i) elif j == len(C[c])//2: M.append(i) else: R.append(i) L.sort() C = [list(reversed(l)) for l in C] N = L+M+list(reversed(L)) toid = {} for j, k in enumerate(N): c = S[k] i = C[c].pop() toid[i] = j bit = BIT(n+1) ans = 0 for i in range(n): ans += bit.sum(toid[i]+1, bit.n) bit.add(toid[i], 1) return ans
ea59bb
975678
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome.   Example 1: Input: s = "aabb" Output: 2 Explanation: We can obtain two palindromes from s, "abba" and "baab". - We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba". - We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab". Thus, the minimum number of moves needed to make s a palindrome is 2. Example 2: Input: s = "letelt" Output: 2 Explanation: One of the palindromes we can obtain from s in 2 moves is "lettel". One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel". Other palindromes such as "tleelt" can also be obtained in 2 moves. It can be shown that it is not possible to obtain a palindrome in less than 2 moves.   Constraints: 1 <= s.length <= 2000 s consists only of lowercase English letters. s can be converted to a palindrome using a finite number of moves.
class Solution(object): def minMovesToMakePalindrome(self, s): """ :type s: str :rtype: int """ cs = [0]*26 b=ord('a') ss = [ord(c)-b for c in s] for c in ss: cs[c]+=1 ccs = [0]*26 n = len(s) m = n/2 rc=0 for i in range(m): j=i while j<n: c=ss[j] if ccs[c]+ccs[c]+1+1>cs[c]: j+=1 else: break c=ss[j] while j>i: ss[j]=ss[j-1] j-=1 rc+=1 ss[i]=c ccs[c]+=1 if n&1: i=m while i<n: c=ss[i] if ccs[c]+ccs[c]<cs[c]: break i+=1 c=ss[i] while i>m: ss[i]=ss[i-1] i-=1 rc+=1 ss[i]=c nss = [] for i in range(m): nss.append(ss[n-1-i]) # print ss[:m], nss for i in range(m): if ss[i]==nss[i]: continue j=i while j<m and nss[j]!=ss[i]: j+=1 c=nss[j] while j>i: nss[j]=nss[j-1] j-=1 rc+=1 return rc
cc551f
867d3e
Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0.   Example 1: Input: n = 3 Output: 2 Explanation: The binary representation of 3 is "11". "11" -> "01" with the 2nd operation since the 0th bit is 1. "01" -> "00" with the 1st operation. Example 2: Input: n = 6 Output: 4 Explanation: The binary representation of 6 is "110". "110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010" -> "011" with the 1st operation. "011" -> "001" with the 2nd operation since the 0th bit is 1. "001" -> "000" with the 1st operation.   Constraints: 0 <= n <= 10^9
class Solution: def minimumOneBitOperations(self, n: int) -> int: def solve(m = n) : if m <= 1 : return m maxt = (1 << (len(bin(m))-3)) return (2*maxt-1) - solve(m-maxt) to_ret = solve() return to_ret
1cd072
867d3e
Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0.   Example 1: Input: n = 3 Output: 2 Explanation: The binary representation of 3 is "11". "11" -> "01" with the 2nd operation since the 0th bit is 1. "01" -> "00" with the 1st operation. Example 2: Input: n = 6 Output: 4 Explanation: The binary representation of 6 is "110". "110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010" -> "011" with the 1st operation. "011" -> "001" with the 2nd operation since the 0th bit is 1. "001" -> "000" with the 1st operation.   Constraints: 0 <= n <= 10^9
class Solution(object): def minimumOneBitOperations(self, n): """ :type n: int :rtype: int """ # this is simply inverse gray code a, b = n, 1 while a: a = n >> b b <<= 1 n ^= a return n
dae4ae
469eec
Imagine you have a special keyboard with the following keys: A: Print one 'A' on the screen. Ctrl-A: Select the whole screen. Ctrl-C: Copy selection to buffer. Ctrl-V: Print buffer on screen appending it after what has already been printed. Given an integer n, return the maximum number of 'A' you can print on the screen with at most n presses on the keys. Example 1: Input: n = 3 Output: 3 Explanation: We can at most get 3 A's on screen by pressing the following key sequence: A, A, A Example 2: Input: n = 7 Output: 9 Explanation: We can at most get 9 A's on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V Constraints: 1 <= n <= 50
class Solution(object): def maxA(self, N): """ :type N: int :rtype: int """ if N <=4: return N dp = range(N+1) for i in xrange(5, N+1): tmp = i for j in xrange(0, i-3): tmp = max(tmp, dp[i-3-j]*(j+2)) dp[i] = tmp return dp[N]
4d7bd7
469eec
Imagine you have a special keyboard with the following keys: A: Print one 'A' on the screen. Ctrl-A: Select the whole screen. Ctrl-C: Copy selection to buffer. Ctrl-V: Print buffer on screen appending it after what has already been printed. Given an integer n, return the maximum number of 'A' you can print on the screen with at most n presses on the keys. Example 1: Input: n = 3 Output: 3 Explanation: We can at most get 3 A's on screen by pressing the following key sequence: A, A, A Example 2: Input: n = 7 Output: 9 Explanation: We can at most get 9 A's on screen by pressing following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V Constraints: 1 <= n <= 50
class Solution: def maxA(self, N): """ :type N: int :rtype: int """ # Base case cache = {} def _maxA(N): if N <= 3: return N answer = cache.get(N, None) if answer is not None: return answer # Lower-bound is simply press 'A' N times best = N # How many paste is pressed for k in range(1, N): if k + 2 < N: best = max(best, _maxA(N-k-2) * (k+1)) best = max(best, _maxA(N-1)+1) cache[N] = best return best return _maxA(N)
bd3028
41cc02
You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type. You need to distribute all products to the retail stores following these rules: A store can only be given at most one product type but can be given any amount of it. After distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store. Return the minimum possible x.   Example 1: Input: n = 6, quantities = [11,6] Output: 3 Explanation: One optimal way is: - The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3 - The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3 The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3. Example 2: Input: n = 7, quantities = [15,10,10] Output: 5 Explanation: One optimal way is: - The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5 - The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5 - The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5 The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5. Example 3: Input: n = 1, quantities = [100000] Output: 100000 Explanation: The only optimal way is: - The 100000 products of type 0 are distributed to the only store. The maximum number of products given to any store is max(100000) = 100000.   Constraints: m == quantities.length 1 <= m <= n <= 100000 1 <= quantities[i] <= 100000
class Solution(object): def minimizedMaximum(self, n, quantities): """ :type n: int :type quantities: List[int] :rtype: int """ def _test(r): c = 0 for q in quantities: c += (q+r-1) // r return c <= n x, y = 0, max(quantities) while x + 1 < y: z = (x + y) >> 1 if _test(z): y = z else: x = z return y
4550cb
41cc02
You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type. You need to distribute all products to the retail stores following these rules: A store can only be given at most one product type but can be given any amount of it. After distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store. Return the minimum possible x.   Example 1: Input: n = 6, quantities = [11,6] Output: 3 Explanation: One optimal way is: - The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3 - The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3 The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3. Example 2: Input: n = 7, quantities = [15,10,10] Output: 5 Explanation: One optimal way is: - The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5 - The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5 - The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5 The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5. Example 3: Input: n = 1, quantities = [100000] Output: 100000 Explanation: The only optimal way is: - The 100000 products of type 0 are distributed to the only store. The maximum number of products given to any store is max(100000) = 100000.   Constraints: m == quantities.length 1 <= m <= n <= 100000 1 <= quantities[i] <= 100000
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: def possible(m): needed = 0 for x in quantities: needed += (x + m - 1) // m return needed <= n lo = 1 hi = 10 ** 10 ans = 10 ** 10 while lo <= hi: mid = (lo + hi) // 2 if possible(mid): ans = min(ans, mid) hi = mid - 1 else: lo = mid + 1 return ans
710078
8ed215
A string is considered beautiful if it satisfies the following conditions: Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.). For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string.   Example 1: Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" Output: 13 Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. Example 2: Input: word = "aeeeiiiioooauuuaeiou" Output: 5 Explanation: The longest beautiful substring in word is "aeiou" of length 5. Example 3: Input: word = "a" Output: 0 Explanation: There is no beautiful substring, so return 0.   Constraints: 1 <= word.length <= 5 * 100000 word consists of characters 'a', 'e', 'i', 'o', and 'u'.
class Solution: def longestBeautifulSubstring(self, word: str) -> int: started = False res = 0 lets = list("aeiou") word = [lets.index(x) for x in list(word)] for i in range(len(word)): if not started: if word[i] == 0: started = True start = i else: if word[i] < word[i-1] or word[i] > word[i-1] + 1: if word[i] == 0: start = i else: started = False else: if word[i] == 4: res = max(res, i - start + 1) return res
986903
8ed215
A string is considered beautiful if it satisfies the following conditions: Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.). For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string.   Example 1: Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" Output: 13 Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. Example 2: Input: word = "aeeeiiiioooauuuaeiou" Output: 5 Explanation: The longest beautiful substring in word is "aeiou" of length 5. Example 3: Input: word = "a" Output: 0 Explanation: There is no beautiful substring, so return 0.   Constraints: 1 <= word.length <= 5 * 100000 word consists of characters 'a', 'e', 'i', 'o', and 'u'.
class Solution(object): def longestBeautifulSubstring(self, word): res = 0 A = [[c, len(list(s))] for c,s in itertools.groupby(word)] for i in xrange(len(A) - 4): if ''.join(A[j][0] for j in xrange(i, i+5)) == 'aeiou': res = max(res, sum(A[j][1] for j in xrange(i, i+5))) return res
678aa3
dbd6ec
You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be: 1 which means a street connecting the left cell and the right cell. 2 which means a street connecting the upper cell and the lower cell. 3 which means a street connecting the left cell and the lower cell. 4 which means a street connecting the right cell and the lower cell. 5 which means a street connecting the left cell and the upper cell. 6 which means a street connecting the right cell and the upper cell. You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets. Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise.   Example 1: Input: grid = [[2,4,3],[6,5,2]] Output: true Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1). Example 2: Input: grid = [[1,2,1],[1,2,1]] Output: false Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0) Example 3: Input: grid = [[1,1,2]] Output: false Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 300 1 <= grid[i][j] <= 6
from collections import defaultdict class Solution(object): def hasValidPath(self, grid): """ :type grid: List[List[int]] :rtype: bool """ ACT = { 'L': (0,-1), 'R': (0, 1), 'U': (-1,0), 'D': (1,0), } DIRS = { 1: 'LR', 2: 'UD', 3: 'LD', 4: 'RD', 5: 'LU', 6: 'UR', } OPP = { 'L':'R', 'R':'L', 'U':'D', 'D':'U' } stack = [(0,0)] visited = defaultdict(bool) R = len(grid) C = len(grid[0]) while stack: r, c = stack.pop() if visited[r,c]: continue visited[r,c] = True if r == R -1 and c == C -1: return True for d in DIRS[grid[r][c]]: dr, dc = ACT[d] nr, nc = dr + r, dc + c if nr < 0 or nr >= R or nc <0 or nc >= C: continue if OPP[d] not in DIRS[grid[nr][nc]]: continue stack.append((nr, nc)) return False
43cf0d
dbd6ec
You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be: 1 which means a street connecting the left cell and the right cell. 2 which means a street connecting the upper cell and the lower cell. 3 which means a street connecting the left cell and the lower cell. 4 which means a street connecting the right cell and the lower cell. 5 which means a street connecting the left cell and the upper cell. 6 which means a street connecting the right cell and the upper cell. You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets. Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise.   Example 1: Input: grid = [[2,4,3],[6,5,2]] Output: true Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1). Example 2: Input: grid = [[1,2,1],[1,2,1]] Output: false Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0) Example 3: Input: grid = [[1,1,2]] Output: false Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 300 1 <= grid[i][j] <= 6
class Solution: def hasValidPath(self, grid: List[List[int]]) -> bool: R, C = len(grid), len(grid[0]) parents = {} def find(p): if p not in parents: parents[p] = p if parents[p] != p: parents[p] = find(parents[p]) return parents[p] def union(p, q): i, j = find(p), find(q) parents[j] = i def connect(r, c): if grid[r][c] == 1: if c > 0 and grid[r][c-1] in [1,4,6]: union((r, c), (r, c-1)) if c < C - 1 and grid[r][c+1] in [1,3,5]: union((r, c), (r, c+1)) elif grid[r][c] == 2: if r > 0 and grid[r-1][c] in [2,3,4]: union((r, c), (r-1, c)) if r < R - 1 and grid[r+1][c] in [2,5,6]: union((r, c), (r+1, c)) elif grid[r][c] == 3: if c > 0 and grid[r][c-1] in [1,4,6]: union((r, c-1), (r, c)) if r < R - 1 and grid[r+1][c] in [2,5,6]: union((r, c), (r+1, c)) elif grid[r][c] == 4: if r < R - 1 and grid[r+1][c] in [2,5,6]: union((r, c), (r+1, c)) if c < C - 1 and grid[r][c+1] in [1,3,5]: union((r, c), (r, c+1)) elif grid[r][c] == 5: if r > 0 and grid[r-1][c] in [2,3,4]: union((r, c), (r-1, c)) if c > 0 and grid[r][c-1] in [1,4,6]: union((r, c-1), (r, c)) elif grid[r][c] == 6: if r > 0 and grid[r-1][c] in [2,3,4]: union((r, c), (r-1, c)) if c < C - 1 and grid[r][c+1] in [1,3,5]: union((r, c), (r, c+1)) for r in range(R): for c in range(C): connect(r, c) return find((0, 0)) == find((R-1, C-1))
b8a042
72d811
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.   Example 1: Input: s = "QWER" Output: 0 Explanation: s is already balanced. Example 2: Input: s = "QQWE" Output: 1 Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced. Example 3: Input: s = "QQQW" Output: 2 Explanation: We can replace the first "QQ" to "ER".   Constraints: n == s.length 4 <= n <= 100000 n is a multiple of 4. s contains only 'Q', 'W', 'E', and 'R'.
class Solution(object): def balancedString(self, S): A = ['QWER'.index(c) for c in S] N = len(A) counts = [0,0,0,0] P = [counts[:]] for x in A: counts[x] += 1 P.append(counts[:]) T = len(A) / 4 if counts[0] == counts[1] == counts[2] == counts[3] == T: return 0 def possible(size): for i in xrange(N - size + 1): j = i + size #P[j] - P[i] is what is deleted # remaining is counts - P[j] + P[i] for d in xrange(4): if counts[d] - P[j][d] + P[i][d] > T: break else: return True return False lo = 0 hi = N while lo < hi: # inv: possible for N mi = (lo + hi) / 2 if possible(mi): hi = mi else: lo = mi + 1 return lo
249e11
72d811
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.   Example 1: Input: s = "QWER" Output: 0 Explanation: s is already balanced. Example 2: Input: s = "QQWE" Output: 1 Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced. Example 3: Input: s = "QQQW" Output: 2 Explanation: We can replace the first "QQ" to "ER".   Constraints: n == s.length 4 <= n <= 100000 n is a multiple of 4. s contains only 'Q', 'W', 'E', and 'R'.
class Solution: def balancedString(self, s: str) -> int: n, req = len(s), len(s) // 4 c_all = collections.Counter(s) c_cur = collections.Counter() l = -1 ans = n for r in range(n): c_cur[s[r]] += 1 while l < r: c_cur[s[l + 1]] -= 1 flag = all(c_all[ch] - c_cur[ch] <= req for ch in "QWER") if flag: l += 1 else: c_cur[s[l + 1]] += 1 break if all(c_all[ch] - c_cur[ch] <= req for ch in "QWER"): ans = min(ans, r - l) return ans
8990fb
8f2c6e
You are given a 0-indexed integer array nums. Initially, all of the indices are unmarked. You are allowed to make this operation any number of times: Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j. Return the maximum possible number of marked indices in nums using the above operation any number of times.   Example 1: Input: nums = [3,5,2,4] Output: 2 Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1. It can be shown that there's no other valid operation so the answer is 2. Example 2: Input: nums = [9,2,5,4] Output: 4 Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. Example 3: Input: nums = [7,6,8] Output: 0 Explanation: There is no valid operation to do, so the answer is 0.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9  
class Solution(object): def maxNumOfMarkedIndices(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() a, j = 0, len(nums) - 1 for i in range(len(nums) / 2 - 1, -1, -1): a, j = a if nums[i] * 2 > nums[j] else a + 2, j if nums[i] * 2 > nums[j] else j - 1 return a
29d26b
8f2c6e
You are given a 0-indexed integer array nums. Initially, all of the indices are unmarked. You are allowed to make this operation any number of times: Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j. Return the maximum possible number of marked indices in nums using the above operation any number of times.   Example 1: Input: nums = [3,5,2,4] Output: 2 Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1. It can be shown that there's no other valid operation so the answer is 2. Example 2: Input: nums = [9,2,5,4] Output: 4 Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. Example 3: Input: nums = [7,6,8] Output: 0 Explanation: There is no valid operation to do, so the answer is 0.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9  
class Solution: def maxNumOfMarkedIndices(self, nums: List[int]) -> int: n = len(nums) nums.sort() l, r = 0, len(nums) // 2 while l <= r: m = (l + r) // 2 for i in range(m): if nums[i] * 2 > nums[n-m+i]: r = m - 1 break else: l = m + 1 return r * 2
fdcd96
983764
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes: 't' that evaluates to true. 'f' that evaluates to false. '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. Given a string expression that represents a boolean expression, return the evaluation of that expression. It is guaranteed that the given expression is valid and follows the given rules.   Example 1: Input: expression = "&(|(f))" Output: false Explanation: First, evaluate |(f) --> f. The expression is now "&(f)". Then, evaluate &(f) --> f. The expression is now "f". Finally, return false. Example 2: Input: expression = "|(f,f,f,t)" Output: true Explanation: The evaluation of (false OR false OR false OR true) is true. Example 3: Input: expression = "!(&(f,t))" Output: true Explanation: First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)". Then, evaluate !(f) --> NOT false --> true. We return true.   Constraints: 1 <= expression.length <= 2 * 10000 expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
class Solution(object): def parseBoolExpr(self, expression): """ :type expression: str :rtype: bool """ def helper(i,j): if i==j: return True if expression[i]=='t' else False if expression[i]=='!': return not helper(i+2,j-1) if expression[i]=='&': st=ed=i+2 while st<j: cnt=0 while ed<j and (cnt!=0 or expression[ed]!=','): if expression[ed]=='(': cnt+=1 elif expression[ed]==')': cnt-=1 ed+=1 tmp=helper(st,ed-1) if not tmp: return False st=ed+1 ed=st return True if expression[i]=='|': st=ed=i+2 while st<j: cnt=0 while ed<j and (cnt!=0 or expression[ed]!=','): if expression[ed]=='(': cnt+=1 elif expression[ed]==')': cnt-=1 ed+=1 tmp=helper(st,ed-1) if tmp: return True st=ed+1 ed=st return False return helper(0,len(expression)-1)
720152
983764
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes: 't' that evaluates to true. 'f' that evaluates to false. '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. Given a string expression that represents a boolean expression, return the evaluation of that expression. It is guaranteed that the given expression is valid and follows the given rules.   Example 1: Input: expression = "&(|(f))" Output: false Explanation: First, evaluate |(f) --> f. The expression is now "&(f)". Then, evaluate &(f) --> f. The expression is now "f". Finally, return false. Example 2: Input: expression = "|(f,f,f,t)" Output: true Explanation: The evaluation of (false OR false OR false OR true) is true. Example 3: Input: expression = "!(&(f,t))" Output: true Explanation: First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)". Then, evaluate !(f) --> NOT false --> true. We return true.   Constraints: 1 <= expression.length <= 2 * 10000 expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
def booleval (expr): if type (expr) is list: oper = expr[0] if oper == '!': return not (booleval (expr[1])) elif oper == '&': return all (booleval (subexpr) for subexpr in expr[1:]) elif oper == '|': return any (booleval (subexpr) for subexpr in expr[1:]) else: return {'t':True, 'f':False} [expr] class Solution: def parseBoolExpr(self, expression): stack = [[]] for char in expression: if char in 'tf': stack[-1].append (char) elif char == ')': stack[-2].append (stack[-1]) stack.pop () elif char in '!&|': stack.append ([char]) return booleval (stack[-1][-1])
c793ba
6cc1d1
You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty: Remove the first character of a string s and give it to the robot. The robot will append this character to the string t. Remove the last character of a string t and give it to the robot. The robot will write this character on paper. Return the lexicographically smallest string that can be written on the paper.   Example 1: Input: s = "zza" Output: "azz" Explanation: Let p denote the written string. Initially p="", s="zza", t="". Perform first operation three times p="", s="", t="zza". Perform second operation three times p="azz", s="", t="". Example 2: Input: s = "bac" Output: "abc" Explanation: Let p denote the written string. Perform first operation twice p="", s="c", t="ba". Perform second operation twice p="ab", s="c", t="". Perform first operation p="ab", s="", t="c". Perform second operation p="abc", s="", t="". Example 3: Input: s = "bdda" Output: "addb" Explanation: Let p denote the written string. Initially p="", s="bdda", t="". Perform first operation four times p="", s="", t="bdda". Perform second operation four times p="addb", s="", t="".   Constraints: 1 <= s.length <= 100000 s consists of only English lowercase letters.
class Solution(object): def robotWithString(self, s): """ :type s: str :rtype: str """ m, t, u = [0] * (len(s) - 1) + [s[-1]], [], [] for i in range(len(s) - 2, -1, -1): m[i] = s[i] if s[i] < m[i + 1] else m[i + 1] for i in range(len(s)): u.append(s[i]) if i < len(s) - 1: while u and u[-1] <= m[i + 1]: t.append(u.pop()) while u: t.append(u.pop()) return ''.join(t)
501dc9
6cc1d1
You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty: Remove the first character of a string s and give it to the robot. The robot will append this character to the string t. Remove the last character of a string t and give it to the robot. The robot will write this character on paper. Return the lexicographically smallest string that can be written on the paper.   Example 1: Input: s = "zza" Output: "azz" Explanation: Let p denote the written string. Initially p="", s="zza", t="". Perform first operation three times p="", s="", t="zza". Perform second operation three times p="azz", s="", t="". Example 2: Input: s = "bac" Output: "abc" Explanation: Let p denote the written string. Perform first operation twice p="", s="c", t="ba". Perform second operation twice p="ab", s="c", t="". Perform first operation p="ab", s="", t="c". Perform second operation p="abc", s="", t="". Example 3: Input: s = "bdda" Output: "addb" Explanation: Let p denote the written string. Initially p="", s="bdda", t="". Perform first operation four times p="", s="", t="bdda". Perform second operation four times p="addb", s="", t="".   Constraints: 1 <= s.length <= 100000 s consists of only English lowercase letters.
class Solution: def robotWithString(self, s: str) -> str: l = list(s) res = [] stack = [] minb = [] for i in range(len(l) - 1, -1, -1): if i == len(l) - 1: minb.append(l[-1]) else: minb.append(min(minb[-1], l[i])) minb.reverse() for i, c in enumerate(l): if c != minb[i]: stack.append(c) else: res.append(c) if i == len(l) - 1: break while stack and stack[-1] <= minb[i + 1]: res.append(stack.pop()) while stack: res.append(stack.pop()) return ''.join(res)
0353b6
882fe5
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.   Example 1: Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. Example 2: Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. Example 3: Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 Output: 500 Explanation: The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.   Constraints: 1 <= n <= 100 0 <= flights.length <= (n * (n - 1) / 2) flights[i].length == 3 0 <= fromi, toi < n fromi != toi 1 <= pricei <= 10000 There will not be any multiple flights between two cities. 0 <= src, dst, k < n src != dst
class Solution(object): def findCheapestPrice(self, n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ D = [-1] * n D[src] = 0 # non-stop for s,t,c in flights: if s == src: D[t] = c print(D) # starting from stop 1 to stop k for ii in range(K): E = D[::] # My fault. Should be initalized as D[::] not [-1] * n for s,t,c in flights: if D[s] >= 0 and (E[t] == -1 or E[t] > D[s] + c): E[t] = D[s] + c D = E print(D) return D[dst]
208c34
882fe5
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.   Example 1: Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. Example 2: Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. Example 3: Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 Output: 500 Explanation: The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.   Constraints: 1 <= n <= 100 0 <= flights.length <= (n * (n - 1) / 2) flights[i].length == 3 0 <= fromi, toi < n fromi != toi 1 <= pricei <= 10000 There will not be any multiple flights between two cities. 0 <= src, dst, k < n src != dst
class Solution: def findCheapestPrice(self, n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ from heapq import heappop, heappush connected = {} # map from node to {(connected, cost)} for i in range(n): connected[i] = [] for src1, dst1, price in flights: connected[src1].append((dst1, price)) flights_left = K+1 heap = [] # heap of (cost to curr point, curr point, flights left) best_costs = {} # map from node to (cost, flights left) heappush(heap, (0, src, flights_left)) while heap: cost, node, curr_left = heappop(heap) if node not in best_costs: best_costs[node] = (cost, curr_left) else: best_cost, best_flights_left = best_costs[node] if cost <= best_cost and curr_left >= best_flights_left: best_costs[node] = (cost, curr_left) if node == dst: return cost if curr_left != 0: for conn, conn_cost in connected[node]: next_cost = cost + conn_cost if conn in best_costs: best_cost, best_flights_left = best_costs[conn] if not (next_cost < best_cost or curr_left-1 > best_flights_left): continue else: heappush(heap, (next_cost, conn, curr_left-1)) return -1
de165a
8bcf4a
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions: The path starts from the upper left cell (0, 0). The path ends at the bottom-right cell (m - 1, n - 1). The path only ever moves down or right. The resulting parentheses string formed by the path is valid. Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.   Example 1: Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]] Output: true Explanation: The above diagram shows two possible paths that form valid parentheses strings. The first path shown results in the valid parentheses string "()(())". The second path shown results in the valid parentheses string "((()))". Note that there may be other valid parentheses string paths. Example 2: Input: grid = [[")",")"],["(","("]] Output: false Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is either '(' or ')'.
class Solution: def hasValidPath(self, grid: List[List[str]]) -> bool: h,w=len(grid),len(grid[0]) g=grid dp=[[set() for _ in range(w)] for _ in range(h)] for y in range(h): for x in range(w): t= 1 if g[y][x]=="(" else -1 if y==0 and x==0: if g[y][x]=="(": dp[y][x].add(1) elif y==0: for a in dp[y][x-1]: if a+t>=0: dp[y][x].add(a+t) elif x==0: for a in dp[y-1][x]: if a+t>=0: dp[y][x].add(a+t) else: for a in dp[y-1][x]: if a+t>=0: dp[y][x].add(a+t) for a in dp[y][x-1]: if a+t>=0: dp[y][x].add(a+t) return 0 in dp[h-1][w-1]
eb570f
8bcf4a
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions: The path starts from the upper left cell (0, 0). The path ends at the bottom-right cell (m - 1, n - 1). The path only ever moves down or right. The resulting parentheses string formed by the path is valid. Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.   Example 1: Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]] Output: true Explanation: The above diagram shows two possible paths that form valid parentheses strings. The first path shown results in the valid parentheses string "()(())". The second path shown results in the valid parentheses string "((()))". Note that there may be other valid parentheses string paths. Example 2: Input: grid = [[")",")"],["(","("]] Output: false Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is either '(' or ')'.
class Solution(object): def hasValidPath(self, grid): """ :type grid: List[List[str]] :rtype: bool """ v = [[[False] * max(len(grid), len(grid[0])) for _ in grid[0]] for _ in grid] def h(r, c, s): if r == len(grid) or c == len(grid[0]) or s > len(grid) - r + len(grid[0]) - c - 1 or s < 0 or v[r][c][s]: return False v[r][c][s] = True if r == len(grid) - 1 and c == len(grid[0]) - 1: return s + (1 if grid[r][c] == '(' else -1) == 0 return h(r + 1, c, s + (1 if grid[r][c] == '(' else -1)) or h(r, c + 1, s + (1 if grid[r][c] == '(' else -1)) return h(0, 0, 0)
fc171e
fb7dba
You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can jump to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you visit index i. In addition to that, if you are currently at index i, you can only jump to any index i + k where i + k <= n and k is a value in the range [1, maxJump]. You are initially positioned at index 1 (coins[1] is not -1). You want to find the path that reaches index n with the minimum cost. Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the lexicographically smallest such path. If it is not possible to reach index n, return an empty array. A path p1 = [Pa1, Pa2, ..., Pax] of length x is lexicographically smaller than p2 = [Pb1, Pb2, ..., Pbx] of length y, if and only if at the first j where Paj and Pbj differ, Paj < Pbj; when no such j exists, then x < y. Example 1: Input: coins = [1,2,4,-1,2], maxJump = 2 Output: [1,3,5] Example 2: Input: coins = [1,2,4,-1,2], maxJump = 1 Output: [] Constraints: 1 <= coins.length <= 1000 -1 <= coins[i] <= 100 coins[1] != -1 1 <= maxJump <= 100
class Solution(object): def cheapestJump(self, A, B): """ :type A: List[int] :type B: int :rtype: List[int] """ dp = [None] * len(A) dp[0] = (0, [1]) def cmp(a, b): zz = min(len(a), len(b)) for i in range(zz): if a[i] < b[i]: return True elif a[i] > b[i]: return False return len(a) > len(b) BIG = 987987987 for i in range(1, len(A)): costi = A[i] if costi == -1: continue b4 = max(0, i - B) best = BIG ba = [] for j in range(b4, i): if dp[j] is None: continue c, a = dp[j] if c < best: best = c ba = a elif c == best and cmp(a,ba): best = c ba = a if best == BIG: continue nc = best + costi na = ba[:] + [i+1] dp[i] = (nc, na) zzz = dp[-1] if zzz is None: return [] return zzz[1]
540514
fb7dba
You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can jump to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you visit index i. In addition to that, if you are currently at index i, you can only jump to any index i + k where i + k <= n and k is a value in the range [1, maxJump]. You are initially positioned at index 1 (coins[1] is not -1). You want to find the path that reaches index n with the minimum cost. Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the lexicographically smallest such path. If it is not possible to reach index n, return an empty array. A path p1 = [Pa1, Pa2, ..., Pax] of length x is lexicographically smaller than p2 = [Pb1, Pb2, ..., Pbx] of length y, if and only if at the first j where Paj and Pbj differ, Paj < Pbj; when no such j exists, then x < y. Example 1: Input: coins = [1,2,4,-1,2], maxJump = 2 Output: [1,3,5] Example 2: Input: coins = [1,2,4,-1,2], maxJump = 1 Output: [] Constraints: 1 <= coins.length <= 1000 -1 <= coins[i] <= 100 coins[1] != -1 1 <= maxJump <= 100
class Solution: def cheapestJump(self, A, B): """ :type A: List[int] :type B: int :rtype: List[int] """ if A[0] == -1: return [] NA = len(A) B += 1 dp = [(float('inf'), tuple())] * NA # (cost, arr) dp[0] = (A[0], (1,)) for i in range(NA): costi, wayi = dp[i] if costi == float('inf'): continue for j in range(i + 1, min(i + B, NA)): nj = A[j] if nj == -1: continue if costi + nj <= dp[j][0]: dp[j] = min(dp[j], (costi + nj, wayi + (j + 1,))) return dp[-1][1]
e9b3d2
19eb68
There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole. Given the m x n maze, the ball's position ball and the hole's position hole, where ball = [ballrow, ballcol] and hole = [holerow, holecol], return a string instructions of all the instructions that the ball should follow to drop in the hole with the shortest distance possible. If there are multiple valid instructions, return the lexicographically minimum one. If the ball can't drop in the hole, return "impossible". If there is a way for the ball to drop in the hole, the answer instructions should contain the characters 'u' (i.e., up), 'd' (i.e., down), 'l' (i.e., left), and 'r' (i.e., right). The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). You may assume that the borders of the maze are all walls (see examples). Example 1: Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1] Output: "lul" Explanation: There are two shortest ways for the ball to drop into the hole. The first way is left -> up -> left, represented by "lul". The second way is up -> left, represented by 'ul'. Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul". Example 2: Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0] Output: "impossible" Explanation: The ball cannot reach the hole. Example 3: Input: maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5] Output: "dldr" Constraints: m == maze.length n == maze[i].length 1 <= m, n <= 100 maze[i][j] is 0 or 1. ball.length == 2 hole.length == 2 0 <= ballrow, holerow <= m 0 <= ballcol, holecol <= n Both the ball and the hole exist in an empty space, and they will not be in the same position initially. The maze contains at least 2 empty spaces.
class Solution(object): def findShortestWay(self, A, ball, hole): R,C = len(A), len(A[0]) ball=tuple(ball) hole=tuple(hole) def neighbors(r, c): for dr, dc, di in [(-1,0,'u'), (0,1,'r'), (0,-1,'l'), (1,0,'d')]: cr, cc = r, c dm = 0 while 0 <= cr + dr < R and 0 <= cc + dc < C and not A[cr+dr][cc+dc]: cr+=dr cc+=dc dm += 1 if (cr,cc) == hole: yield (cr, cc), di, dm, True break else: yield (cr, cc), di, dm, False pq = [(0, '', ball, False)] seen = set() #shortest distance, break ties by path while pq: dist, path, node, flag = heapq.heappop(pq) if node in seen: continue if node == hole or flag: return path seen.add(node) for nei, di, nei_dist, flag in neighbors(*node): heapq.heappush(pq, (dist+nei_dist, path+di, nei, flag) ) return "impossible" """ #dq = collections.deque() #dq.append((ball, '')) stack = [(ball, '', False)] seen = set() def neighbors(r, c): #dlru for dr, dc, di in [(-1,0,'u'), (0,1,'r'), (0,-1,'l'), (1,0,'d')]: cr, cc = r, c flag = False while 0 <= cr + dr < R and 0 <= cc + dc < C and not A[cr+dr][cc+dc]: cr+=dr cc+=dc if (cr,cc) == hole: print 'r,c', len(A), r,c,cr,cc flag = True yield (cr,cc), di, flag while stack: node, path, flag = stack.pop() if node == hole or flag: return path for nei, di, flag in neighbors(*node): if (nei, di) not in seen: seen.add((nei,di)) stack.append((nei, path+di, flag)) return "impossible" """
c867f5
86e987
Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids.   Example 1: Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]] Output: 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: Input: cuboids = [[38,25,45],[76,35,3]] Output: 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]] Output: 102 Explanation: After rearranging the cuboids, you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102.   Constraints: n == cuboids.length 1 <= n <= 100 1 <= widthi, lengthi, heighti <= 100
class Solution: def maxHeight(self, cuboids: List[List[int]]) -> int: def ok(a, b): return a[0]<=b[0] and a[1]<=b[1] and a[2]<=b[2] N = len(cuboids) for i in range(N): cuboids[i].sort() cuboids.sort() dp = [cuboids[i][2] for i in range(N)] for i in range(N): for j in range(i): if ok(cuboids[j], cuboids[i]): dp[i] = max(dp[i], dp[j]+cuboids[i][-1]) return max(dp)
18dbd5
86e987
Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids.   Example 1: Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]] Output: 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: Input: cuboids = [[38,25,45],[76,35,3]] Output: 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]] Output: 102 Explanation: After rearranging the cuboids, you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102.   Constraints: n == cuboids.length 1 <= n <= 100 1 <= widthi, lengthi, heighti <= 100
class Solution(object): def maxHeight(self, cuboids): """ :type cuboids: List[List[int]] :rtype: int """ a = [] for cube in cuboids: a.extend(set(permutations(cube))) a.sort(key=lambda (x,y,z):x*y*z) f = [z for x,y,z in a] for i in xrange(len(a)): for j in xrange(i): if all(a[j][k]<=a[i][k] for k in xrange(3)): f[i] = max(f[i], f[j] + a[i][2]) return max(f)
b838f4
52b39f
There are n people and 40 types of hats labeled from 1 to 40. Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: hats = [[3,4],[4,5],[5]] Output: 1 Explanation: There is only one way to choose hats given the conditions. First person choose hat 3, Second person choose hat 4 and last one hat 5. Example 2: Input: hats = [[3,5,1],[3,5]] Output: 4 Explanation: There are 4 ways to choose hats: (3,5), (5,3), (1,3) and (1,5) Example 3: Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] Output: 24 Explanation: Each person can choose hats labeled from 1 to 4. Number of Permutations of (1,2,3,4) = 24.   Constraints: n == hats.length 1 <= n <= 10 1 <= hats[i].length <= 40 1 <= hats[i][j] <= 40 hats[i] contains a list of unique integers.
class Solution: def numberWays(self, hats): hh = [] n = len(hats) for h in hats: hh.append(set(h)) mod = int(1e9 + 7) fc = [0] * (1 << n) fc[0] = 1 for i in range(1, 41): fp = [v for v in fc] fc = [v for v in fp] for k in range(n): if i in hh[k]: for j in range(1 << n): if ((1 << k) & j) == 0: nj = ((1 << k) | j) fc[nj] += fp[j] if fc[nj] >= mod: fc[nj] -= mod return fc[((1 << n) - 1)]
5d7cd8
52b39f
There are n people and 40 types of hats labeled from 1 to 40. Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: hats = [[3,4],[4,5],[5]] Output: 1 Explanation: There is only one way to choose hats given the conditions. First person choose hat 3, Second person choose hat 4 and last one hat 5. Example 2: Input: hats = [[3,5,1],[3,5]] Output: 4 Explanation: There are 4 ways to choose hats: (3,5), (5,3), (1,3) and (1,5) Example 3: Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] Output: 24 Explanation: Each person can choose hats labeled from 1 to 4. Number of Permutations of (1,2,3,4) = 24.   Constraints: n == hats.length 1 <= n <= 10 1 <= hats[i].length <= 40 1 <= hats[i][j] <= 40 hats[i] contains a list of unique integers.
class Solution(object): def numberWays(self, hats): """ :type hats: List[List[int]] :rtype: int """ n=len(hats) d,a,m=[[0]*n for _ in range(41)],[0]*(1<<n),10**9+7 a[0]=1 for i,x in enumerate(hats): for j in x: d[j][i]=1 for k in range(1,41): for i in range(len(a)-1,-1,-1): for j in range(n): if i&(1<<j) and d[k][j]: a[i]=(a[i]+a[i^(1<<j)])%m return a[-1]
1d065a
bfb7f9
The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. Given a string s, return the total appeal of all of its substrings. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abbca" Output: 28 Explanation: The following are the substrings of "abbca": - Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5. - Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7. - Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7. - Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 5: "abbca" has an appeal of 3. The sum is 3. The total sum is 5 + 7 + 7 + 6 + 3 = 28. Example 2: Input: s = "code" Output: 20 Explanation: The following are the substrings of "code": - Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4. - Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6. - Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 4: "code" has an appeal of 4. The sum is 4. The total sum is 4 + 6 + 6 + 4 = 20.   Constraints: 1 <= s.length <= 100000 s consists of lowercase English letters.
class Solution(object): def appealSum(self, s): """ :type s: str :rtype: int """ n = len(s) idx = dict() ans = 0 for i, c in enumerate(s): if c not in idx: ans += (i + 1) * (n - i) else: ans += (i - idx[c]) * (n - i) idx[c] = i return ans
57b112
bfb7f9
The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. Given a string s, return the total appeal of all of its substrings. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "abbca" Output: 28 Explanation: The following are the substrings of "abbca": - Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5. - Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7. - Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7. - Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 5: "abbca" has an appeal of 3. The sum is 3. The total sum is 5 + 7 + 7 + 6 + 3 = 28. Example 2: Input: s = "code" Output: 20 Explanation: The following are the substrings of "code": - Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4. - Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6. - Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 4: "code" has an appeal of 4. The sum is 4. The total sum is 4 + 6 + 6 + 4 = 20.   Constraints: 1 <= s.length <= 100000 s consists of lowercase English letters.
class Solution: def appealSum(self, s: str) -> int: chars = collections.defaultdict(list) N = len(s) for i, c in enumerate(s): chars[c].append(i) ret = 0 for lst in chars.values(): last = -1 ret += N * (N + 1) // 2 for i in lst: ret -= (i - last - 1) * (i - last) // 2 last = i rem = N - last - 1 ret -= rem * (rem + 1) // 2 return ret
19220d
2a3276
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.   Example 1: Input: piles = [[1,100,3],[7,8,9]], k = 2 Output: 101 Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101. Example 2: Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7 Output: 706 Explanation: The maximum total can be obtained if we choose all coins from the last pile.   Constraints: n == piles.length 1 <= n <= 1000 1 <= piles[i][j] <= 100000 1 <= k <= sum(piles[i].length) <= 2000
class Solution(object): def maxValueOfCoins(self, piles, k): """ :type piles: List[List[int]] :type k: int :rtype: int """ a, d, e, m = [[0] * (k + 1) for _ in range(len(piles))], [0] * (k + 1), [0] * (k + 1), 0 for i in range(len(piles)): s, j = 0, 0 while j < len(piles[i]) and j < k: s, a[i][j + 1], j = s + piles[i][j], s + piles[i][j], j + 1 for i in range(len(a)): j = 1 while j <= len(piles[i]) and j <= k: l = 0 while l <= m and l + j < len(d): e[l + j], l = max(e[l + j], d[l + j], a[i][j] + d[l]), l + 1 j += 1 m += len(piles[i]) for j in range(len(d)): d[j] = e[j] return d[k]
a3168e
2a3276
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.   Example 1: Input: piles = [[1,100,3],[7,8,9]], k = 2 Output: 101 Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101. Example 2: Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7 Output: 706 Explanation: The maximum total can be obtained if we choose all coins from the last pile.   Constraints: n == piles.length 1 <= n <= 1000 1 <= piles[i][j] <= 100000 1 <= k <= sum(piles[i].length) <= 2000
class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: @cache def ans(pile, rem): if rem < 0: return -inf if pile < 0: if rem == 0: return 0 return -inf res = ans(pile-1, rem) cur = 0 for i in range(len(piles[pile])): cur += piles[pile][i] res = max(res, cur+ans(pile-1, rem-i-1)) return res return ans(len(piles)-1, k)
a37155
8409f3
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Return the number of distinct islands. Example 1: Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]] Output: 1 Example 2: Input: grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 grid[i][j] is either 0 or 1.
class Solution: def numDistinctIslands(self, grid): """ :type grid: List[List[int]] :rtype: int """ if len(grid) == 0: return 0 m, n = len(grid), len(grid[0]) dx, dy = (1, -1, 0, 0), (0, 0, 1, -1) distinct_set = set() def bfs(u, v): q = [(u, v)] shape = [] for x, y in q: if grid[x][y] != 1: continue grid[x][y] = -1 shape.append((x-u, y-v)) for i in range(4): nx, ny = x + dx[i], y + dy[i] if 0<=nx<m and 0<=ny<n and grid[nx][ny]==1: q.append((nx, ny)) distinct_set.add(tuple(shape)) for i in range(m): for j in range(n): if grid[i][j] == 1: bfs(i, j) return len(distinct_set)
1007ac
8409f3
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Return the number of distinct islands. Example 1: Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]] Output: 1 Example 2: Input: grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 grid[i][j] is either 0 or 1.
class Solution(object): def numDistinctIslands(self, grid): """ :type grid: List[List[int]] :rtype: int """ ret = set() m = len(grid) if m == 0: return 0 n = len(grid[0]) for i in xrange(m): for j in xrange(n): if grid[i][j] == 1: ret.add(self.helper(grid, i, j, [(0,-1), (0,1), (-1,0), (1,0)])) return len(ret) def helper(self, grid, i, j, offsets): m = len(grid) n = len(grid[0]) q = collections.deque() q.append((i, j)) grid[i][j] = 0 ret = [] while q: x, y = q.pop() for dx, dy in offsets: xx = x + dx yy = y + dy if xx >= 0 and yy >= 0 and xx < m and yy < n and grid[xx][yy] == 1: ret.append((xx-i, yy-j)) q.append((xx,yy)) grid[xx][yy] = 0 return tuple(ret)
25a9aa
d92b7e
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: The value of the first element in arr must be 1. The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x. There are 2 types of operations that you can perform any number of times: Decrease the value of any element of arr to a smaller positive integer. Rearrange the elements of arr to be in any order. Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.   Example 1: Input: arr = [2,2,1,2,1] Output: 2 Explanation: We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. The largest element in arr is 2. Example 2: Input: arr = [100,1,1000] Output: 3 Explanation: One possible way to satisfy the conditions is by doing the following: 1. Rearrange arr so it becomes [1,100,1000]. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now arr = [1,2,3], which satisfies the conditions. The largest element in arr is 3. Example 3: Input: arr = [1,2,3,4,5] Output: 5 Explanation: The array already satisfies the conditions, and the largest element is 5.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i] <= 10^9
class Solution: def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: arr.sort() N = len(arr) arr[0] = 1 for index in range(1, N): arr[index] = min(arr[index - 1] + 1, arr[index]) return arr[-1]
66b0f9
d92b7e
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: The value of the first element in arr must be 1. The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x. There are 2 types of operations that you can perform any number of times: Decrease the value of any element of arr to a smaller positive integer. Rearrange the elements of arr to be in any order. Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.   Example 1: Input: arr = [2,2,1,2,1] Output: 2 Explanation: We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. The largest element in arr is 2. Example 2: Input: arr = [100,1,1000] Output: 3 Explanation: One possible way to satisfy the conditions is by doing the following: 1. Rearrange arr so it becomes [1,100,1000]. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now arr = [1,2,3], which satisfies the conditions. The largest element in arr is 3. Example 3: Input: arr = [1,2,3,4,5] Output: 5 Explanation: The array already satisfies the conditions, and the largest element is 5.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i] <= 10^9
class Solution(object): def maximumElementAfterDecrementingAndRearranging(self, arr): """ :type arr: List[int] :rtype: int """ arr.sort() for i in range(len(arr)): if i==0: arr[i]=1 else: arr[i] = min(arr[i-1]+1,arr[i]) return arr[-1] # left = len(arr) # right = max(arr)+1 # while left<right: # mid = left+(right-left)//2
062c5c
6e0dbe
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons.   Example 1: Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. Example 2: Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4 Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. Example 3: Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].   Constraints: 1 <= points.length <= 100000 points[i].length == 2 -2^31 <= xstart < xend <= 2^31 - 1
class Solution(object): def findMinArrowShots(self, points): """ :type points: List[List[int]] :rtype: int """ if len(points)==0: return 0 points.sort(key = lambda x: x[1]) ans=0 a=0 b=0 while True: if a == len(points) or points[a][0] > points[b][1]: b=a ans+=1 if a == len(points): break a+=1 return ans
e62cc1
a4ded6
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...]. Given an integer n, return the nth (1-indexed) integer in the new sequence. Example 1: Input: n = 9 Output: 10 Example 2: Input: n = 10 Output: 11 Constraints: 1 <= n <= 8 * 10^8
class Solution(object): def newInteger(self, n): """ :type n: int :rtype: int """ a = [] while n > 0: a.append(n % 9) n /= 9 r = 0 for x in a[::-1]: r = r * 10 + x return r
c06688
a4ded6
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...]. Given an integer n, return the nth (1-indexed) integer in the new sequence. Example 1: Input: n = 9 Output: 10 Example 2: Input: n = 10 Output: 11 Constraints: 1 <= n <= 8 * 10^8
class Solution: def newInteger(self, n): """ :type n: int :rtype: int """ s = '' while n >= 9: s += str(n % 9) n //= 9 s += str(n) return int(''.join(reversed(s)))
02b249
14b69b
You are given a string s consisting of digits from 1 to 9 and an integer k. A partition of a string s is called good if: Each digit of s is part of exactly one substring. The value of each substring is less than or equal to k. Return the minimum number of substrings in a good partition of s. If no good partition of s exists, return -1. Note that: The value of a string is its result when interpreted as an integer. For example, the value of "123" is 123 and the value of "1" is 1. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "165462", k = 60 Output: 4 Explanation: We can partition the string into substrings "16", "54", "6", and "2". Each substring has a value less than or equal to k = 60. It can be shown that we cannot partition the string into less than 4 substrings. Example 2: Input: s = "238182", k = 5 Output: -1 Explanation: There is no good partition for this string.   Constraints: 1 <= s.length <= 100000 s[i] is a digit from '1' to '9'. 1 <= k <= 10^9  
class Solution: def minimumPartition(self, s: str, k: int) -> int: ans = 0 pre = "" for w in s: if int(pre+w) <= k: pre += w else: if not pre: return -1 if int(pre) <= k: ans += 1 else: return -1 pre = w if pre: if int(pre) <= k: ans += 1 else: return -1 return ans
84da48
14b69b
You are given a string s consisting of digits from 1 to 9 and an integer k. A partition of a string s is called good if: Each digit of s is part of exactly one substring. The value of each substring is less than or equal to k. Return the minimum number of substrings in a good partition of s. If no good partition of s exists, return -1. Note that: The value of a string is its result when interpreted as an integer. For example, the value of "123" is 123 and the value of "1" is 1. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "165462", k = 60 Output: 4 Explanation: We can partition the string into substrings "16", "54", "6", and "2". Each substring has a value less than or equal to k = 60. It can be shown that we cannot partition the string into less than 4 substrings. Example 2: Input: s = "238182", k = 5 Output: -1 Explanation: There is no good partition for this string.   Constraints: 1 <= s.length <= 100000 s[i] is a digit from '1' to '9'. 1 <= k <= 10^9  
class Solution(object): def minimumPartition(self, s, k): """ :type s: str :type k: int :rtype: int """ c, p = 0, 0 for i in range(len(s)): if int(s[i]) > k: return -1 p = p * 10 + int(s[i]) if p > k: c, p = c + 1, int(s[i]) return c + 1
ec2f88
201eb3
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score.   Example 1: Input: parents = [-1,2,0,2,0] Output: 3 Explanation: - The score of node 0 is: 3 * 1 = 3 - The score of node 1 is: 4 = 4 - The score of node 2 is: 1 * 1 * 2 = 2 - The score of node 3 is: 4 = 4 - The score of node 4 is: 4 = 4 The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score. Example 2: Input: parents = [-1,2,0] Output: 2 Explanation: - The score of node 0 is: 2 = 2 - The score of node 1 is: 2 = 2 - The score of node 2 is: 1 * 1 = 1 The highest score is 2, and two nodes (node 0 and node 1) have the highest score.   Constraints: n == parents.length 2 <= n <= 100000 parents[0] == -1 0 <= parents[i] <= n - 1 for i != 0 parents represents a valid binary tree.
class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: setrecursionlimit(1000000) self.best = -1 self.res = 0 n = len(parents) edges = [[] for i in range(n)] sz = [1]*n for i in range(1, n): edges[parents[i]].append(i) def dfs(x): cur = 1 for i in edges[x]: dfs(i) sz[x] += sz[i] cur *= sz[i] if x: cur *= n-sz[x] if cur > self.best: self.best = cur self.res = 1 elif cur == self.best: self.res += 1 dfs(0) return self.res
3bf145
201eb3
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score.   Example 1: Input: parents = [-1,2,0,2,0] Output: 3 Explanation: - The score of node 0 is: 3 * 1 = 3 - The score of node 1 is: 4 = 4 - The score of node 2 is: 1 * 1 * 2 = 2 - The score of node 3 is: 4 = 4 - The score of node 4 is: 4 = 4 The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score. Example 2: Input: parents = [-1,2,0] Output: 2 Explanation: - The score of node 0 is: 2 = 2 - The score of node 1 is: 2 = 2 - The score of node 2 is: 1 * 1 = 1 The highest score is 2, and two nodes (node 0 and node 1) have the highest score.   Constraints: n == parents.length 2 <= n <= 100000 parents[0] == -1 0 <= parents[i] <= n - 1 for i != 0 parents represents a valid binary tree.
class Solution(object): def countHighestScoreNodes(self, parents): """ :type parents: List[int] :rtype: int """ nei = {} n = len(parents) cs = [0]*n for i in range(1, n): p = parents[i] if p not in nei: nei[p]=set() nei[p].add(i) def count(r): c=1 if r in nei: for b in nei[r]: c+=count(b) cs[r]=c return c m = count(0) vs = [0]*n rv = [0] def dfs(r): v1 = m-cs[r] if v1==0: v1=1 if r in nei: for b in nei[r]: dfs(b) v1*=cs[b] if rv[0]<v1: rv[0]=v1 vs[r]=v1 # print r, v1 dfs(0) rc =0 for i in range(n): if vs[i]==rv[0]: rc+=1 return rc
e2e0de
c5e3f6
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: arr = ["un","iq","ue"] Output: 4 Explanation: All the valid concatenations are: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") Maximum length is 4. Example 2: Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). Example 3: Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26 Explanation: The only string in arr has all 26 characters.   Constraints: 1 <= arr.length <= 16 1 <= arr[i].length <= 26 arr[i] contains only lowercase English letters.
class Solution(object): def maxLength(self, A): for i in xrange(len(A) - 1, -1, -1): if len(set(A[i])) != len(A[i]): A.pop(i) N = len(A) B = [] for word in A: ct = [0] * 26 for letter in word: ct[ord(letter) - ord('a')] += 1 B.append(ct) self.ans = 0 count = [0] * 26 def search(i): if i == N: cand = sum(count) if cand > self.ans: self.ans = cand return for letter, ct in enumerate(B[i]): if ct and count[letter]: search(i+1) break else: search(i+1) for letter, ct in enumerate(B[i]): if ct: count[letter] += 1 search(i+1) for letter, ct in enumerate(B[i]): if ct: count[letter] -= 1 search(0) return self.ans
418c4e
c5e3f6
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.   Example 1: Input: arr = ["un","iq","ue"] Output: 4 Explanation: All the valid concatenations are: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") Maximum length is 4. Example 2: Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). Example 3: Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26 Explanation: The only string in arr has all 26 characters.   Constraints: 1 <= arr.length <= 16 1 <= arr[i].length <= 26 arr[i] contains only lowercase English letters.
from collections import Counter class Solution: def sToNum(self, s): ans = 0 for c in s: ans |= 1<<(ord(c) - ord("a")) return ans def count(self, num): ans = 0 while num: num -= num&(-num) ans += 1 return ans def maxLength(self, A): A = [word for word in A if len(word) == len(set(word))] sA = [self.sToNum(word) for word in A] aSet = set([0]) for word in sA: newS = set(aSet) for s in aSet: if not (s & word): newS.add(s | word) aSet = newS # print (aSet) return max(self.count(word) for word in aSet) # cA = [Counter(word) for word in A] # l = 0 # r = 0 # cur = Counter("") # curLen = 0 # ans = 0 # while True: # print (l, r, curLen) # if not cur.values() or max(cur.values()) <= 1: # ans = max(ans, curLen) # if r == len(A): # break # cur += cA[r] # curLen += len(A[r]) # r += 1 # else: # if l == len(A): # break # cur -= cA[l] # curLen -= len(A[l]) # l += 1 # return ans
3e678f
059f92
Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones. Return the maximum possible number of ones that the matrix M can have. Example 1: Input: width = 3, height = 3, sideLength = 2, maxOnes = 1 Output: 4 Explanation: In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. The best solution that has 4 ones is: [1,0,1] [0,0,0] [1,0,1] Example 2: Input: width = 3, height = 3, sideLength = 2, maxOnes = 2 Output: 6 Explanation: [1,0,1] [1,0,1] [1,0,1] Constraints: 1 <= width, height <= 100 1 <= sideLength <= width, height 0 <= maxOnes <= sideLength * sideLength
class Solution(object): def maximumNumberOfOnes(self, C, R, K, maxOnes): # every K*K square has at most maxOnes ones count = [0] * (K*K) for r in xrange(R): for c in xrange(C): code = (r%K) * K + c%K count[code] += 1 count.sort() ans = 0 for _ in xrange(maxOnes): ans += count.pop() return ans
8c8051
059f92
Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones. Return the maximum possible number of ones that the matrix M can have. Example 1: Input: width = 3, height = 3, sideLength = 2, maxOnes = 1 Output: 4 Explanation: In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. The best solution that has 4 ones is: [1,0,1] [0,0,0] [1,0,1] Example 2: Input: width = 3, height = 3, sideLength = 2, maxOnes = 2 Output: 6 Explanation: [1,0,1] [1,0,1] [1,0,1] Constraints: 1 <= width, height <= 100 1 <= sideLength <= width, height 0 <= maxOnes <= sideLength * sideLength
class Solution: def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int: k1, p = width // sideLength, width % sideLength k2, q = height // sideLength, height % sideLength occ = list() for i in range(sideLength): for j in range(sideLength): if i < p and j < q: occ.append(k1 + k2 + 1) elif i < p: occ.append(k2) elif j < q: occ.append(k1) occ.sort(reverse=True) extra = sum(occ[:maxOnes] if len(occ) >= maxOnes else occ) return k1 * k2 * maxOnes + extra
b3f846
578915
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. Return the list answer. If there multiple valid answers, return any of them.   Example 1: Input: n = 3, k = 1 Output: [1,2,3] Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1 Example 2: Input: n = 3, k = 2 Output: [1,3,2] Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.   Constraints: 1 <= k < n <= 10000
class Solution(object): def constructArray(self, n, k): cur = 1 ans = [] while n > k + cur: ans.append(cur) cur += 1 rem = collections.deque(range(cur, n+1)) d=1 while rem: if d: ans.append(rem.popleft()) else: ans.append(rem.pop()) d ^=1 return ans
a67ee6
578915
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. Return the list answer. If there multiple valid answers, return any of them.   Example 1: Input: n = 3, k = 1 Output: [1,2,3] Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1 Example 2: Input: n = 3, k = 2 Output: [1,3,2] Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.   Constraints: 1 <= k < n <= 10000
class Solution: def constructArray(self, n, k): """ :type n: int :type k: int :rtype: List[int] """ result = [i+1 for i in range(n)] for i in range(k+1): # result[k] = k+1 if (k-i)%2 == 0: result[i] = (k + i + 2)//2 else: result[i] = (k + 1 - i)//2 return result
e63d4c
bd582e
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer gets exactly quantity[i] integers, The integers the ith customer gets are all equal, and Every customer is satisfied. Return true if it is possible to distribute nums according to the above conditions.   Example 1: Input: nums = [1,2,3,4], quantity = [2] Output: false Explanation: The 0th customer cannot be given two different integers. Example 2: Input: nums = [1,2,3,3], quantity = [2] Output: true Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. Example 3: Input: nums = [1,1,2,2], quantity = [2,2] Output: true Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].   Constraints: n == nums.length 1 <= n <= 100000 1 <= nums[i] <= 1000 m == quantity.length 1 <= m <= 10 1 <= quantity[i] <= 100000 There are at most 50 unique values in nums.
class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: c = collections.Counter(nums) cv = list(c.values()) M = len(cv) N = len(quantity) cache = [0] * (1 << N) for i in range(1 << N): for j in range(N): if ((1 << j) & (i)) > 0: cache[i] += quantity[j] @lru_cache(None) def go(index, mask): if mask == 0: return True if index == M: return False i = mask while i > 0: total = cache[i] if total <= cv[index] and go(index + 1, mask ^ i): return True i = (i - 1) & mask return go(index + 1, mask) return go(0, (1 << N) - 1)
3b8e16
bd582e
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer gets exactly quantity[i] integers, The integers the ith customer gets are all equal, and Every customer is satisfied. Return true if it is possible to distribute nums according to the above conditions.   Example 1: Input: nums = [1,2,3,4], quantity = [2] Output: false Explanation: The 0th customer cannot be given two different integers. Example 2: Input: nums = [1,2,3,3], quantity = [2] Output: true Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. Example 3: Input: nums = [1,1,2,2], quantity = [2,2] Output: true Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].   Constraints: n == nums.length 1 <= n <= 100000 1 <= nums[i] <= 1000 m == quantity.length 1 <= m <= 10 1 <= quantity[i] <= 100000 There are at most 50 unique values in nums.
class Solution(object): def canDistribute(self, nums, quantity): """ :type nums: List[int] :type quantity: List[int] :rtype: bool """ cs = {} for v in nums: if v not in cs: cs[v]=0 cs[v]+=1 vcs = [] for v in cs: vcs.append(cs[v]) n = len(vcs) m = len(quantity) mm = 1<<m ss = [0]*mm qs = quantity dp = {} for s in range(mm): cc = 0 for i in range(m): if s&(1<<i): cc+=qs[i] ss[s]=cc # print ss, vcs def dfs(i, s): if s==0: return True if i>=n: return False k = (i, s) if k in dp: return dp[k] r = dfs(i+1, s) ns=0 while True: ns = (ns-s)&s if ns==0: break if ss[ns]<=vcs[i] and dfs(i+1, s&(~ns)): r = True break dp[k]=r return r return dfs(0, mm-1)
28b7a4
7bc8ea
Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.  For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.   Example 1: Input: pizza = ["A..","AAA","..."], k = 3 Output: 3 Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. Example 2: Input: pizza = ["A..","AA.","..."], k = 3 Output: 1 Example 3: Input: pizza = ["A..","A..","..."], k = 1 Output: 1   Constraints: 1 <= rows, cols <= 50 rows == pizza.length cols == pizza[i].length 1 <= k <= 10 pizza consists of characters 'A' and '.' only.
class Solution(object): def ways(self, pizza, k): """ :type pizza: List[str] :type k: int :rtype: int """ M = 10**9 + 7 n, m = len(pizza), len(pizza[0]) s = [[0]*(m+1) for _ in xrange(n+1)] for i in xrange(n): for j in xrange(m): s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] if pizza[i][j] == 'A': s[i+1][j+1] += 1 def has_apple(i0, j0, i1, j1): return s[i1][j1] + s[i0][j0] > s[i0][j1] + s[i1][j0] w = [[0]*(m+1) for _ in xrange(n+1)] for i in xrange(n): for j in xrange(m): if has_apple(i, j, n, m): w[i][j] = 1 for _ in xrange(k-1): for i in xrange(n): for j in xrange(m): t = 0 for ii in xrange(i+1, n): if not has_apple(i, j, ii, m): continue t += w[ii][j] for jj in xrange(j+1, m): if not has_apple(i, j, n, jj): continue t += w[i][jj] w[i][j] = t % M return w[0][0]
ad275c
7bc8ea
Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.  For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.   Example 1: Input: pizza = ["A..","AAA","..."], k = 3 Output: 3 Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. Example 2: Input: pizza = ["A..","AA.","..."], k = 3 Output: 1 Example 3: Input: pizza = ["A..","A..","..."], k = 1 Output: 1   Constraints: 1 <= rows, cols <= 50 rows == pizza.length cols == pizza[i].length 1 <= k <= 10 pizza consists of characters 'A' and '.' only.
class Solution: def ways(self, pizza: List[str], k: int) -> int: r = len(pizza) c = len(pizza[0]) mod = 1000000007 ss = [[0 for i in range(c+2)] for j in range(r+2)] for i in range(r): for j in range(c): ss[i+1][j+1] = int(pizza[i][j]=='A') + ss[i][j+1] + ss[i+1][j] - ss[i][j] def valid(i,j,k,m): return ss[k][m] - ss[i-1][m] - ss[k][j-1] + ss[i-1][j-1] > 0 dp = [[0 for i in range(c+2)] for j in range(r+2)] dp[1][1] = 1 for ___ in range(k-1): ndp = [[0 for i in range(c+2)] for j in range(r+2)] for i in range(1,r+1): for j in range(1,c+1): if dp[i][j] == 0: continue for k in range(i+1,r+1): if valid(i,j,k-1,c): ndp[k][j] += dp[i][j] if ndp[k][j] >= mod: ndp[k][j] -= mod for k in range(j+1,c+1): if valid(i,j,r,k-1): ndp[i][k] += dp[i][j] if ndp[i][k] >= mod: ndp[i][k] -= mod dp = ndp res = 0 for i in range(1,r+1): for j in range(1,c+1): if valid(i,j,r,c): res = (res + dp[i][j]) % mod return res
089a56
54218b
Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: FrontMiddleBack() Initializes the queue. void pushFront(int val) Adds val to the front of the queue. void pushMiddle(int val) Adds val to the middle of the queue. void pushBack(int val) Adds val to the back of the queue. int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1. int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1. int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1. Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].   Example 1: Input: ["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] [[], [1], [2], [3], [4], [], [], [], [], []] Output: [null, null, null, null, null, 1, 3, 4, 2, -1] Explanation: FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // [1] q.pushBack(2); // [1, 2] q.pushMiddle(3); // [1, 3, 2] q.pushMiddle(4); // [1, 4, 3, 2] q.popFront(); // return 1 -> [4, 3, 2] q.popMiddle(); // return 3 -> [4, 2] q.popMiddle(); // return 4 -> [2] q.popBack(); // return 2 -> [] q.popFront(); // return -1 -> [] (The queue is empty)   Constraints: 1 <= val <= 10^9 At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack.
class FrontMiddleBackQueue(object): def __init__(self): self.A = [] def pushFront(self, val): """ :type val: int :rtype: None """ self.A.insert(0, val) def pushMiddle(self, val): """ :type val: int :rtype: None """ self.A.insert(len(self.A)/2, val) def pushBack(self, val): """ :type val: int :rtype: None """ self.A.append(val) def popFront(self): """ :rtype: int """ return self.A.pop(0) if self.A else -1 def popMiddle(self): """ :rtype: int """ return self.A.pop((len(self.A)-1)/2) if self.A else -1 def popBack(self): """ :rtype: int """ return self.A.pop() if self.A else -1 # Your FrontMiddleBackQueue object will be instantiated and called as such: # obj = FrontMiddleBackQueue() # obj.pushFront(val) # obj.pushMiddle(val) # obj.pushBack(val) # param_4 = obj.popFront() # param_5 = obj.popMiddle() # param_6 = obj.popBack()
5d3edd
54218b
Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: FrontMiddleBack() Initializes the queue. void pushFront(int val) Adds val to the front of the queue. void pushMiddle(int val) Adds val to the middle of the queue. void pushBack(int val) Adds val to the back of the queue. int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1. int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1. int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1. Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].   Example 1: Input: ["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] [[], [1], [2], [3], [4], [], [], [], [], []] Output: [null, null, null, null, null, 1, 3, 4, 2, -1] Explanation: FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // [1] q.pushBack(2); // [1, 2] q.pushMiddle(3); // [1, 3, 2] q.pushMiddle(4); // [1, 4, 3, 2] q.popFront(); // return 1 -> [4, 3, 2] q.popMiddle(); // return 3 -> [4, 2] q.popMiddle(); // return 4 -> [2] q.popBack(); // return 2 -> [] q.popFront(); // return -1 -> [] (The queue is empty)   Constraints: 1 <= val <= 10^9 At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack.
class FrontMiddleBackQueue: def __init__(self): self.q = list() def pushFront(self, val: int) -> None: self.q[0:0] = [val] def pushMiddle(self, val: int) -> None: l = len(self.q) // 2 self.q[l:l] = [val] def pushBack(self, val: int) -> None: self.q.append(val) def popFront(self) -> int: if not self.q: return -1 # print(self.q) ret = self.q[0] self.q[0:1] = [] return ret def popMiddle(self) -> int: if not self.q: return -1 # print(self.q) l = (len(self.q) - 1) // 2 ret = self.q[l] self.q[l:l+1] = [] return ret def popBack(self) -> int: if not self.q: return -1 # print(self.q) return self.q.pop() # Your FrontMiddleBackQueue object will be instantiated and called as such: # obj = FrontMiddleBackQueue() # obj.pushFront(val) # obj.pushMiddle(val) # obj.pushBack(val) # param_4 = obj.popFront() # param_5 = obj.popMiddle() # param_6 = obj.popBack()
891715
bb6e65
You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary.   Example 1: Input: nums = [1,2,4,3], limit = 4 Output: 1 Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed). nums[0] + nums[3] = 1 + 3 = 4. nums[1] + nums[2] = 2 + 2 = 4. nums[2] + nums[1] = 2 + 2 = 4. nums[3] + nums[0] = 3 + 1 = 4. Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. Example 2: Input: nums = [1,2,2,1], limit = 2 Output: 2 Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit. Example 3: Input: nums = [1,2,1,2], limit = 2 Output: 0 Explanation: nums is already complementary.   Constraints: n == nums.length 2 <= n <= 100000 1 <= nums[i] <= limit <= 100000 n is even.
class Solution(object): def minMoves(self, A, limit): N = len(A) events = [0] * (2 * limit + 3) def add(lo,hi,v): events[lo] += v events[hi+1] -= v for i in xrange(N // 2): x = A[i] y = A[~i] if x > y: x,y=y,x s = x+y lo = x + 1 hi = y + limit add(0, 2 * limit + 1, 2) add(x + 1, y + limit, -1) add(s, s, -1) #print("after", events, x, y) #B = events[:] #for i in xrange(1, len(events)): # B[i] += B[i - 1] #print("and", B) for i in xrange(1, len(events)): events[i] += events[i - 1] events.pop() return min(events)
735d6a
bb6e65
You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary.   Example 1: Input: nums = [1,2,4,3], limit = 4 Output: 1 Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed). nums[0] + nums[3] = 1 + 3 = 4. nums[1] + nums[2] = 2 + 2 = 4. nums[2] + nums[1] = 2 + 2 = 4. nums[3] + nums[0] = 3 + 1 = 4. Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. Example 2: Input: nums = [1,2,2,1], limit = 2 Output: 2 Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit. Example 3: Input: nums = [1,2,1,2], limit = 2 Output: 0 Explanation: nums is already complementary.   Constraints: n == nums.length 2 <= n <= 100000 1 <= nums[i] <= limit <= 100000 n is even.
class Solution: def minMoves(self, nums: List[int], limit: int) -> int: q = deque(nums) l = [0] * (3 * 10**5) while q: a = q.popleft() b = q.pop() a, b = sorted([a, b]) l[2] += 2 l[a+1] -= 1 l[a+b] -= 1 l[a+b+1] += 1 l[limit+b+1] += 1 cnt = 0 ans = inf for i in range(2, 2*limit + 1): cnt += l[i] ans = min(ans, cnt) return ans
ead84e
ce7a05
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}.  Notice that "tars" and "arts" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?   Example 1: Input: strs = ["tars","rats","arts","star"] Output: 2 Example 2: Input: strs = ["omv","ovm"] Output: 1   Constraints: 1 <= strs.length <= 300 1 <= strs[i].length <= 300 strs[i] consists of lowercase letters only. All words in strs have the same length and are anagrams of each other.
class Solution(object): def numSimilarGroups(self, A): n = len(A) m = len(A[1]) collect = dict() graph = [set() for i in range(n)] def similar(s1, s2): i, j = -1, -1 for k in range(len(s1)): if s1[k] != s2[k]: if i == -1: i = k elif j == -1: j = k if s1[i] != s2[j] or s1[j] != s2[i]: return False else: return False return True for i in range(n): for j in range(i + 1, n): if similar(A[i], A[j]): graph[i].add(j) graph[j].add(i) visited = [0] * n res = 0 def dfs(i, visited, n, graph): if visited[i]: return visited[i] = 1 for j in graph[i]: dfs(j, visited, n, graph) return for i in range(n): if not visited[i]: res += 1 dfs(i, visited, n, graph) return res """ :type A: List[str] :rtype: int """
d0b60c
ce7a05
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}.  Notice that "tars" and "arts" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?   Example 1: Input: strs = ["tars","rats","arts","star"] Output: 2 Example 2: Input: strs = ["omv","ovm"] Output: 1   Constraints: 1 <= strs.length <= 300 1 <= strs[i].length <= 300 strs[i] consists of lowercase letters only. All words in strs have the same length and are anagrams of each other.
class WeightedQuickUnionUF: def __init__(self, n): self.count = n self.uid = [i for i in range(n)] self.sz = [1] * n def connected(self, p, q): return self.find(p) == self.find(q) def find(self, p): while p != self.uid[p]: p = self.uid[p] return p def union(self, p, q): i = self.find(p) j = self.find(q) if i == j: return if self.sz[i] < self.sz[j]: self.uid[i] = j self.sz[j] += self.sz[i] else: self.uid[j] = i self.sz[i] += self.sz[j] self.count -= 1 class Solution: def numSimilarGroups(self, A): """ :type A: List[str] :rtype: int """ uf = WeightedQuickUnionUF(len(A)) for i in range(len(A)): for j in range(i+1, len(A)): if self.isSimilar(A[i], A[j]): uf.union(i, j) return uf.count def isSimilar(self, a, b): i = 0 j = len(a) - 1 while i < len(a): if a[i] != b[i]: break i += 1 while j >= i: if a[j] != b[j]: break j -= 1 return a[i] == b[j] and a[j] == b[i] and a[i+1:j] == b[i+1:j]
af9fef
994c11
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.   Example 1: Input: n = 5 Output: 2 Explanation: 5 = 2 + 3 Example 2: Input: n = 9 Output: 3 Explanation: 9 = 4 + 5 = 2 + 3 + 4 Example 3: Input: n = 15 Output: 4 Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5   Constraints: 1 <= n <= 10^9
class Solution(object): def consecutiveNumbersSum(self, N): """ :type N: int :rtype: int """ base=0 res=0 dup=1 while dup+base<=N: if (N-base)%dup==0: res+=1 base+=dup dup+=1 return res
a8d57b
994c11
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.   Example 1: Input: n = 5 Output: 2 Explanation: 5 = 2 + 3 Example 2: Input: n = 9 Output: 3 Explanation: 9 = 4 + 5 = 2 + 3 + 4 Example 3: Input: n = 15 Output: 4 Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5   Constraints: 1 <= n <= 10^9
from math import * class Solution: def consecutiveNumbersSum(self, N): """ :type N: int :rtype: int """ ans=0 for i in range(1,ceil(sqrt(2*N))): if i%2 and N%i==0 or i%2==0 and (N-i//2)%i==0: ans+=1 return ans
43a84c
f4c1c8
You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the element is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4]. The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations.   Example 1: Input: nums = [1,2,3,4] Output: 1 Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. Example 2: Input: nums = [4,1,5,20,3] Output: 3 Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. Example 3: Input: nums = [2,10,8] Output: 3   Constraints: n == nums.length 2 <= n <= 5 * 10000 1 <= nums[i] <= 10^9
class Solution(object): def minimumDeviation(self, A): A.sort() from heapq import heappop,heappush, heapify pq = [] for x in A: if x % 2: x *= 2 pq.append(-x) heapify(pq) m = -max(pq) ans = float('inf') while True: x = -heappop(pq) cand = x-m if cand<ans:ans=cand if x & 1: break x >>= 1 if x < m: m = x # print("!", max(-x for x in pq), m) heappush(pq, -x) return ans
5640e7
f4c1c8
You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the element is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4]. The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations.   Example 1: Input: nums = [1,2,3,4] Output: 1 Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. Example 2: Input: nums = [4,1,5,20,3] Output: 3 Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. Example 3: Input: nums = [2,10,8] Output: 3   Constraints: n == nums.length 2 <= n <= 5 * 10000 1 <= nums[i] <= 10^9
from sortedcontainers import SortedList class Solution: def minimumDeviation(self, nums: List[int]) -> int: sl = SortedList(a*2 if a & 1 else a for a in nums) ans = sl[-1] - sl[0] while sl[-1] % 2 == 0: sl.add(sl.pop() // 2) ans = min(ans, sl[-1] - sl[0]) return ans
c2d8f7
2319a6
A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurrences of the letter 'c'. Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". A substring is a contiguous sequence of characters within a string.   Example 1: Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer. Example 2: Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case.   Constraints: 0 <= a, b, c <= 100 a + b + c > 0
class Solution(object): def longestDiverseString(self, a, b, c): A = [[a, 'a'], [b, 'b'], [c, 'c']] ans = [] for _ in xrange(a+b+c): A.sort(reverse=True) for i in xrange(3): x = A[i][0] c = A[i][1] if x == 0: continue if len(ans) < 2 or not(ans[-1] == ans[-2] == c): ans.append(c) A[i][0] -= 1 break else: break return "".join(ans)
42a963
2319a6
A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurrences of the letter 'c'. Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". A substring is a contiguous sequence of characters within a string.   Example 1: Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer. Example 2: Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case.   Constraints: 0 <= a, b, c <= 100 a + b + c > 0
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: ans=[] def canAdd(x): return len(ans)<2 or ans[-1]!=x or ans[-2] != x d=[[a,"a"],[b,"b"], [c, "c"]] total=a+b+c while total>0: d.sort(reverse=True) for i, (k, c) in enumerate(d): if k==0: continue if canAdd(c): ans.append(c) d[i][0]-=1 total-=1 break else: break return "".join(ans)
45db3a
a247d3
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.   Example 1: Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. Example 2: Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] Output: 10   Constraints: m == heightMap.length n == heightMap[i].length 1 <= m, n <= 200 0 <= heightMap[i][j] <= 2 * 10000
class Solution(object): def trapRainWater(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ if len(heightMap) == 0 or len(heightMap[0]) == 0: return 0 y, x = len(heightMap), len(heightMap[0]) queue = ( [(0, i) for i in range(y)] + [(x - 1, i) for i in range(y)] + [(i, 0) for i in range(x)] + [(i, y - 1) for i in range(x)] ) level = [[1000000] * x for i in range(y)] for i in range(x): for j in range(y): if (i, j) in queue: level[j][i] = heightMap[j][i] while len(queue): i, j = queue.pop(0) if i > 0: n = max(heightMap[j][i - 1], min(level[j][i - 1], level[j][i])) if level[j][i - 1] != n: level[j][i - 1] = n queue.append((i - 1, j)) if i < x - 1: n = max(heightMap[j][i + 1], min(level[j][i + 1], level[j][i])) if level[j][i + 1] != n: level[j][i + 1] = n queue.append((i + 1, j)) if j > 0: n = max(heightMap[j - 1][i], min(level[j - 1][i], level[j][i])) if level[j - 1][i] != n: level[j - 1][i] = n queue.append((i, j - 1)) if j < y - 1: n = max(heightMap[j + 1][i], min(level[j + 1][i], level[j][i])) if level[j + 1][i] != n: level[j + 1][i] = n queue.append((i, j + 1)) result = 0 for i in range(x): for j in range(y): result += level[j][i] - heightMap[j][i] return result
cd60a9
dae878
There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip. For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time. Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.   Example 1: Input: n = 5, rides = [[2,5,4],[1,5,1]] Output: 7 Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars. Example 2: Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]] Output: 20 Explanation: We will pick up the following passengers: - Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars. - Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars. - Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars. We earn 9 + 5 + 6 = 20 dollars in total.   Constraints: 1 <= n <= 100000 1 <= rides.length <= 3 * 10000 rides[i].length == 3 1 <= starti < endi <= n 1 <= tipi <= 100000
from collections import defaultdict from functools import lru_cache from typing import List class Solution: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: memo = defaultdict(list) for start, end, tip in rides: memo[start].append((end, tip)) @lru_cache(None) def helper(idx): if idx == n: return 0 ans = helper(idx + 1) for end, tip in memo[idx]: ans = max(ans, end - idx + tip + helper(end)) return ans return helper(1)
083e4c
dae878
There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip. For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time. Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.   Example 1: Input: n = 5, rides = [[2,5,4],[1,5,1]] Output: 7 Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars. Example 2: Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]] Output: 20 Explanation: We will pick up the following passengers: - Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars. - Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars. - Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars. We earn 9 + 5 + 6 = 20 dollars in total.   Constraints: 1 <= n <= 100000 1 <= rides.length <= 3 * 10000 rides[i].length == 3 1 <= starti < endi <= n 1 <= tipi <= 100000
class Solution(object): def maxTaxiEarnings(self, n, rides): """ :type n: int :type rides: List[List[int]] :rtype: int """ nei={} for s, e, t in rides: if s not in nei: nei[s]=[] nei[s].append((e, e-s+t)) dp = [0]*(n+2) i=n while i>0: dp[i]=dp[i+1] if i in nei: for e, c in nei[i]: t=c+dp[e] if t>dp[i]: dp[i]=t i-=1 return dp[1]
cca98b
167075
You are given an m x n integer matrix grid and an array queries of size k. Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process: If queries[i] is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4 directions: up, down, left, and right. Otherwise, you do not get any points, and you end this process. After the process, answer[i] is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times. Return the resulting array answer.   Example 1: Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2] Output: [5,8,1] Explanation: The diagrams above show which cells we visit to get points for each query. Example 2: Input: grid = [[5,2,1],[1,1,2]], queries = [3] Output: [0] Explanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.   Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= 100000 k == queries.length 1 <= k <= 10000 1 <= grid[i][j], queries[i] <= 1000000
# 标准并查集 class UnionFind: def __init__(self, n): self.root = [i for i in range(n)] self.size = [1] * n self.part = n def find(self, x): if x != self.root[x]: # 在查询的时候合并到顺带直接根节点 root_x = self.find(self.root[x]) self.root[x] = root_x return root_x return x def union(self, x, y): root_x = self.find(x) root_y = self.find(y) if root_x == root_y: return False if self.size[root_x] >= self.size[root_y]: root_x, root_y = root_y, root_x self.root[root_x] = root_y self.size[root_y] += self.size[root_x] # 将非根节点的秩赋0 self.size[root_x] = 0 self.part -= 1 return True def is_connected(self, x, y): return self.find(x) == self.find(y) def get_root_part(self): # 获取每个根节点对应的组 part = defaultdict(list) n = len(self.root) for i in range(n): part[self.find(i)].append(i) return part def get_root_size(self): # 获取每个根节点对应的组大小 size = defaultdict(int) n = len(self.root) for i in range(n): size[self.find(i)] = self.size[self.find(i)] return size class Solution: def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: k = len(queries) ind = list(range(k)) ind.sort(key=lambda x: queries[x]) dct = [] m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if i+1<m: dct.append([i*n+j,i*n+n+j, max(grid[i][j], grid[i+1][j])]) if j+1<n: dct.append([i * n + j, i * n + 1 + j, max(grid[i][j], grid[i][j+1])]) dct.sort(key=lambda x: x[2]) uf = UnionFind(m*n) ans = [] j = 0 length = len(dct) for i in ind: cur = queries[i] while j<length and dct[j][2] < cur: uf.union(dct[j][0], dct[j][1]) j += 1 if cur > grid[0][0]: ans.append([i,uf.size[uf.find(0)]]) else: ans.append([i, 0]) ans.sort(key=lambda x: x[0]) return [a[1] for a in ans]
608ea4
167075
You are given an m x n integer matrix grid and an array queries of size k. Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process: If queries[i] is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4 directions: up, down, left, and right. Otherwise, you do not get any points, and you end this process. After the process, answer[i] is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times. Return the resulting array answer.   Example 1: Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2] Output: [5,8,1] Explanation: The diagrams above show which cells we visit to get points for each query. Example 2: Input: grid = [[5,2,1],[1,1,2]], queries = [3] Output: [0] Explanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.   Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= 100000 k == queries.length 1 <= k <= 10000 1 <= grid[i][j], queries[i] <= 1000000
class DisjointSetUnion: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] return a def union(self, a, b): a, b = self.find(a), self.find(b) if a != b: if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets class Solution(object): def maxPoints(self, grid, queries): m = len(grid) n = len(grid[0]) pts = [] for i in range(m): for j in range(n): pts.append((grid[i][j], i, j)) pts.sort(key = lambda x: -x[0]) UF = DisjointSetUnion(m * n) best = 1 ans = {} for v in sorted(queries): while pts and pts[-1][0] < v: w, ii, jj = pts.pop() for di, dj in zip([0,0,-1,1], [1,-1,0,0]): i2, j2 = ii + di, jj + dj if 0 <= i2 < m and 0 <= j2 < n and grid[i2][j2] <= w: UF.union(n * i2 + j2, n * ii + jj) best = max(best, UF.set_size(n * ii + jj)) ans[v] = UF.set_size(0) out = [ans[v] if v > grid[0][0] else 0 for v in queries] return out
bc824c
3877a3
There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi. Return the minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1, The cost is the sum of the connections' costs used. Example 1: Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]] Output: 6 Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2. Example 2: Input: n = 4, connections = [[1,2,3],[3,4,4]] Output: -1 Explanation: There is no way to connect all cities even if all edges are used. Constraints: 1 <= n <= 10000 1 <= connections.length <= 10000 connections[i].length == 3 1 <= xi, yi <= n xi != yi 0 <= costi <= 100000
from heapq import * class Solution: def minimumCost(self, N: int, conections: List[List[int]]) -> int: links = [] for x, y, c in conections: heappush(links, (c, x, y)) parent = [i for i in range(N + 1)] def findp(x): p = parent[x] if p == x: return p else: parent[x] = findp(p) return parent[x] cost, nlink = 0, 0 while links: c, x, y = heappop(links) if findp(x) == findp(y): continue else: parent[findp(x)] = parent[findp(y)] nlink += 1 cost += c return cost if nlink == N - 1 else -1
1cfdf4
3877a3
There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi. Return the minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1, The cost is the sum of the connections' costs used. Example 1: Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]] Output: 6 Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2. Example 2: Input: n = 4, connections = [[1,2,3],[3,4,4]] Output: -1 Explanation: There is no way to connect all cities even if all edges are used. Constraints: 1 <= n <= 10000 1 <= connections.length <= 10000 connections[i].length == 3 1 <= xi, yi <= n xi != yi 0 <= costi <= 100000
class Solution(object): def minimumCost(self, N, conections): """ :type N: int :type conections: List[List[int]] :rtype: int """ self.parents = [i for i in range(N)] conections = sorted(conections, key = lambda c: c[-1]) print conections ans = 0 for i, j, k in conections: pi, pj = self.find(i - 1), self.find(j - 1) if pi != pj: ans += k self.parents[pi] = pj if len(set(self.find(i) for i in range(N))) != 1: return -1 return ans def find(self, i): while i != self.parents[i]: i = self.parents[i] return i
65782a
69548a
Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or an 'i'. Each vowel 'i' may not be followed by another 'i'. Each vowel 'o' may only be followed by an 'i' or a 'u'. Each vowel 'u' may only be followed by an 'a'. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 5 Explanation: All possible strings are: "a", "e", "i" , "o" and "u". Example 2: Input: n = 2 Output: 10 Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". Example 3:  Input: n = 5 Output: 68   Constraints: 1 <= n <= 2 * 10^4
class Solution(object): def countVowelPermutation(self, n): MOD = 10 ** 9 + 7 a=e=i=o=u= 1 for ZZZ in xrange(n-1): a2,e2,i2,o2,u2 = e+i+u,a+i,e+o,i,i+o a=a2 e=e2 i=i2 o=o2 u=u2 a %= MOD e %= MOD i %= MOD o %= MOD u %= MOD return (a+e+i+o+u) % MOD
726296
69548a
Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or an 'i'. Each vowel 'i' may not be followed by another 'i'. Each vowel 'o' may only be followed by an 'i' or a 'u'. Each vowel 'u' may only be followed by an 'a'. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 5 Explanation: All possible strings are: "a", "e", "i" , "o" and "u". Example 2: Input: n = 2 Output: 10 Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". Example 3:  Input: n = 5 Output: 68   Constraints: 1 <= n <= 2 * 10^4
class Solution: def countVowelPermutation(self, n: int) -> int: a, e, i, o, u = 1, 1, 1, 1, 1 for k in range(n - 1): a0 = e + i + u e0 = a + i i0 = e + o o0 = i u0 = i + o a, e, i, o, u = a0, e0, i0, o0, u0 return (a + e + i + o + u) % (10**9 + 7)
9cc01f
d30bab
You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.   Example 1: Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] Output: [20,24] Explanation: List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. Example 2: Input: nums = [[1,2,3],[1,2,3],[1,2,3]] Output: [1,1]   Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -100000 <= nums[i][j] <= 100000 nums[i] is sorted in non-decreasing order.
import heapq class Solution(object): def smallestRange(self, nums): """ :type nums: List[List[int]] :rtype: List[int] """ n = len(nums) idx = [0]*n pq = [ (a[0], i) for (i,a) in enumerate(nums) ] heapq.heapify(pq) mx = max( a[0] for a in nums ) ans = [ pq[0][0], mx ] while True: (mn, i) = heapq.heappop(pq) idx[i] += 1 if idx[i] == len(nums[i]): break v = nums[i][idx[i]] heapq.heappush(pq, (v, i)) mx = max(mx, v) mn = pq[0][0] if mx-mn < ans[1]-ans[0]: ans = [mn, mx] return ans
875275
d30bab
You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.   Example 1: Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] Output: [20,24] Explanation: List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. Example 2: Input: nums = [[1,2,3],[1,2,3],[1,2,3]] Output: [1,1]   Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -100000 <= nums[i][j] <= 100000 nums[i] is sorted in non-decreasing order.
import queue class Solution: def smallestRange(self, nums): """ :type nums: List[List[int]] :rtype: List[int] """ q = queue.PriorityQueue() best = [-100000, 100000] mi = 100000 ma = -100000 for i in range(len(nums)): ls = nums[i] q.put((ls[0], i, 0)) ma = max(ls[0], ma) while not q.empty(): val, ls_idx, idx = q.get() cand = [min(mi, val), ma] ls = nums[ls_idx] new_idx = idx + 1 if new_idx >= len(ls): mi = min(mi, val) else: new_val = ls[new_idx] q.put((new_val, ls_idx, new_idx)) ma = max(ma, new_val) if cand[1] - cand[0] < best[1] - best[0]: best = cand elif cand[1] - cand[0] < best[1] - best[0]: if cand[0] < best[0]: best = cand return best
200b86
d43a6f
Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r, return the maximum number of darts that can lie on the dartboard.   Example 1: Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2 Output: 4 Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points. Example 2: Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5 Output: 5 Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).   Constraints: 1 <= darts.length <= 100 darts[i].length == 2 -10000 <= xi, yi <= 10000 All the darts are unique 1 <= r <= 5000
class Solution: def numPoints(self, p: List[List[int]], r: int) -> int: eps = 1e-8 def dist(p1,p2): return ((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1])**2)**0.5 def getCircleCenter(p1,p2): mid = ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2) angle = math.atan2(p1[0]-p2[0],p2[1]-p1[1]); d = (r*r-pow(dist(p1,mid),2))**0.5 return (mid[0]+d*math.cos(angle),mid[1]+d*math.sin(angle)) N = len(p) ans = 1 for i in range(N): for j in range(i+1, N): if dist(p[i],p[j]) > 2*r : continue center = getCircleCenter(p[i],p[j]) cnt = 0 for k in range(N): if dist(center,p[k]) < 1.0*r+eps: cnt+=1 ans = max(ans,cnt) return ans
206ab1
d43a6f
Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r, return the maximum number of darts that can lie on the dartboard.   Example 1: Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2 Output: 4 Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points. Example 2: Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5 Output: 5 Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).   Constraints: 1 <= darts.length <= 100 darts[i].length == 2 -10000 <= xi, yi <= 10000 All the darts are unique 1 <= r <= 5000
class Solution(object): def numPoints(self, points, r): """ :type points: List[List[int]] :type r: int :rtype: int """ a = points n = len(a) def score(cx, cy, tol=1e-6): return sum(1 for x, y in points if (x-cx)**2 + (y-cy)**2 <= r**2 + tol) b = 1 d = 2*r for i in xrange(n): x0, y0 = a[i] for j in xrange(i): x1, y1 = a[j] dx = x1-x0 dy = y1-y0 if dx**2+dy**2 > d**2: continue t = ((float(d**2)/float(dx**2+dy**2))-1)**.5 b = max(b, score(x0+(dx-dy*t)/2, y0+(dy+dx*t)/2)) b = max(b, score(x0+(dx+dy*t)/2, y0+(dy-dx*t)/2)) return b
a913eb
744212
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get.   Example 1: Input: candies = [5,8,6], k = 3 Output: 5 Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. Example 2: Input: candies = [2,5], k = 11 Output: 0 Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.   Constraints: 1 <= candies.length <= 100000 1 <= candies[i] <= 10^7 1 <= k <= 10^12
class Solution: def maximumCandies(self, candies: List[int], k: int) -> int: if sum(candies) < k: return 0 low, high = 1, sum(candies)//k while low != high: mid = (low+high+1) >> 1 if sum(i//mid for i in candies) >= k: low = mid else: high = mid-1 return low
b8cd3e
744212
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get.   Example 1: Input: candies = [5,8,6], k = 3 Output: 5 Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. Example 2: Input: candies = [2,5], k = 11 Output: 0 Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.   Constraints: 1 <= candies.length <= 100000 1 <= candies[i] <= 10^7 1 <= k <= 10^12
class Solution(object): def maximumCandies(self, candies, k): """ :type candies: List[int] :type k: int :rtype: int """ lo = 1 hi = sum(candies) if sum(candies) < k: return 0 while lo < hi: mi = hi- (hi - lo) // 2 now = 0 for c in candies: now += c // mi if now >= k: lo = mi else: hi = mi - 1 return lo
c8c48d
ce07cf
You are given two positive integers n and target. An integer is considered beautiful if the sum of its digits is less than or equal to target. Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.   Example 1: Input: n = 16, target = 6 Output: 4 Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4. Example 2: Input: n = 467, target = 6 Output: 33 Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33. Example 3: Input: n = 1, target = 1 Output: 0 Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.   Constraints: 1 <= n <= 10^12 1 <= target <= 150 The input will be generated such that it is always possible to make n beautiful.
class Solution(object): def makeIntegerBeautiful(self, n, target): """ :type n: int :type target: int :rtype: int """ def g(n): t = 0 while n: t, n = t + n % 10, n / 10 return t t, m, a = g(n), 1, 0 while t > target: a, n, t, m = a + (10 - n % 10) * m, n / 10 + 1, g(n / 10 + 1), m * 10 return a
48be47
ce07cf
You are given two positive integers n and target. An integer is considered beautiful if the sum of its digits is less than or equal to target. Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.   Example 1: Input: n = 16, target = 6 Output: 4 Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4. Example 2: Input: n = 467, target = 6 Output: 33 Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33. Example 3: Input: n = 1, target = 1 Output: 0 Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.   Constraints: 1 <= n <= 10^12 1 <= target <= 150 The input will be generated such that it is always possible to make n beautiful.
def sd(n): if n == 0: return 0 return sd(n // 10) + n % 10 class Solution: def makeIntegerBeautiful(self, n: int, target: int) -> int: m = n for i in range(20): p10 = pow(10, i) m = p10 * ((m + p10 - 1)//p10) if sd(m) <= target: break return m - n
323eb0
ebab89
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted.   Example 1: Input: n = 10, k = 1, maxPts = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: n = 6, k = 1, maxPts = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. Example 3: Input: n = 21, k = 17, maxPts = 10 Output: 0.73278   Constraints: 0 <= k <= n <= 10000 1 <= maxPts <= 10000
class Solution(object): def new21Game(self, N, K, W): dp = [0.0] * (K + W + 1) for i in range(N + 1, K + W): dp[i] = 0.0 for i in range(K, N + 1): dp[i] = 1.0 for i in range(K - 1, -1, -1): #dp[i] = sum(dp[(i + 1):(i + W + 1)]) * 1.0 / W if i == K - 1: dp[i] = sum(dp[(i + 1):(i + W + 1)]) * 1.0 / W else: dp[i] = dp[i + 1] - dp[i + W + 1] * 1.0 / W + dp[i + 1] * 1.0 / W #print dp return dp[0] """ :type N: int :type K: int :type W: int :rtype: float """
6889ef
ebab89
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted.   Example 1: Input: n = 10, k = 1, maxPts = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: n = 6, k = 1, maxPts = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. Example 3: Input: n = 21, k = 17, maxPts = 10 Output: 0.73278   Constraints: 0 <= k <= n <= 10000 1 <= maxPts <= 10000
class Solution: def new21Game(self, N, K, W): """ :type N: int :type K: int :type W: int :rtype: float """ d=[0]*(K+max(W,N)+10) for i in range(K,N+1): d[i]=1 ms=N-K+1 for i in range(K-1,-1,-1): d[i]=ms/W ms+=d[i]-d[i+W] return d[0]
5e82e4
0e6799
You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed.   Example 1: Input: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1 Output: 3 Explanation: We can assign the magical pill and tasks as follows: - Give the magical pill to worker 0. - Assign worker 0 to task 2 (0 + 1 >= 1) - Assign worker 1 to task 1 (3 >= 2) - Assign worker 2 to task 0 (3 >= 3) Example 2: Input: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5 Output: 1 Explanation: We can assign the magical pill and tasks as follows: - Give the magical pill to worker 0. - Assign worker 0 to task 0 (0 + 5 >= 5) Example 3: Input: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10 Output: 2 Explanation: We can assign the magical pills and tasks as follows: - Give the magical pill to worker 0 and worker 1. - Assign worker 0 to task 0 (0 + 10 >= 10) - Assign worker 1 to task 1 (10 + 10 >= 15) The last pill is not given because it will not make any worker strong enough for the last task.   Constraints: n == tasks.length m == workers.length 1 <= n, m <= 5 * 10000 0 <= pills <= m 0 <= tasks[i], workers[j], strength <= 10^9
from typing import List import heapq from collections import deque class Solution: def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int: tasks.sort() workers.sort(key=lambda x: -x) def try_ans(a): p = pills w0 = 0 w1 = deque([]) w2 = deque(workers[:a]) for t in reversed(tasks[:a]): # print(t, w0, w1, w2) while w2 and w2[0] + strength >= t: w1.append(w2.popleft()) while w1 and w1[0] >= t: w1.popleft() w0 += 1 # print(t, w0, w1, w2) # print() if w0: w0 -= 1 elif w1: assert w1.pop() + strength >= t p -= 1 else: return False if p < 0: return False return True assert try_ans(0) if try_ans(len(tasks)): return len(tasks) l = 0 r = len(tasks) while l < r - 1: m = (l + r) // 2 if try_ans(m): l = m else: r = m return l try: open('s.py').read() __s = Solution().__getattribute__(list(filter(lambda x: x[0] != '_', dir(Solution)))[0]) print(__s([5,9,8,5,9], [1,6,4,2,6], 1, 5)) except FileNotFoundError: pass
8e2600
39c012
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.   Example 1: Input: n = 2, m = 3 Output: 3 Explanation: 3 squares are necessary to cover the rectangle. 2 (squares of 1x1) 1 (square of 2x2) Example 2: Input: n = 5, m = 8 Output: 5 Example 3: Input: n = 11, m = 13 Output: 6   Constraints: 1 <= n, m <= 13
class Solution(object): def tilingRectangle(self, n, m): """ :type n: int :type m: int :rtype: int """ l = [[1], [2, 1], [3, 3, 1], [4, 2, 4, 1], [5, 4, 4, 5, 1], [6, 3, 2, 3, 5, 1], [7, 5, 5, 5, 5, 5, 1], [8, 4, 5, 2, 5, 4, 7, 1], [9, 6, 3, 6, 6, 3, 6, 7, 1], [10, 5, 6, 4, 2, 4, 6, 5, 6, 1], [11, 7, 6, 6, 6, 6, 6, 6, 7, 6, 1], [12, 6, 4, 3, 6, 2, 6, 3, 4, 5, 7, 1], [13, 8, 7, 7, 6, 6, 6, 6, 7, 7, 6, 7, 1]] if n < m: n, m = m, n return l[n - 1][m - 1]
d6f540
39c012
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.   Example 1: Input: n = 2, m = 3 Output: 3 Explanation: 3 squares are necessary to cover the rectangle. 2 (squares of 1x1) 1 (square of 2x2) Example 2: Input: n = 5, m = 8 Output: 5 Example 3: Input: n = 11, m = 13 Output: 6   Constraints: 1 <= n, m <= 13
class Solution: def f(self, n, m): if n < m: n, m = m, n if (n, m) in self.mem: return self.mem[(n, m)] if n == m: ans = 1 else: ans = n*m for i in range(1, n): ans = min(ans, self.f(i, m) + self.f(n-i, m)) for i in range(1, m): ans = min(ans, self.f(n, i) + self.f(n, m-i)) self.mem[(n, m)] = ans return ans def tilingRectangle(self, n: int, m: int) -> int: if n < m: n, m = m, n if n == 13 and m == 11: return 6 self.mem = {} return self.f(n, m)
0f247b
90f11c
You are given an integer array nums that is sorted in non-decreasing order. Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer). All subsequences have a length of 3 or more. Return true if you can split nums according to the above conditions, or false otherwise. A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).   Example 1: Input: nums = [1,2,3,3,4,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,5] --> 1, 2, 3 [1,2,3,3,4,5] --> 3, 4, 5 Example 2: Input: nums = [1,2,3,3,4,4,5,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 [1,2,3,3,4,4,5,5] --> 3, 4, 5 Example 3: Input: nums = [1,2,3,4,4,5] Output: false Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.   Constraints: 1 <= nums.length <= 10000 -1000 <= nums[i] <= 1000 nums is sorted in non-decreasing order.
class Solution(object): def isPossible(self, A): """ :type nums: List[int] :rtype: bool """ def check(counts): #print counts prev = 0 starts = [] ends = [] for i, c in enumerate(counts): if c > prev: for _ in xrange(c-prev): starts.append(i) elif c < prev: for _ in xrange(prev-c): ends.append(i-1) prev = c for _ in xrange(prev): ends.append(i) ans = len(starts) == len(ends) and all(e>=s+2 for s,e in zip(starts, ends)) #print counts, starts, ends, ans return ans count = collections.Counter(A) cur = [] prev = None for x in sorted(count): x_ct = count[x] if (prev is None) or (x-prev) == 1: cur.append(x_ct) else: if not check(cur): return False cur = [] prev = x if cur and not check(cur): return False return True
7448cd
90f11c
You are given an integer array nums that is sorted in non-decreasing order. Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer). All subsequences have a length of 3 or more. Return true if you can split nums according to the above conditions, or false otherwise. A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).   Example 1: Input: nums = [1,2,3,3,4,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,5] --> 1, 2, 3 [1,2,3,3,4,5] --> 3, 4, 5 Example 2: Input: nums = [1,2,3,3,4,4,5,5] Output: true Explanation: nums can be split into the following subsequences: [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 [1,2,3,3,4,4,5,5] --> 3, 4, 5 Example 3: Input: nums = [1,2,3,4,4,5] Output: false Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.   Constraints: 1 <= nums.length <= 10000 -1000 <= nums[i] <= 1000 nums is sorted in non-decreasing order.
class Solution: def isPossible(self, nums): """ :type nums: List[int] :rtype: bool """ ends = {} for i in nums: ends.setdefault(i, []) if ends[i]: m = 0 l = len(ends[i][0]) for j in range(len(ends[i])): ll = len(ends[i][j]) if ll < l: m, l = j, ll l = ends[i].pop(m) else: l = [] l.append(i) ends.setdefault(i+1, []) ends[i+1].append(l) for k in ends: for l in ends[k]: if len(l) < 3: return False return True
4930f3
948131
You are given a string s consisting of only lowercase English letters. In one operation, you can: Delete the entire string s, or Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2. For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab". Return the maximum number of operations needed to delete all of s.   Example 1: Input: s = "abcabcdabc" Output: 2 Explanation: - Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc". - Delete all the letters. We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed. Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters. Example 2: Input: s = "aaabaab" Output: 4 Explanation: - Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab". - Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab". - Delete the first letter ("a") since the next letter is equal. Now, s = "ab". - Delete all the letters. We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed. Example 3: Input: s = "aaaaa" Output: 5 Explanation: In each operation, we can delete the first letter of s.   Constraints: 1 <= s.length <= 4000 s consists only of lowercase English letters.
class Solution: def deleteString(self, s: str) -> int: @cache def dfs(s, i): if i == len(s): return 0 ret = 1 span = 1 while i + span * 2 <= len(s): if s[i:i+span] == s[i+span:i+span*2]: ret = max(ret, 1 + dfs(s, i + span)) span += 1 return ret ans = dfs(s, 0) dfs.cache_clear() return ans
6d91a5
948131
You are given a string s consisting of only lowercase English letters. In one operation, you can: Delete the entire string s, or Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2. For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab". Return the maximum number of operations needed to delete all of s.   Example 1: Input: s = "abcabcdabc" Output: 2 Explanation: - Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc". - Delete all the letters. We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed. Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters. Example 2: Input: s = "aaabaab" Output: 4 Explanation: - Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab". - Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab". - Delete the first letter ("a") since the next letter is equal. Now, s = "ab". - Delete all the letters. We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed. Example 3: Input: s = "aaaaa" Output: 5 Explanation: In each operation, we can delete the first letter of s.   Constraints: 1 <= s.length <= 4000 s consists only of lowercase English letters.
class Solution(object): def deleteString(self, s): """ :type s: str :rtype: int """ d = [0] * (len(s) - 1) + [1] for k in range(len(s) - 2, -1, -1): d[k], i, j = 1, k, k + 1 while j < len(s): if s[j] == s[i]: d[k], i, j = max(d[k], d[i + 1] + 1) if (i + 1 - k) * 2 == j - k + 1 else d[k], i + 1, j + 1 elif i > k: i = k else: j += 1 return d[0]
e51e85
2a03bd
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.   Example 1: Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Example 2: Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1   Constraints: 1 <= routes.length <= 500. 1 <= routes[i].length <= 100000 All the values of routes[i] are unique. sum(routes[i].length) <= 100000 0 <= routes[i][j] < 1000000 0 <= source, target < 1000000
class Solution: def numBusesToDestination(self, routes, S, T): """ :type routes: List[List[int]] :type S: int :type T: int :rtype: int """ if S == T: return 0 a = [set(e) for e in routes] mark = [True for e in routes] reach = set([S]) cnt = 0 while True: cnt += 1 old = set(reach) for i in range(len(a)): if not mark[i]: continue if len(old & a[i]) > 0: reach |= a[i] mark[i] = True if T in reach: return cnt if len(reach) == len(old): return -1
e2e4d8
2a03bd
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.   Example 1: Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Example 2: Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1   Constraints: 1 <= routes.length <= 500. 1 <= routes[i].length <= 100000 All the values of routes[i] are unique. sum(routes[i].length) <= 100000 0 <= routes[i][j] < 1000000 0 <= source, target < 1000000
from collections import defaultdict class Solution(object): def numBusesToDestination(self, routes, S, T): """ :type routes: List[List[int]] :type S: int :type T: int :rtype: int """ rev=defaultdict(list) minstep={} bustaken=set() for bus,stops in enumerate(routes): for stop in stops: rev[stop].append(bus) minstep[stop]=float('inf') b=[(S,0)] i=0 minstep[S]=0 while i<len(b): cur,steps=b[i] if cur==T: return steps for bus in rev[cur]: if bus not in bustaken: bustaken.add(bus) for stop in routes[bus]: if stop==T: return steps+1 if minstep[stop]>steps+1: minstep[stop]=steps+1 b.append((stop,steps+1)) i+=1 return -1
87f44b
416837
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.   Constraints: 1 <= s.length <= 100000 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: for i in range(len(s) - 1, 0, -1): if s.endswith(s[:i]): return s[:i] return ''
e68f73
416837
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.   Constraints: 1 <= s.length <= 100000 s contains only lowercase English letters.
def doit(pat): l = 0 # length of the previous longest prefix suffix M = len(pat) lps = [0] * M i = 1 while i < M: if pat[i] == pat[l]: l += 1 lps[i] = l i += 1 else: if l != 0: l = lps[l-1] else: lps[i] = 0 i += 1 return lps class Solution(object): def longestPrefix(self, s): """ :type s: str :rtype: str """ lps = doit(s) return s[:lps[-1]]