sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
06b883
addc64
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.   Example 1: Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 Output: [0,1,2,3,5] Explanation: At time 0, person 0 shares the secret with person 1. At time 5, person 1 shares the secret with person 2. At time 8, person 2 shares the secret with person 3. At time 10, person 1 shares the secret with person 5.​​​​ Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. Example 2: Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 Output: [0,1,3] Explanation: At time 0, person 0 shares the secret with person 3. At time 2, neither person 1 nor person 2 know the secret. At time 3, person 3 shares the secret with person 0 and person 1. Thus, people 0, 1, and 3 know the secret after all the meetings. Example 3: Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 Output: [0,1,2,3,4] Explanation: At time 0, person 0 shares the secret with person 1. At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. Note that person 2 can share the secret at the same time as receiving it. At time 2, person 3 shares the secret with person 4. Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.   Constraints: 2 <= n <= 100000 1 <= meetings.length <= 100000 meetings[i].length == 3 0 <= xi, yi <= n - 1 xi != yi 1 <= timei <= 100000 1 <= firstPerson <= n - 1
from collections import defaultdict class Solution(object): def findAllPeople(self, n, meetings, firstPerson): """ :type n: int :type meetings: List[List[int]] :type firstPerson: int :rtype: List[int] """ d = defaultdict(list) for u, v, t in meetings: d[t].append((u, v)) d[0].append((0, firstPerson)) vis = [False] * n vis[0] = True for t in sorted(d): adj = defaultdict(list) for u, v in d[t]: adj[u].append(v) adj[v].append(u) q = [u for u in adj if vis[u]] while q: u = q.pop() for v in adj[u]: if not vis[v]: q.append(v) vis[v] = True return [i for i in xrange(n) if vis[i]]
856363
b9300a
Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values. Two nodes of a binary tree are cousins if they have the same depth with different parents. Return the root of the modified tree. Note that the depth of a node is the number of edges in the path from the root node to it.   Example 1: Input: root = [5,4,9,1,10,null,7] Output: [0,0,0,7,7,null,11] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. Example 2: Input: root = [3,1,2] Output: [0,0,0] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0.   Constraints: The number of nodes in the tree is in the range [1, 10^5]. 1 <= Node.val <= 10^4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: queue = [(root, None)] while queue: next_queue = [] child_sum = defaultdict(int) p = {} curr = 0 for _ in range(len(queue)): node, parent = queue.pop() child_sum[parent] += node.val p[node] = parent curr += node.val if node.left: next_queue.append((node.left, node)) if node.right: next_queue.append((node.right, node)) for node in p: node.val = curr - child_sum[p[node]] queue = next_queue return root
719520
b9300a
Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values. Two nodes of a binary tree are cousins if they have the same depth with different parents. Return the root of the modified tree. Note that the depth of a node is the number of edges in the path from the root node to it.   Example 1: Input: root = [5,4,9,1,10,null,7] Output: [0,0,0,7,7,null,11] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. Example 2: Input: root = [3,1,2] Output: [0,0,0] Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0.   Constraints: The number of nodes in the tree is in the range [1, 10^5]. 1 <= Node.val <= 10^4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def replaceValueInTree(self, root): """ :type root: Optional[TreeNode] :rtype: Optional[TreeNode] """ cs = {} def dfs(r, l): if not r: return if l not in cs: cs[l]=0 cs[l]+=r.val dfs(r.left, l+1) dfs(r.right, l+1) dfs(root, 0) def rebuild(r, v, l): if not r: return r.val = cs[l]-v-r.val v1, v2 = 0, 0 if r.left: v1=r.left.val if r.right: v2=r.right.val rebuild(r.left, v2, l+1) rebuild(r.right, v1, l+1) rebuild(root, 0, 0) return root
424eeb
13fa5f
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) In addition, the spell checker operates under the following precedence rules: When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. When the query matches a word up to capitlization, you should return the first such match in the wordlist. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. If the query has no matches in the wordlist, you should return the empty string. Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].   Example 1: Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] Example 2: Input: wordlist = ["yellow"], queries = ["YellOw"] Output: ["yellow"]   Constraints: 1 <= wordlist.length, queries.length <= 5000 1 <= wordlist[i].length, queries[i].length <= 7 wordlist[i] and queries[i] consist only of only English letters.
class Solution: def spellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ wl = set(wordlist) ci = {} for w in wordlist: if w.lower() not in ci: ci[w.lower()] = w vi = {} for w in wordlist: w1 = w.lower() for l in 'aeiou': w1 = w1.replace(l, '_') if w1 not in vi: vi[w1] = w result = [] #print(vi) for q in queries: if q in wl: result.append(q) elif q.lower() in ci: result.append(ci[q.lower()]) else: qq = q.lower() for l in 'aeiou': qq = qq.replace(l, '_') if qq in vi: result.append(vi[qq]) else: result.append("") return result
cbb039
13fa5f
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) In addition, the spell checker operates under the following precedence rules: When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. When the query matches a word up to capitlization, you should return the first such match in the wordlist. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. If the query has no matches in the wordlist, you should return the empty string. Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].   Example 1: Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] Example 2: Input: wordlist = ["yellow"], queries = ["YellOw"] Output: ["yellow"]   Constraints: 1 <= wordlist.length, queries.length <= 5000 1 <= wordlist[i].length, queries[i].length <= 7 wordlist[i] and queries[i] consist only of only English letters.
class Solution(object): def spellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ def can(mapper): r = {} for word in wordlist: r.setdefault(mapper(word), word) return r def cap(word): return word.lower() d = {c:'-' for c in 'aeiou'} def vow(word): return ''.join(d.get(c,c) for c in word.lower()) words = set(wordlist) dcap = can(cap) dvow = can(vow) def correct(word): if word in words: return word if cap(word) in dcap: return dcap[cap(word)] if vow(word) in dvow: return dvow[vow(word)] return '' return map(correct, queries)
fd30c2
3bd001
You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'. You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7. In case there is no path, return [0, 0].   Example 1: Input: board = ["E23","2X2","12S"] Output: [7,1] Example 2: Input: board = ["E12","1X1","21S"] Output: [4,2] Example 3: Input: board = ["E11","XXX","11S"] Output: [0,0]   Constraints: 2 <= board.length == board[i].length <= 100
class Solution(object): def pathsWithMaxScore(self, A): R, C = len(A), len(A[0]) MOD = 10**9 + 7 A = map(list, A) A[0][0] = "0" A[-1][-1] = "0" for r, row in enumerate(A): for c, val in enumerate(row): if val == "X": A[r][c] = "-1" A = [map(int, row) for row in A] # max sum, number of paths to get max sum dp = [[ [0, 0 ] for c in xrange(C+1) ] for _ in xrange(R+1)] dp[0][0][1] = 1 # sum , num ways for r in xrange(R): for c in xrange(C): if r == c == 0: continue if A[r][c] == -1: continue s = w = None if r-1 >= 0: s, w = dp[r-1][c] if c-1 >= 0: s2, w2 = dp[r][c-1] if s == s2: w += w2 elif s2 > s: s, w = s2, w2 if r-1>=0 and c-1>=0: s3, w3 = dp[r-1][c-1] if s is None: s, w = s3, w3 elif s3 > s: s, w = s3, w3 elif s3 == s: w += w3 s += A[r][c] w %= MOD dp[r][c][0] = s dp[r][c][1] = w #print "!",r,c,';',s,w #print dp[r] s,w = dp[-2][-2] if w == 0: return [0,0] return [s,w]
90eaf6
3bd001
You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'. You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7. In case there is no path, return [0, 0].   Example 1: Input: board = ["E23","2X2","12S"] Output: [7,1] Example 2: Input: board = ["E12","1X1","21S"] Output: [4,2] Example 3: Input: board = ["E11","XXX","11S"] Output: [0,0]   Constraints: 2 <= board.length == board[i].length <= 100
class Solution: def pathsWithMaxScore(self, board: List[str]) -> List[int]: n = len(board) score, path = [[-1] * n for _ in range(n)], [[0] * n for _ in range(n)] dx, dy = [0, 1, 1], [1, 0, 1] MOD = 10 ** 9 + 7 for i in range(n - 1, -1, -1): for j in range(n - 1, -1, -1): if i == n - 1 == j: score[i][j] = 0 path[i][j] = 1 continue if board[i][j] == 'X': continue m = 0 p = 0 f = False for k in range(3): ni, nj = i + dx[k], j + dy[k] if ni < n and nj < n and board[ni][nj] != 'X' and score[ni][nj] >= 0: f = True if m == score[ni][nj]: m = score[ni][nj] p += path[ni][nj] elif m < score[ni][nj]: m = score[ni][nj] p = path[ni][nj] if f: score[i][j] = m + (int(board[i][j]) if board[i][j].isnumeric() else 0) path[i][j] = p % MOD return [max(0, score[0][0]), path[0][0]]
a5eea6
4ed788
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["ca","bb","ac"] Output: 1 Explanation: After deleting the first column, strs = ["a", "b", "c"]. Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1. Example 2: Input: strs = ["xc","yb","za"] Output: 0 Explanation: strs is already in lexicographic order, so we do not need to delete anything. Note that the rows of strs are not necessarily in lexicographic order: i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) Example 3: Input: strs = ["zyx","wvu","tsr"] Output: 3 Explanation: We have to delete every column.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.
class Solution: def minDeletionSize(self, A): """ :type A: List[str] :rtype: int """ def inorder(chars, same_prefix): for i in range(len(chars)-1): if chars[i] <= chars[i+1] or not same_prefix[i]: continue return False return True n, m = len(A), len(A[0]) same_prefix_with_next = [True] * n del_cnt = 0 for j in range(m): col = [A[i][j] for i in range(n)] if not inorder(col, same_prefix_with_next): del_cnt += 1 else: for i in range(n-1): same_prefix_with_next[i] &= col[i] == col[i+1] return del_cnt
2770cd
4ed788
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["ca","bb","ac"] Output: 1 Explanation: After deleting the first column, strs = ["a", "b", "c"]. Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1. Example 2: Input: strs = ["xc","yb","za"] Output: 0 Explanation: strs is already in lexicographic order, so we do not need to delete anything. Note that the rows of strs are not necessarily in lexicographic order: i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) Example 3: Input: strs = ["zyx","wvu","tsr"] Output: 3 Explanation: We have to delete every column.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.
from collections import deque class Solution(object): def minDeletionSize(self, A): """ :type A: List[str] :rtype: int """ A = map(list, A) A = zip(*A) i = c = 0 while i < len(A): X = zip(*A[:i+1]) if X != sorted(X): A.pop(i) c += 1 else: i += 1 return c
746285
ca15e6
There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points. Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 10^9 + 7. Note that questions of the same type are indistinguishable. For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.   Example 1: Input: target = 6, types = [[6,1],[3,2],[2,3]] Output: 7 Explanation: You can earn 6 points in one of the seven ways: - Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6 - Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6 - Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6 - Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6 - Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6 - Solve 3 questions of the 1st type: 2 + 2 + 2 = 6 - Solve 2 questions of the 2nd type: 3 + 3 = 6 Example 2: Input: target = 5, types = [[50,1],[50,2],[50,5]] Output: 4 Explanation: You can earn 5 points in one of the four ways: - Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5 - Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5 - Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5 - Solve 1 question of the 2nd type: 5 Example 3: Input: target = 18, types = [[6,1],[3,2],[2,3]] Output: 1 Explanation: You can only earn 18 points by answering all questions.   Constraints: 1 <= target <= 1000 n == types.length 1 <= n <= 50 types[i].length == 2 1 <= counti, marksi <= 50
class Solution: def waysToReachTarget(self, target: int, types: List[List[int]]) -> int: mod = 10 ** 9 + 7 dp = [0] * (target + 1) dp[0] = 1 for c, v in types: for i in range(target, 0, -1): for j in range(1, c+1): if i - j*v >= 0: dp[i] = (dp[i] + dp[i-j*v]) % mod return dp[target]
88af7c
ca15e6
There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points. Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 10^9 + 7. Note that questions of the same type are indistinguishable. For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.   Example 1: Input: target = 6, types = [[6,1],[3,2],[2,3]] Output: 7 Explanation: You can earn 6 points in one of the seven ways: - Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6 - Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6 - Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6 - Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6 - Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6 - Solve 3 questions of the 1st type: 2 + 2 + 2 = 6 - Solve 2 questions of the 2nd type: 3 + 3 = 6 Example 2: Input: target = 5, types = [[50,1],[50,2],[50,5]] Output: 4 Explanation: You can earn 5 points in one of the four ways: - Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5 - Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5 - Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5 - Solve 1 question of the 2nd type: 5 Example 3: Input: target = 18, types = [[6,1],[3,2],[2,3]] Output: 1 Explanation: You can only earn 18 points by answering all questions.   Constraints: 1 <= target <= 1000 n == types.length 1 <= n <= 50 types[i].length == 2 1 <= counti, marksi <= 50
class Solution(object): def waysToReachTarget(self, target, types): """ :type target: int :type types: List[List[int]] :rtype: int """ d = [[-1] * 1001 for _ in range(52)] def a(i, t): if not t or (t < 0 or i == len(types)) or (d[i][t] != -1): return 1 if not t else 0 if t < 0 or i == len(types) else d[i][t] d[i][t] = 0 for j in range(types[i][0] + 1): d[i][t] = (d[i][t] + a(i + 1, t - j * types[i][1])) % 1000000007 return d[i][t] return a(0, target)
cb1bf9
d67f2b
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (arr[i], arr[j], arr[k]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. Example 2: Input: arr = [1,1,2,2,2,2], target = 5 Output: 12 Explanation: arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: We choose one 1 from [1,1] in 2 ways, and two 2s from [2,2,2,2] in 6 ways. Example 3: Input: arr = [2,1,3], target = 6 Output: 1 Explanation: (1, 2, 3) occured one time in the array so we return 1.   Constraints: 3 <= arr.length <= 3000 0 <= arr[i] <= 100 0 <= target <= 300
from collections import defaultdict class Solution: def threeSumMulti(self, A, target): """ :type A: List[int] :type target: int :rtype: int """ mod = 10 ** 9 + 7 count = defaultdict(int) count2 = defaultdict(int) count3 = defaultdict(int) for x in A: for k, v in count2.items(): count3[k + x] = (count3[k + x] + v) % mod for k, v in count.items(): count2[k + x] = (count2[k + x] + v) % mod count[x] += 1 return count3[target] % mod
65e819
d67f2b
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (arr[i], arr[j], arr[k]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. Example 2: Input: arr = [1,1,2,2,2,2], target = 5 Output: 12 Explanation: arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: We choose one 1 from [1,1] in 2 ways, and two 2s from [2,2,2,2] in 6 ways. Example 3: Input: arr = [2,1,3], target = 6 Output: 1 Explanation: (1, 2, 3) occured one time in the array so we return 1.   Constraints: 3 <= arr.length <= 3000 0 <= arr[i] <= 100 0 <= target <= 300
from collections import Counter class Solution(object): def threeSumMulti(self, A, target): """ :type A: List[int] :type target: int :rtype: int """ c = Counter(A) c = [(key, value) for key, value in c.iteritems()] ans = 0 mod = 10**9 + 7 for i in range(len(c)): for j in range(i, len(c)): for k in range(j, len(c)): if c[i][0] + c[j][0] + c[k][0] == target: if i==j and j==k: ans += c[i][1]*(c[i][1]-1)*(c[i][1]-2)/6 ans %= mod elif i==j: ans += c[i][1]*(c[i][1]-1)/2*c[k][1] ans %= mod elif i==k: ans += c[i][1]*(c[i][1]-1)/2*c[j][1] ans %= mod elif j==k: ans += c[j][1]*(c[j][1]-1)/2*c[i][1] ans %= mod else: ans += c[i][1]*c[j][1]*c[k][1] ans %= mod return ans % mod
e5a58d
8ecb46
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's.   Example 1: Input: nums = [1,0,0,1,0,1], k = 2 Output: 1 Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. Example 2: Input: nums = [1,0,0,0,0,0,1,1], k = 3 Output: 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. Example 3: Input: nums = [1,1,0,1], k = 2 Output: 0 Explanation: nums already has 2 consecutive 1's.   Constraints: 1 <= nums.length <= 100000 nums[i] is 0 or 1. 1 <= k <= sum(nums)
class Solution: def minMoves(self, s: List[int], k: int) -> int: N = len(s) left_index = 0 right_index = 0 # the count of 0's that are closer to the left (with number of 1's as the distance) queue_left = collections.deque([0] * (k // 2)) # the sum of distances to the left border sum_left = 0 # the count of 0's that are on this half count_left = 0 # the count of 0's that are closer to the right queue_right = collections.deque([0] * ((k - 1) // 2)) sum_right = 0 count_right = 0 # number of ones in the sliding window num_ones = 0 # keeps track of the min best = 1000000000000 # current number of zeroes that are trailing, until we hit a "1" run_total = 0 # sliding window while right_index < N: if s[right_index] == 1: # number of ones num_ones += 1 # process the current run of zeroes queue_right.append(run_total) count_right += run_total # as we process a "1", the weight of every number goes up by one sum_right += count_right # the right goes over to the left -> so now these zeroes are closer to the left border than the right border shifting_zeroes = queue_right[0] count_right -= shifting_zeroes sum_right -= shifting_zeroes * ((k - 1) // 2) sum_left += shifting_zeroes * (k // 2) count_left += shifting_zeroes queue_left.append(shifting_zeroes) queue_right.popleft() # if we see a new "1", that means that one of the old "1"s will be gone, assuming we have enough "1"s sum_left -= count_left count_left -= queue_left[0] queue_left.popleft() # reset zeroes run_total = 0 else: run_total += 1 while num_ones > k: if s[left_index] == 1: num_ones -= 1 left_index += 1 while s[left_index] == 0: left_index += 1 if num_ones == k: # the cost is just the sum of cost left and cost right cost = sum_left + sum_right best = min(best, cost) right_index += 1 return best
71d815
8ecb46
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's.   Example 1: Input: nums = [1,0,0,1,0,1], k = 2 Output: 1 Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. Example 2: Input: nums = [1,0,0,0,0,0,1,1], k = 3 Output: 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. Example 3: Input: nums = [1,1,0,1], k = 2 Output: 0 Explanation: nums already has 2 consecutive 1's.   Constraints: 1 <= nums.length <= 100000 nums[i] is 0 or 1. 1 <= k <= sum(nums)
class Solution(object): def minMoves(self, A, k): A = [i for i, a in enumerate(A) if a] n = len(A) B = [0] * (n + 1) res = float('inf') for i in xrange(n): B[i + 1] = B[i] + A[i] for i in xrange(len(A) - k + 1): m1, m2 = (k - 1) / 2 + i, k / 2 + i cur = (B[i + k] - B[m2]) - (B[m1 + 1] - B[i]) res = min(res, cur) if k % 2 == 1: res -= (k / 2 + 1) * (k / 2) if k % 2 == 0: res -= (k / 2)**2 return res
a1dbaf
593298
Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions. The score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4. Example 1: Input: grid = [[5,4,5],[1,2,6],[7,4,6]] Output: 4 Explanation: The path with the maximum score is highlighted in yellow. Example 2: Input: grid = [[2,2,1,2,2,2],[1,2,2,2,1,2]] Output: 2 Example 3: Input: grid = [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 0 <= grid[i][j] <= 10^9
from heapq import * # Solution class Solution: def maximumMinimumPath(self, A: List[List[int]]) -> int: R = len(A) C = len(A[0]) if R == 1 and C == 1: return A[0][0] q = [(-A[0][0], 0, 0)] best_score = [[-math.inf]*C for _ in range(R)] best_score[0][0] = A[0][0] while q: sc, r, c = heappop(q) sc = -sc if best_score[r][c] > sc: continue if r == R-1 and c == C-1: return sc for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)): nr, nc = r + dr, c + dc if 0 <= nr < R and 0 <= nc < C: new_score = min(A[nr][nc], best_score[r][c]) if new_score > best_score[nr][nc]: best_score[nr][nc] = new_score heappush(q, (-new_score, nr, nc))
be63d8
593298
Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions. The score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4. Example 1: Input: grid = [[5,4,5],[1,2,6],[7,4,6]] Output: 4 Explanation: The path with the maximum score is highlighted in yellow. Example 2: Input: grid = [[2,2,1,2,2,2],[1,2,2,2,1,2]] Output: 2 Example 3: Input: grid = [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 0 <= grid[i][j] <= 10^9
class Solution(object): def maximumMinimumPath(self, A): """ :type A: List[List[int]] :rtype: int """ R,C = len(A), len(A[0]) h = [[-A[0][0],0,0]] res = 10**9 seen = set((0, 0)) while True: score, x0, y0 = heapq.heappop(h) res = min(res, -score) if (x0, y0) == (R - 1, C - 1): return res for i,j in [[1,0],[-1,0],[0,1],[0,-1]]: x, y = x0 + i, y0 + j if 0<=x<R and 0<=y<C and (x,y) not in seen: heapq.heappush(h, [-A[x][y],x,y]) seen.add((x,y))
f75531
f1c4ac
You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops Return the lexicographically largest string after cutting the loop, which will make the looped string into a regular one. Specifically, to find the lexicographically largest string, you need to experience two phases: Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given. Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint. And your job is to find the lexicographically largest one among all the possible regular strings. Example 1: Input: strs = ["abc","xyz"] Output: "zyxcba" Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", where '-' represents the looped status. The answer string came from the fourth looped one, where you could cut from the middle character 'a' and get "zyxcba". Example 2: Input: strs = ["abc"] Output: "cba" Constraints: 1 <= strs.length <= 1000 1 <= strs[i].length <= 1000 1 <= sum(strs[i].length) <= 1000 strs[i] consists of lowercase English letters.
class Solution(object): def splitLoopedString(self, strs): """ :type strs: List[str] :rtype: str """ strs = map(lambda x: max(x, x[::-1]), strs) answer = '\x00' for i in xrange(len(strs)): before = ''.join(strs[:i]) after = ''.join(strs[i+1:]) s = strs[i] rs = s[::-1] for cut in xrange(len(s)): answer = max(answer, s[cut:] + after + before + s[:cut]) answer = max(answer, rs[cut:] + after + before + rs[:cut]) return answer
8441a5
90f933
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0.   Example 1: Input: mat = [[0,0],[0,1]] Output: 3 Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown. Example 2: Input: mat = [[0]] Output: 0 Explanation: Given matrix is a zero matrix. We do not need to change it. Example 3: Input: mat = [[1,0,0],[1,0,0]] Output: -1 Explanation: Given matrix cannot be a zero matrix.   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 3 mat[i][j] is either 0 or 1.
class Solution(object): def minFlips(self, A): R, C = len(A), len(A[0]) N = R*C ans = N + 1 for cand in itertools.product(range(2), repeat = N): bns = sum(cand) if bns >= ans: continue r=c= 0 B = [row[:] for row in A] for adj in cand: if adj: B[r][c] ^= 1 for nr, nc in ((r-1,c), (r, c-1), (r, c+1), (r+1, c)): if 0 <= nr < R and 0 <= nc < C: B[nr][nc] ^= 1 c += 1 if c == C: c = 0 r += 1 if sum(sum(row) for row in B) == 0: ans = bns return ans if ans < N+1 else -1
0717d4
90f933
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0.   Example 1: Input: mat = [[0,0],[0,1]] Output: 3 Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown. Example 2: Input: mat = [[0]] Output: 0 Explanation: Given matrix is a zero matrix. We do not need to change it. Example 3: Input: mat = [[1,0,0],[1,0,0]] Output: -1 Explanation: Given matrix cannot be a zero matrix.   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 3 mat[i][j] is either 0 or 1.
class Solution: def minFlips(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) dirs = [(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)] ans = m * n + 1 for i in range(1 << (m * n)): mm = [x[:] for x in mat] cur = 0 open = 0 for j in range(m): for k in range(n): if ((i >> cur) & 1) == 1: open += 1 for dx, dy in dirs: x, y = j + dx, k + dy if 0 <= x < m and 0 <= y < n: mm[x][y] = 1 - mm[x][y] cur += 1 judge = True for j in range(m): for k in range(n): if mm[j][k] != 0: judge = False if judge: ans = min(ans, open) if ans == m * n + 1: ans = -1 return ans
73872e
299024
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events.   Example 1: Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 Output: 7 Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. Example 3: Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 Output: 9 Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.   Constraints: 1 <= k <= events.length 1 <= k * events.length <= 1000000 1 <= startDayi <= endDayi <= 10^9 1 <= valuei <= 1000000
from bisect import bisect_left class Solution(object): def maxValue(self, events, k): """ :type events: List[List[int]] :type k: int :rtype: int """ n=len(events) arr=sorted(events,key=lambda x:x[1]) l=[0]+[arr[i][1] for i in range(n)] dp=[[0 for i in range(k+1)]for j in range(n+1)] for i in range(1,n+1): pos=bisect_left(l,arr[i-1][0])-1 for j in range(1,k+1): dp[i][j]=dp[i-1][j] dp[i][j]=max(dp[i][j],dp[pos][j-1]+arr[i-1][2]) return max(dp[-1])
a07c3e
299024
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events.   Example 1: Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 Output: 7 Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. Example 3: Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 Output: 9 Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.   Constraints: 1 <= k <= events.length 1 <= k * events.length <= 1000000 1 <= startDayi <= endDayi <= 10^9 1 <= valuei <= 1000000
class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: n = len(events) dp = [0] * (n + 1) ret = 0 events = sorted([end, begin, v] for begin, end, v in events) for i in range(1, k + 1): ndp = [0] * (n + 1) for j in range(n): p = bisect_right(events, [events[j][1] - 1, math.inf]) ndp[j] = max(ndp[j - 1], dp[p - 1] + events[j][2]) ret = max(ret, ndp[j]) dp = ndp return ret
47a5f4
bc2758
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.   Example 1: Input: start = "RXXLRXRXL", end = "XRLXXRRLX" Output: true Explanation: We can transform start to end following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX Example 2: Input: start = "X", end = "L" Output: false   Constraints: 1 <= start.length <= 10000 start.length == end.length Both start and end will only consist of characters in 'L', 'R', and 'X'.
class Solution(object): def canTransform(self, start, end): """ :type start: str :type end: str :rtype: bool """ def rx(s): return ''.join(s.split('X')) def plc(s): al=[] ar=[] for i,c in enumerate(s): if c=='L': al.append(i) elif c=='R': ar.append(i) return [al,ar] if rx(start)!=rx(end): return False sl,sr=plc(start) el,er=plc(end) for i in range(len(sl)): if el[i]>sl[i]: return False for i in range(len(sr)): if er[i]<sr[i]: return False return True
c22c50
bc2758
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.   Example 1: Input: start = "RXXLRXRXL", end = "XRLXXRRLX" Output: true Explanation: We can transform start to end following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX Example 2: Input: start = "X", end = "L" Output: false   Constraints: 1 <= start.length <= 10000 start.length == end.length Both start and end will only consist of characters in 'L', 'R', and 'X'.
class Solution: def canTransform(self, start, end): """ :type start: str :type end: str :rtype: bool """ def process(s): ans = "" id = [] for i in range(len(s)): c = s[i] if c != "X": ans = ans + c id.append(i) return ans, id f_start, id_start = process(start) f_end, id_end = process(end) if f_start != f_end: return False for i in range(len(f_start)): if f_start[i] == "L" and id_start[i] < id_end[i]: return False if f_start[i] == "R" and id_start[i] > id_end[i]: return False return True
c4883a
27a412
Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr. int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right]. A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).   Example 1: Input ["RangeFreqQuery", "query", "query"] [[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]] Output [null, 1, 2] Explanation RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]); rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4] rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i], value <= 10000 0 <= left <= right < arr.length At most 100000 calls will be made to query
class RangeFreqQuery: def __init__(self, arr: List[int]): n = len(arr) self.dic = collections.defaultdict(list) for i,v in enumerate(arr): self.dic[v] += [i] def query(self, left: int, right: int, v: int) -> int: indl = bisect.bisect_left(self.dic[v], left) indr = bisect.bisect_right(self.dic[v], right) return indr - indl # Your RangeFreqQuery object will be instantiated and called as such: # obj = RangeFreqQuery(arr) # param_1 = obj.query(left,right,value)
ae6555
27a412
Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr. int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right]. A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).   Example 1: Input ["RangeFreqQuery", "query", "query"] [[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]] Output [null, 1, 2] Explanation RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]); rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4] rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.   Constraints: 1 <= arr.length <= 100000 1 <= arr[i], value <= 10000 0 <= left <= right < arr.length At most 100000 calls will be made to query
class RangeFreqQuery(object): def __init__(self, arr): """ :type arr: List[int] """ vs = {} for i, v in enumerate(arr): if v not in vs: vs[v]=[] vs[v].append(i) self.ix = vs def query(self, left, right, value): """ :type left: int :type right: int :type value: int :rtype: int """ if value not in self.ix: return 0 a = self.ix[value] return bisect_right(a, right)-bisect_left(a, left) # Your RangeFreqQuery object will be instantiated and called as such: # obj = RangeFreqQuery(arr) # param_1 = obj.query(left,right,value)
b10bb9
ee4c89
There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.    Example 1: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 Output: ["B","C"] Explanation: You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = ["C"]  Person with id = 2 -> watchedVideos = ["B","C"]  The frequencies of watchedVideos by your friends are:  B -> 1  C -> 2 Example 2: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 Output: ["D"] Explanation: You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).   Constraints: n == watchedVideos.length == friends.length 2 <= n <= 100 1 <= watchedVideos[i].length <= 100 1 <= watchedVideos[i][j].length <= 8 0 <= friends[i].length < n 0 <= friends[i][j] < n 0 <= id < n 1 <= level < n if friends[i] contains j, then friends[j] contains i
class Solution(object): def watchedVideosByFriends(self, watchedVideos, friends, uid, level): seen = {uid} queue = collections.deque([(uid, 0)]) plaque = set() while queue: node, d = queue.popleft() if d > level: break if d == level: plaque.add(node) for nei in friends[node]: if nei not in seen: seen.add(nei) queue.append((nei, d+1)) count = collections.Counter() for node in plaque: for video in watchedVideos[node]: count[video] += 1 items = count.items() items.sort(key = lambda (k,v): (v, k)) return [k for k,v in items]
af4764
ee4c89
There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.    Example 1: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 Output: ["B","C"] Explanation: You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = ["C"]  Person with id = 2 -> watchedVideos = ["B","C"]  The frequencies of watchedVideos by your friends are:  B -> 1  C -> 2 Example 2: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 Output: ["D"] Explanation: You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).   Constraints: n == watchedVideos.length == friends.length 2 <= n <= 100 1 <= watchedVideos[i].length <= 100 1 <= watchedVideos[i][j].length <= 8 0 <= friends[i].length < n 0 <= friends[i][j] < n 0 <= id < n 1 <= level < n if friends[i] contains j, then friends[j] contains i
class Solution: def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], myId: int, level: int) -> List[str]: n = len(watchedVideos) INF = n * 10 + 100 dist = [INF] * n dist[myId] = 0 q = collections.deque([myId]) while q: v = q.popleft() if dist[v] > level: break for t in friends[v]: if dist[t] == INF: dist[t] = dist[v] + 1 q.append(t) count = collections.defaultdict(int) for i in range(n): if dist[i] == level: for x in watchedVideos[i]: count[x] += 1 ans = [] for x in count: ans.append((count[x], x)) ans.sort() return [x[1] for x in ans]
1b834b
2a3569
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length. Return the minimum total space wasted if you can resize the array at most k times. Note: The array can have any size at the start and does not count towards the number of resizing operations.   Example 1: Input: nums = [10,20], k = 0 Output: 10 Explanation: size = [20,20]. We can set the initial size to be 20. The total wasted space is (20 - 10) + (20 - 20) = 10. Example 2: Input: nums = [10,20,30], k = 1 Output: 10 Explanation: size = [20,20,30]. We can set the initial size to be 20 and resize to 30 at time 2. The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10. Example 3: Input: nums = [10,20,15,30,20], k = 2 Output: 15 Explanation: size = [10,20,20,30,30]. We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3. The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.   Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1000000 0 <= k <= nums.length - 1
class Solution: def minSpaceWastedKResizing(self, A, K): N = len(A) @cache def dp(i, rem): if i >= N: return 0 if rem == 0: s = 0 m = -inf t = 0 for j in range(i, N): s += A[j] m = max(m, A[j]) t += 1 return m * t - s s = t = 0 m = -inf ans = inf for j in range(i, N): s += A[j] t += 1 m = max(m, A[j]) # print("i rem", i, rem, "j", j, "m t s", m, t, s, 'of ', dp(j + 1, rem - 1)) ans = min(ans, m * t - s + dp(j + 1, rem - 1)) return ans # print(dp(2, 0)) return dp(0, K)
713408
2a3569
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length. Return the minimum total space wasted if you can resize the array at most k times. Note: The array can have any size at the start and does not count towards the number of resizing operations.   Example 1: Input: nums = [10,20], k = 0 Output: 10 Explanation: size = [20,20]. We can set the initial size to be 20. The total wasted space is (20 - 10) + (20 - 20) = 10. Example 2: Input: nums = [10,20,30], k = 1 Output: 10 Explanation: size = [20,20,30]. We can set the initial size to be 20 and resize to 30 at time 2. The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10. Example 3: Input: nums = [10,20,15,30,20], k = 2 Output: 15 Explanation: size = [10,20,20,30,30]. We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3. The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.   Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1000000 0 <= k <= nums.length - 1
class Solution(object): def minSpaceWastedKResizing(self, A, k): memo = {} n = len(A) def dp(i, k): if (i,k) in memo: return memo[i,k] if i == n: return 0 if k == 0: memo[i,k] = max(A[i:]) * (n - i) - sum(A[i:]) return memo[i,k] res = float('inf') su = ma = 0 for j in xrange(i, n): su += A[j] ma = max(ma, A[j]) res = min(res, ma * (j - i + 1) - su + dp(j+1, k - 1)) memo[i,k] = res return res return dp(0, k)
28b4d2
d1a357
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).   Example 1: Input: grid = [[0,2],[1,3]] Output: 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. Example 2: Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] Output: 16 Explanation: The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected.   Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 0 <= grid[i][j] < n2 Each value grid[i][j] is unique.
from bisect import * class Solution(object): def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ n=len(grid) m=n*n ans=max(grid[0][0],grid[n-1][n-1]) if ans==n*n-1: return n*n-1 used=[False]*m used[grid[0][0]]=True cand=[] di=[0,1,0,-1] dj=[1,0,-1,0] b=[[0,0]] i=0 while i<len(b): x,y=b[i] for k in range(4): nx,ny=x+di[k],y+dj[k] if nx==n-1 and ny==n-1: return ans if nx<0 or nx>=n or ny<0 or ny>=n or used[grid[nx][ny]]: continue insort_left(cand,[grid[nx][ny],nx,ny]) if cand: b.append(cand[0][1:]) ans=max(ans,cand[0][0]) used[cand[0][0]]=True del cand[0] i+=1 return ans
ea2e23
d1a357
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).   Example 1: Input: grid = [[0,2],[1,3]] Output: 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. Example 2: Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] Output: 16 Explanation: The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected.   Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 0 <= grid[i][j] < n2 Each value grid[i][j] is unique.
class Solution: def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ def get_father(x, y): if father[x][y] == (x, y): return father[x][y] father[x][y] = get_father(father[x][y][0], father[x][y][1]) return father[x][y] def hebing(a, b): if get_father(a[0], a[1]) == get_father(b[0], b[1]): return a = get_father(a[0], a[1]) b = get_father(b[0], b[1]) father[a[0]][a[1]] = b WEI = [[-1, 0], [0, -1], [1, 0], [0, 1]] pos = {} m = len(grid) n = len(grid[0]) for i in range(m): for j in range(n): pos[grid[i][j]] = (i, j) father = [] for i in range(m): new_list = [] for j in range(n): new_list.append((i, j)) father.append(new_list) for i in range(m * n): x, y = pos[i] for j in range(4): tx = x + WEI[j][0] ty = y + WEI[j][1] if tx >= 0 and tx < m and ty >= 0 and ty < n: if grid[tx][ty] <= i: hebing((x, y), (tx, ty)) if get_father(0, 0) == get_father(m - 1, n - 1): return i
a055d8
197982
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. Any student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7.   Example 1: Input: n = 2 Output: 8 Explanation: There are 8 records with length 2 that are eligible for an award: "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL" Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2). Example 2: Input: n = 1 Output: 3 Example 3: Input: n = 10^101 Output: 183236316   Constraints: 1 <= n <= 100000
class Solution(object): def checkRecord(self, N): MOD = 10**9 + 7 # no A, ends in not L 3 0 1 # no A, ends in notL, L 3 0 2 # no A, ends in L , L 3 0 # one A, ends in not L 3 4 # one A, ends in notL, L 3 5 # one A, ends in LL 3 dp0 = dp1 = dp2 = dp3 = dp4 = dp5 = 0 np0 = np1 = np2 = np3 = np4 = np5 = 0 dp0 = dp1 = dp3 = 1 for _ in xrange(N-1): np0 = np1 = np2 = np3 = np4 = np5 = 0 np3 += dp0 + dp1 + dp2 + dp3 + dp4 + dp5 np0 += dp0 + dp1 + dp2 np1 += dp0 np2 += dp1 np4 += dp3 np5 += dp4 np0 %= MOD np1 %= MOD np2 %= MOD np3 %= MOD np4 %= MOD np5 %= MOD dp0,dp1,dp2,dp3,dp4,dp5 = np0,np1,np2,np3,np4,np5 return (dp0 + dp1 + dp2 + dp3 + dp4 + dp5) % MOD
7c96a2
21018c
Design a food rating system that can do the following: Modify the rating of a food item listed in the system. Return the highest-rated food item for a type of cuisine in the system. Implement the FoodRatings class: FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. foods[i] is the name of the ith food, cuisines[i] is the type of cuisine of the ith food, and ratings[i] is the initial rating of the ith food. void changeRating(String food, int newRating) Changes the rating of the food item with the name food. String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.   Example 1: Input ["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] [[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] Output [null, "kimchi", "ramen", null, "sushi", null, "ramen"] Explanation FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); foodRatings.highestRated("korean"); // return "kimchi" // "kimchi" is the highest rated korean food with a rating of 9. foodRatings.highestRated("japanese"); // return "ramen" // "ramen" is the highest rated japanese food with a rating of 14. foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. foodRatings.highestRated("japanese"); // return "sushi" // "sushi" is the highest rated japanese food with a rating of 16. foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. foodRatings.highestRated("japanese"); // return "ramen" // Both "sushi" and "ramen" have a rating of 16. // However, "ramen" is lexicographically smaller than "sushi".   Constraints: 1 <= n <= 2 * 10000 n == foods.length == cuisines.length == ratings.length 1 <= foods[i].length, cuisines[i].length <= 10 foods[i], cuisines[i] consist of lowercase English letters. 1 <= ratings[i] <= 10^8 All the strings in foods are distinct. food will be the name of a food item in the system across all calls to changeRating. cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated. At most 2 * 10000 calls in total will be made to changeRating and highestRated.
from collections import defaultdict from typing import List from sortedcontainers import SortedList class FoodRatings: def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): self.food_to_cr = {} self.cuisine_to_fr = defaultdict(SortedList) for f, c, r in zip(foods, cuisines, ratings): self.food_to_cr[f] = [r, c] self.cuisine_to_fr[c].add((-r, f)) def changeRating(self, food: str, newRating: int) -> None: old, c = self.food_to_cr[food] self.food_to_cr[food][0] = newRating self.cuisine_to_fr[c].remove((-old, food)) self.cuisine_to_fr[c].add((-newRating, food)) def highestRated(self, cuisine: str) -> str: return self.cuisine_to_fr[cuisine][0][1] # Your FoodRatings object will be instantiated and called as such: # obj = FoodRatings(foods, cuisines, ratings) # obj.changeRating(food,newRating) # param_2 = obj.highestRated(cuisine)
a0b1e0
21018c
Design a food rating system that can do the following: Modify the rating of a food item listed in the system. Return the highest-rated food item for a type of cuisine in the system. Implement the FoodRatings class: FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. foods[i] is the name of the ith food, cuisines[i] is the type of cuisine of the ith food, and ratings[i] is the initial rating of the ith food. void changeRating(String food, int newRating) Changes the rating of the food item with the name food. String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.   Example 1: Input ["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] [[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] Output [null, "kimchi", "ramen", null, "sushi", null, "ramen"] Explanation FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); foodRatings.highestRated("korean"); // return "kimchi" // "kimchi" is the highest rated korean food with a rating of 9. foodRatings.highestRated("japanese"); // return "ramen" // "ramen" is the highest rated japanese food with a rating of 14. foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. foodRatings.highestRated("japanese"); // return "sushi" // "sushi" is the highest rated japanese food with a rating of 16. foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. foodRatings.highestRated("japanese"); // return "ramen" // Both "sushi" and "ramen" have a rating of 16. // However, "ramen" is lexicographically smaller than "sushi".   Constraints: 1 <= n <= 2 * 10000 n == foods.length == cuisines.length == ratings.length 1 <= foods[i].length, cuisines[i].length <= 10 foods[i], cuisines[i] consist of lowercase English letters. 1 <= ratings[i] <= 10^8 All the strings in foods are distinct. food will be the name of a food item in the system across all calls to changeRating. cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated. At most 2 * 10000 calls in total will be made to changeRating and highestRated.
from sortedcontainers import SortedSet class FoodRatings(object): def __init__(self, foods, cuisines, ratings): """ :type foods: List[str] :type cuisines: List[str] :type ratings: List[int] """ self.f, self.c = {}, defaultdict(SortedSet) for i in range(len(foods)): self.f[foods[i]] = (-ratings[i], foods[i], cuisines[i]) self.c[cuisines[i]].add((-ratings[i], foods[i], cuisines[i])) def changeRating(self, food, newRating): """ :type food: str :type newRating: int :rtype: None """ self.c[self.f[food][2]].discard(self.f[food]) self.f[food] = (-newRating, food, self.f[food][2]) self.c[self.f[food][2]].add(self.f[food]) def highestRated(self, cuisine): """ :type cuisine: str :rtype: str """ return self.c[cuisine][0][1] # Your FoodRatings object will be instantiated and called as such: # obj = FoodRatings(foods, cuisines, ratings) # obj.changeRating(food,newRating) # param_2 = obj.highestRated(cuisine)
469738
091402
A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s. For example, [0,1,2] and [0,0,1,1,1,2] are special. In contrast, [2,1,0], [1], and [0,1,2,0] are not special. Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.   Example 1: Input: nums = [0,1,2,2] Output: 3 Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2]. Example 2: Input: nums = [2,2,0,0] Output: 0 Explanation: There are no special subsequences in [2,2,0,0]. Example 3: Input: nums = [0,1,2,0,1,2] Output: 7 Explanation: The special subsequences are bolded: - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2]   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 2
class Solution: def countSpecialSubsequences(self, nums: List[int]) -> int: a = b = c = 0 for i in nums[::-1]: if i == 2: c = 2*c+1 elif i == 1: b += b+c else: a += a+b return a%(10**9+7)
c53b7f
091402
A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s. For example, [0,1,2] and [0,0,1,1,1,2] are special. In contrast, [2,1,0], [1], and [0,1,2,0] are not special. Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.   Example 1: Input: nums = [0,1,2,2] Output: 3 Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2]. Example 2: Input: nums = [2,2,0,0] Output: 0 Explanation: There are no special subsequences in [2,2,0,0]. Example 3: Input: nums = [0,1,2,0,1,2] Output: 7 Explanation: The special subsequences are bolded: - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2] - [0,1,2,0,1,2]   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 2
class Solution(object): def countSpecialSubsequences(self, nums): """ :type nums: List[int] :rtype: int """ mod = 1000000007 dp1, dp2, dp3 = [0], [0], [0] for num in nums: if num == 0: dp1.append((2*dp1[-1]+1)%mod) elif num == 1: dp2.append((2*dp2[-1]+dp1[-1])%mod) else: dp3.append((2*dp3[-1]+dp2[-1])%mod) return dp3[-1]
0e6f13
d33328
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges.   Example 1: Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Nodes 0, 1, and 2 do not have any ancestors. - Node 3 has two ancestors 0 and 1. - Node 4 has two ancestors 0 and 2. - Node 5 has three ancestors 0, 1, and 3. - Node 6 has five ancestors 0, 1, 2, 3, and 4. - Node 7 has four ancestors 0, 1, 2, and 3. Example 2: Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Node 0 does not have any ancestor. - Node 1 has one ancestor 0. - Node 2 has two ancestors 0 and 1. - Node 3 has three ancestors 0, 1, and 2. - Node 4 has four ancestors 0, 1, 2, and 3.   Constraints: 1 <= n <= 1000 0 <= edges.length <= min(2000, n * (n - 1) / 2) edges[i].length == 2 0 <= fromi, toi <= n - 1 fromi != toi There are no duplicate edges. The graph is directed and acyclic.
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: from collections import deque def cycle_detectable_topological_sort(g, ind): V = len(g) order = [] depth = [-1]*V for i in range(V): if not ind[i]: order.append(i) depth[i] = 0 q = deque(order) while q: v = q.popleft() cur_depth = depth[v] for u in g[v]: ind[u] -= 1 if not ind[u]: depth[u] = max(depth[u], cur_depth+1) q.append(u) order.append(u) if len(order) == V: return (order, depth) else: return (None, None) ind = [0]*n g = [[] for i in range(n)] for u,v in edges: g[u].append(v) ind[v] += 1 order, _ = cycle_detectable_topological_sort(g, ind) print(order) ans = [set() for i in range(n)] for v in order: for u in g[v]: ans[u] |= (ans[v]|{v}) ans = [sorted(list(l)) for l in ans] return ans
d77c6c
d33328
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges.   Example 1: Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Nodes 0, 1, and 2 do not have any ancestors. - Node 3 has two ancestors 0 and 1. - Node 4 has two ancestors 0 and 2. - Node 5 has three ancestors 0, 1, and 3. - Node 6 has five ancestors 0, 1, 2, 3, and 4. - Node 7 has four ancestors 0, 1, 2, and 3. Example 2: Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Node 0 does not have any ancestor. - Node 1 has one ancestor 0. - Node 2 has two ancestors 0 and 1. - Node 3 has three ancestors 0, 1, and 2. - Node 4 has four ancestors 0, 1, 2, and 3.   Constraints: 1 <= n <= 1000 0 <= edges.length <= min(2000, n * (n - 1) / 2) edges[i].length == 2 0 <= fromi, toi <= n - 1 fromi != toi There are no duplicate edges. The graph is directed and acyclic.
class Solution(object): def getAncestors(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[List[int]] """ nc = [0]*n nei = [set() for _ in range(n)] for a, b in edges: if b in nei[a]: continue nc[b]+=1 nei[a].add(b) r = [set() for _ in range(n)] q = deque() for i in range(n): if nc[i]==0: q.append(i) while q: a=q.popleft() for b in nei[a]: r[b].add(a) for c in r[a]: r[b].add(c) nc[b]-=1 if nc[b]==0: q.append(b) rr = [list(a) for a in r] for a in rr: a.sort() return rr
ca3cd5
662850
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer.   (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Input: head = [1,2,-3,3,1] Output: [3,1] Note: The answer [1,2,1] would also be accepted. Example 2: Input: head = [1,2,3,-3,4] Output: [1,2,4] Example 3: Input: head = [1,2,3,-3,-2] Output: [1]   Constraints: The given linked list will contain between 1 and 1000 nodes. Each node in the linked list has -1000 <= node.val <= 1000.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None def to_list(h): ans = [] while h: ans.append(h.val) h = h.next return ans def to_link(l): n = ListNode(None) h = n for node in l: n.next = ListNode(node) n = n.next return h.next class Solution(object): def removeZeroSumSublists(self, head): """ :type head: ListNode :rtype: ListNode """ l = to_list(head) ans = list() for n in l: ans.append(n) s = 0 for k in reversed(xrange(len(ans))): s += ans[k] if s == 0: ans = ans[:k] break return to_link(ans)
91d932
662850
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer.   (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Input: head = [1,2,-3,3,1] Output: [3,1] Note: The answer [1,2,1] would also be accepted. Example 2: Input: head = [1,2,3,-3,4] Output: [1,2,4] Example 3: Input: head = [1,2,3,-3,-2] Output: [1]   Constraints: The given linked list will contain between 1 and 1000 nodes. Each node in the linked list has -1000 <= node.val <= 1000.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: sum_dict = {} start_pointer = ListNode(0) start_pointer.next = head p = start_pointer s = 0 while p: s += p.val if s not in sum_dict: sum_dict[s] = p else: sum_dict[s].next = p.next p = p.next return start_pointer.next
b00194
ba2f98
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.   Example 1: Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". Example 2: Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".   Constraints: 1 <= k <= s.length <= 1000 s consist of lowercase English letters.
class Solution(object): def orderlyQueue(self, S, K): """ :type S: str :type K: int :rtype: str """ if K == 1: return min(S[i:] + S[:i] for i in range(len(S))) return "".join(sorted(S))
07944e
ba2f98
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.   Example 1: Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". Example 2: Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".   Constraints: 1 <= k <= s.length <= 1000 s consist of lowercase English letters.
class Solution: def orderlyQueue(self, S, K): """ :type S: str :type K: int :rtype: str """ n = len(S) if K > 1: s = sorted(S) ans = "" for c in s: ans += c return ans s = S a = [] for i in range(n): x = s[0] s = s[1:] + x a.append(s) return sorted(a)[0]
bf9cc8
3dc463
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.   Example 1: Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5 Example 2: Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4   Constraints: n == arr.length 1 <= n <= 100000 1 <= arr[i] <= 100000
from collections import Counter class Solution(object): def getDistances(self, arr): """ :type arr: List[int] :rtype: List[int] """ n = len(arr) r = [0] * n cnt = Counter() tot = Counter() for i in xrange(n): v = arr[i] r[i] += cnt[v]*i - tot[v] cnt[v] += 1 tot[v] += i cnt = Counter() tot = Counter() for i in xrange(n-1, -1, -1): v = arr[i] r[i] += tot[v] - cnt[v]*i cnt[v] += 1 tot[v] += i return r
66b006
3dc463
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.   Example 1: Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5 Example 2: Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4   Constraints: n == arr.length 1 <= n <= 100000 1 <= arr[i] <= 100000
class Solution: def getDistances(self, arr: List[int]) -> List[int]: v2list = collections.defaultdict(list) for i, v in enumerate(arr) : v2list[v].append(i) to_ret = [0] * len(arr) for v in v2list : lt = v2list[v] rlt = sum(lt) llt = 0 nv = len(lt) for it in lt : to_ret[it] = rlt - it * nv - llt nv -= 2 rlt -= it llt += it return to_ret
9559ec
db1007
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix.   Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. Example 3: Input: matrix = [[5,2],[1,6]], k = 3 Output: 4 Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 0 <= matrix[i][j] <= 1000000 1 <= k <= m * n
class Solution(object): def kthLargestValue(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ m=len(matrix) n = len(matrix[0]) save = [] for i in range(m): c = 0 for j in range(n): c ^= matrix[i][j] if i == 0: matrix[i][j] = c else: matrix[i][j] = matrix[i-1][j] ^ c save.append(matrix[i][j]) save.sort() return save[-k]
719758
db1007
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix.   Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. Example 3: Input: matrix = [[5,2],[1,6]], k = 3 Output: 4 Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 0 <= matrix[i][j] <= 1000000 1 <= k <= m * n
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) for i in range(m) : for j in range(1, n) : matrix[i][j] = matrix[i][j] ^ matrix[i][j-1] for i in range(1, m) : for j in range(n) : matrix[i][j] = matrix[i][j] ^ matrix[i-1][j] line = sorted([t for a in matrix for t in a]) return line[-k]
857691
f8b92c
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers.   Example 1: Input: n = "123" Output: "121" Example 2: Input: n = "1" Output: "0" Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.   Constraints: 1 <= n.length <= 18 n consists of only digits. n does not have leading zeros. n is representing an integer in the range [1, 10^18 - 1].
class Solution(object): def nearestPalindromic(self, n): """ :type n: str :rtype: str """ def getpalin(seed, targetLen): digits = list(str(seed))[:targetLen] digits += ['0'] * (targetLen-len(digits)) for i in xrange(targetLen//2): digits[targetLen-i-1] = digits[i] return int(''.join(digits)) def palinabove(seed, targetLen): newseed, newTargetLen = seed+1, targetLen if len(str(newseed)) > len(str(seed)): newTargetLen += 1 return getpalin(newseed, newTargetLen) def palinbelow(seed, targetLen): if seed == 0: return None if seed == 1 and targetLen == 2: return 9 newseed, newTargetLen = seed-1, targetLen if len(str(newseed)) < len(str(seed)): newTargetLen -= 1 if newTargetLen % 2: newseed = 10*newseed + 9 return getpalin(newseed, newTargetLen) targetLen = len(n) seed = int(n[:(len(n)+1)//2]) n = int(n) candidates = [] for x in getpalin(seed, targetLen), palinabove(seed, targetLen), palinbelow(seed, targetLen): if x is not None and x != n: candidates.append((abs(x-n), x)) return str(min(candidates)[1])
577f67
9e4234
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots.   Example 1: Input: values = [8,1,5,2,6] Output: 11 Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11 Example 2: Input: values = [1,2] Output: 2   Constraints: 2 <= values.length <= 5 * 10000 1 <= values[i] <= 1000
class Solution: def maxScoreSightseeingPair(self, A: List[int]) -> int: max_val = max(A[0] + 0, A[1] + 1) ans = A[0] + A[1] + 0 - 1 for j, x in enumerate(A): if j < 2: continue ans = max(ans, A[j] - j + max_val) max_val = max(max_val, A[j] + j) return ans
5e80a3
9e4234
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots.   Example 1: Input: values = [8,1,5,2,6] Output: 11 Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11 Example 2: Input: values = [1,2] Output: 2   Constraints: 2 <= values.length <= 5 * 10000 1 <= values[i] <= 1000
class Solution(object): def maxScoreSightseeingPair(self, A): """ :type A: List[int] :rtype: int """ n = len(A) best = float('-inf') ans = float('-inf') for i in range(n): sj = A[i] - i ans = max(ans, best + sj) si = A[i] + i if si > best: best = si return ans
329f7a
288121
You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that: subtexti is a non-empty string. The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text). subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k). Return the largest possible value of k.   Example 1: Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)". Example 2: Input: text = "merchant" Output: 1 Explanation: We can split the string on "(merchant)". Example 3: Input: text = "antaprezatepzapreanta" Output: 11 Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".   Constraints: 1 <= text.length <= 1000 text consists only of lowercase English characters.
class Solution: def longestDecomposition(self, text: str) -> int: memo = {} def helper(a, b): if (a, b) not in memo: n = len(a) ans = 1 for i in range(1, n): if a[:i] == b[:i][::-1]: new = helper(a[i:], b[i:]) ans = max(ans, new + 1) memo[(a, b)] = ans return memo[(a, b)] return helper(text, text[::-1])
8f1a34
288121
You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that: subtexti is a non-empty string. The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text). subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k). Return the largest possible value of k.   Example 1: Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)". Example 2: Input: text = "merchant" Output: 1 Explanation: We can split the string on "(merchant)". Example 3: Input: text = "antaprezatepzapreanta" Output: 11 Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".   Constraints: 1 <= text.length <= 1000 text consists only of lowercase English characters.
class Solution(object): def longestDecomposition(self, text): if len(text) == 1: return 1 k = 0 left = 0 right = len(text)-1 ls, rs = text[left], text[right] while left < right: if ls == rs: k += 2 ls = "" rs = "" left += 1 right -= 1 if left <= right: ls = ls + text[left] rs = text[right] + rs if ls == "" and rs == "": return k return k+1
c2a1c3
21a773
A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.   Example 1: Input: word = "aba" Output: 4 Explanation: The four wonderful substrings are underlined below: - "aba" -> "a" - "aba" -> "b" - "aba" -> "a" - "aba" -> "aba" Example 2: Input: word = "aabb" Output: 9 Explanation: The nine wonderful substrings are underlined below: - "aabb" -> "a" - "aabb" -> "aa" - "aabb" -> "aab" - "aabb" -> "aabb" - "aabb" -> "a" - "aabb" -> "abb" - "aabb" -> "b" - "aabb" -> "bb" - "aabb" -> "b" Example 3: Input: word = "he" Output: 2 Explanation: The two wonderful substrings are underlined below: - "he" -> "h" - "he" -> "e"   Constraints: 1 <= word.length <= 100000 word consists of lowercase English letters from 'a' to 'j'.
class Solution: def wonderfulSubstrings(self, word: str) -> int: mask = 0 masks = [0] for i, x in enumerate(word): mask ^= 1 << (ord(x) - ord('a')) masks.append(mask) freq = Counter() ans = 0 for mask in masks: ans += freq[mask] for i in range(10): ans += freq[mask ^ (1 << i)] freq[mask] += 1 return ans
e5a0f7
21a773
A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.   Example 1: Input: word = "aba" Output: 4 Explanation: The four wonderful substrings are underlined below: - "aba" -> "a" - "aba" -> "b" - "aba" -> "a" - "aba" -> "aba" Example 2: Input: word = "aabb" Output: 9 Explanation: The nine wonderful substrings are underlined below: - "aabb" -> "a" - "aabb" -> "aa" - "aabb" -> "aab" - "aabb" -> "aabb" - "aabb" -> "a" - "aabb" -> "abb" - "aabb" -> "b" - "aabb" -> "bb" - "aabb" -> "b" Example 3: Input: word = "he" Output: 2 Explanation: The two wonderful substrings are underlined below: - "he" -> "h" - "he" -> "e"   Constraints: 1 <= word.length <= 100000 word consists of lowercase English letters from 'a' to 'j'.
class Solution(object): def wonderfulSubstrings(self, word): count = [0] * 1100 count[0] = 1 cur = 0 res = 0 for c in word: i = ord(c) - ord('a') cur ^= 1 << i res += count[cur] for i in xrange(10): cur ^= 1 << i res += count[cur] cur ^= 1 << i count[cur] += 1 return res
80683e
a8068a
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: Adding exactly one letter to the set of the letters of s1. Deleting exactly one letter from the set of the letters of s1. Replacing exactly one letter from the set of the letters of s1 with any letter, including itself. The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: It is connected to at least one other string of the group. It is the only string present in the group. Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: ans[0] is the maximum number of groups words can be divided into, and ans[1] is the size of the largest group.   Example 1: Input: words = ["a","b","ab","cde"] Output: [2,3] Explanation: - words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2]. - words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2]. - words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1]. - words[3] is not connected to any string in words. Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3. Example 2: Input: words = ["a","ab","abc"] Output: [1,3] Explanation: - words[0] is connected to words[1]. - words[1] is connected to words[0] and words[2]. - words[2] is connected to words[1]. Since all strings are connected to each other, they should be grouped together. Thus, the size of the largest group is 3.   Constraints: 1 <= words.length <= 2 * 10000 1 <= words[i].length <= 26 words[i] consists of lowercase English letters only. No letter occurs more than once in words[i].
from collections import Counter class Solution(object): def groupStrings(self, words): """ :type words: List[str] :rtype: List[int] """ c = Counter(sum(1<<(ord(ch)-ord('a')) for ch in w) for w in words) adj = defaultdict(set) for u in c: for i in xrange(26): v = u ^ (1<<i) if v in c and u != v: adj[u].add(v) if v < u: for j in xrange(26): w = v | (1<<j) if w in c and u != w: adj[u].add(w) vis = set() comps = 0 r = 0 for u in c: if u in vis: continue compsize = c[u] vis.add(u) q = [u] while q: u = q.pop() for v in adj[u]: if v not in vis: compsize += c[v] vis.add(v) q.append(v) r = max(r, compsize) comps += 1 return [comps, r]
c10642
a8068a
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: Adding exactly one letter to the set of the letters of s1. Deleting exactly one letter from the set of the letters of s1. Replacing exactly one letter from the set of the letters of s1 with any letter, including itself. The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: It is connected to at least one other string of the group. It is the only string present in the group. Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: ans[0] is the maximum number of groups words can be divided into, and ans[1] is the size of the largest group.   Example 1: Input: words = ["a","b","ab","cde"] Output: [2,3] Explanation: - words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2]. - words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2]. - words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1]. - words[3] is not connected to any string in words. Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3. Example 2: Input: words = ["a","ab","abc"] Output: [1,3] Explanation: - words[0] is connected to words[1]. - words[1] is connected to words[0] and words[2]. - words[2] is connected to words[1]. Since all strings are connected to each other, they should be grouped together. Thus, the size of the largest group is 3.   Constraints: 1 <= words.length <= 2 * 10000 1 <= words[i].length <= 26 words[i] consists of lowercase English letters only. No letter occurs more than once in words[i].
class Solution: def groupStrings(self, words: List[str]) -> List[int]: vis = Counter() exist = Counter() cur = 0 groups = 0 max_group = 0 def try_mask(mask): if exist[mask] > 0 and vis[mask] == 0: dfs(mask) def dfs(mask): nonlocal cur vis[mask] = 1 cur += exist[mask] for i in range(26): if mask & (1 << i): try_mask(mask ^ (1 << i)) for j in range(26): if not (mask & (1 << j)): try_mask(mask ^ (1 << i) ^ (1 << j)) else: try_mask(mask | (1 << i)) for word in words: cnt = Counter(word) mask = 0 for i in range(26): if cnt[chr(ord('a') + i)] != 0: mask |= 1 << i exist[mask] += 1 for mask in exist.keys(): if vis[mask] == 0: cur = 0 dfs(mask) groups += 1 if cur > max_group: max_group = cur return [groups, max_group]
a65510
a681a3
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words. For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters "axyz" matches "xyz" from words. Implement the StreamChecker class: StreamChecker(String[] words) Initializes the object with the strings array words. boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.   Example 1: Input ["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"] [[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]] Output [null, false, false, false, true, false, true, false, false, false, false, false, true] Explanation StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]); streamChecker.query("a"); // return False streamChecker.query("b"); // return False streamChecker.query("c"); // return False streamChecker.query("d"); // return True, because 'cd' is in the wordlist streamChecker.query("e"); // return False streamChecker.query("f"); // return True, because 'f' is in the wordlist streamChecker.query("g"); // return False streamChecker.query("h"); // return False streamChecker.query("i"); // return False streamChecker.query("j"); // return False streamChecker.query("k"); // return False streamChecker.query("l"); // return True, because 'kl' is in the wordlist   Constraints: 1 <= words.length <= 2000 1 <= words[i].length <= 200 words[i] consists of lowercase English letters. letter is a lowercase English letter. At most 4 * 10000 calls will be made to query.
class TrieNode: def __init__(self): self.isin = False self.children = collections.defaultdict(TrieNode) class StreamChecker: def __init__(self, words: List[str]): self.checker = TrieNode() for word in words: ptr = self.checker for ch in reversed(word): ptr = ptr.children[ch] ptr.isin = True self.stream = [] def query(self, letter: str) -> bool: self.stream.append(letter) ptr = self.checker for ch in reversed(self.stream): ptr = ptr.children.get(ch, None) if ptr is None: return False if ptr.isin: return True return False # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) # param_1 = obj.query(letter)
18d898
a681a3
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words. For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters "axyz" matches "xyz" from words. Implement the StreamChecker class: StreamChecker(String[] words) Initializes the object with the strings array words. boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.   Example 1: Input ["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"] [[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]] Output [null, false, false, false, true, false, true, false, false, false, false, false, true] Explanation StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]); streamChecker.query("a"); // return False streamChecker.query("b"); // return False streamChecker.query("c"); // return False streamChecker.query("d"); // return True, because 'cd' is in the wordlist streamChecker.query("e"); // return False streamChecker.query("f"); // return True, because 'f' is in the wordlist streamChecker.query("g"); // return False streamChecker.query("h"); // return False streamChecker.query("i"); // return False streamChecker.query("j"); // return False streamChecker.query("k"); // return False streamChecker.query("l"); // return True, because 'kl' is in the wordlist   Constraints: 1 <= words.length <= 2000 1 <= words[i].length <= 200 words[i] consists of lowercase English letters. letter is a lowercase English letter. At most 4 * 10000 calls will be made to query.
class Trie(object): def __init__(self, words): self.data = [None] * 27 for word in words: layer = self.data for char in word: index = ord(char) - ord('a') if layer[index] is None: layer[index] = [None] * 27 layer = layer[index] layer[-1] = True class StreamChecker(object): def __init__(self, words): """ :type words: List[str] """ self.trie = Trie(words) self.poss = [self.trie.data] def query(self, letter): """ :type letter: str :rtype: bool """ nposs = list() index = ord(letter) - ord('a') ans = False for poss in self.poss: if poss[index] is not None: if poss[index][-1]: ans = True nposs.append(poss[index]) nposs.append(self.trie.data) self.poss = nposs return ans
279f3e
89a5fa
You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0. An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.   Example 1: Input: n = 5, mines = [[4,2]] Output: 2 Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown. Example 2: Input: n = 1, mines = [[0,0]] Output: 0 Explanation: There is no plus sign, so return 0.   Constraints: 1 <= n <= 500 1 <= mines.length <= 5000 0 <= xi, yi < n All the pairs (xi, yi) are unique.
class Solution(object): def orderOfLargestPlusSign(self, N, mines): """ :type N: int :type mines: List[List[int]] :rtype: int """ m = [[1]*N for _ in range(N)] up = [[0]*N for _ in range(N)] down = [[0]*N for _ in range(N)] left = [[0]*N for _ in range(N)] right = [[0]*N for _ in range(N)] for i, j in mines: m[i][j] = 0 for i in range(N): up[0][i] = m[0][i] left[i][0] = m[i][0] right[i][-1] = m[i][-1] down[-1][i] = m[-1][i] for i in range(1, N): for j in range(N): up[i][j] = (up[i-1][j]+1)*m[i][j] for i in reversed(range(N-1)): for j in range(N): down[i][j] = (down[i+1][j]+1)*m[i][j] for j in range(1, N): for i in range(N): left[i][j] = (left[i][j-1]+1)*m[i][j] for j in reversed(range(N-1)): for i in range(N): right[i][j] = (right[i][j+1]+1)*m[i][j] best = 0 for i in range(N): for j in range(N): this = min(up[i][j], down[i][j], left[i][j], right[i][j]) if this > best: best = this return best
c02be9
89a5fa
You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0. An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.   Example 1: Input: n = 5, mines = [[4,2]] Output: 2 Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown. Example 2: Input: n = 1, mines = [[0,0]] Output: 0 Explanation: There is no plus sign, so return 0.   Constraints: 1 <= n <= 500 1 <= mines.length <= 5000 0 <= xi, yi < n All the pairs (xi, yi) are unique.
from bisect import * class Solution: def orderOfLargestPlusSign(self, N, mines): """ :type N: int :type mines: List[List[int]] :rtype: int """ row=[[-1,N] for _ in range(N)] col=[[-1,N] for _ in range(N)] for m,n in mines: insort(row[m],n) insort(col[n],m) ans=0 for m in range(N): for n in range(N): i=bisect_left(row[m],n) j=bisect_right(row[m],n) if i<j: continue t=min(row[m][i]-n,n-row[m][i-1]) i=bisect_left(col[n],m) t=min(t,col[n][i]-m,m-col[n][i-1]) ans=max(ans,t) return ans
2a8d20
190660
Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles. A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1's used must be distinct. Example 1: Input: grid = [[1,0,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[1,0,1,0,1]] Output: 1 Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1,1,1],[1,1,1],[1,1,1]] Output: 9 Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid = [[1,1,1,1]] Output: 0 Explanation: Rectangles must have four distinct corners. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 200 grid[i][j] is either 0 or 1. The number of 1's in the grid is in the range [1, 6000].
class Solution(object): def countCornerRectangles(self, grid): """ :type grid: List[List[int]] :rtype: int """ table = {} res = 0 for i in range(len(grid)): lst = [] for j in range(len(grid[0])): if grid[i][j] == 1: lst.append(j) for j1 in range(len(lst)): for j2 in range(j1 + 1, len(lst)): c = (lst[j1], lst[j2]) if c in table: #print i, c res += table[c] table[c] = table.get(c, 0) + 1 return res
24e4c4
190660
Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles. A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1's used must be distinct. Example 1: Input: grid = [[1,0,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[1,0,1,0,1]] Output: 1 Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1,1,1],[1,1,1],[1,1,1]] Output: 9 Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid = [[1,1,1,1]] Output: 0 Explanation: Rectangles must have four distinct corners. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 200 grid[i][j] is either 0 or 1. The number of 1's in the grid is in the range [1, 6000].
class Solution: def countCornerRectangles(self, grid): """ :type grid: List[List[int]] :rtype: int """ M = len(grid) N = len(grid[0]) if M==1 or N==1: return 0 dp = [0] *(N*N) for i in range(M): for j in range(N): if grid[i][j] == 1: for k in range(j): if grid[i][k] == 1: l = j*N+k dp[l] += 1 # print(dp) cnt = 0 for d in dp: if d>0: cnt += d*(d-1)//2 return cnt
f7ce6b
4a1481
You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n. The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n. You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times. Note: You are allowed to modify the array elements to become negative integers.   Example 1: Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0 Output: 579 Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579. Example 2: Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1 Output: 43 Explanation: One way to obtain the minimum sum of square difference is: - Increase nums1[0] once. - Increase nums2[2] once. The minimum of the sum of square difference will be: (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43. Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.   Constraints: n == nums1.length == nums2.length 1 <= n <= 100000 0 <= nums1[i], nums2[i] <= 100000 0 <= k1, k2 <= 10^9
class Solution: def minSumSquareDiff(self, a: List[int], b: List[int], k1: int, k2: int) -> int: n = len(a) c = [abs(a[i] - b[i]) for i in range(n)] m = k1 + k2 c.sort(reverse=True) if sum(c) <= m: return 0 c.append(0) for i in range(n): if (c[i] - c[i + 1]) * (i + 1) <= m: m -= (c[i] - c[i + 1]) * (i + 1) else: d = m // (i + 1) e = m % (i + 1) z = e * (c[i] - d - 1) ** 2 + (i + 1 - e) * (c[i] - d) ** 2 for j in range(i + 1, n): z += c[j] ** 2 break return z
afd6ce
4a1481
You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n. The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n. You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times. Note: You are allowed to modify the array elements to become negative integers.   Example 1: Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0 Output: 579 Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579. Example 2: Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1 Output: 43 Explanation: One way to obtain the minimum sum of square difference is: - Increase nums1[0] once. - Increase nums2[2] once. The minimum of the sum of square difference will be: (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43. Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.   Constraints: n == nums1.length == nums2.length 1 <= n <= 100000 0 <= nums1[i], nums2[i] <= 100000 0 <= k1, k2 <= 10^9
class Solution(object): def minSumSquareDiff(self, nums1, nums2, k1, k2): """ :type nums1: List[int] :type nums2: List[int] :type k1: int :type k2: int :rtype: int """ n=len(nums1) l=[] for i in range(n): l.append(abs(nums1[i]-nums2[i])) k=k1+k2 l.sort(reverse=True) i=0 c=l[0] while True: while i<n-1 and c==l[i+1]: i+=1 if i==n-1: if k>=c*(i+1): return 0 else: minus=k//(i+1) more=k%(i+1) return (i+1-more)*(c-minus)**2+more*(c-minus-1)**2 else: if k>=(c-l[i+1])*(i+1): k-=(c-l[i+1])*(i+1) c=l[i+1] else: minus=k//(i+1) more=k%(i+1) total=(i+1-more)*(c-minus)**2+more*(c-minus-1)**2 for j in range(i+1,n): total+=l[j]**2 return total
f3dfef
b7321f
You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j]. Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.   Example 1: Input: word1 = "ac", word2 = "b" Output: false Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string. Example 2: Input: word1 = "abcc", word2 = "aab" Output: true Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters. Example 3: Input: word1 = "abcde", word2 = "fghij" Output: true Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.   Constraints: 1 <= word1.length, word2.length <= 100000 word1 and word2 consist of only lowercase English letters.
class Solution(object): def isItPossible(self, word1, word2): """ :type word1: str :type word2: str :rtype: bool """ f, g, c, d = [0] * 26, [0] * 26, 0, 0 for i in word1: f[ord(i) - ord('a')] += 1 for i in word2: g[ord(i) - ord('a')] += 1 for i in range(26): c, d = c + (f[i] > 0), d + (g[i] > 0) for i in range(26): for j in range(26): if f[i] and g[j] and (c - (f[i] == 1) + (not f[j]) == d - (g[j] == 1) + (not g[i]) if i - j else c == d): return True return False
5635c4
b7321f
You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j]. Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.   Example 1: Input: word1 = "ac", word2 = "b" Output: false Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string. Example 2: Input: word1 = "abcc", word2 = "aab" Output: true Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters. Example 3: Input: word1 = "abcde", word2 = "fghij" Output: true Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.   Constraints: 1 <= word1.length, word2.length <= 100000 word1 and word2 consist of only lowercase English letters.
class Solution: def isItPossible(self, word1: str, word2: str) -> bool: cnt1 = collections.Counter(word1) cnt2 = collections.Counter(word2) for c in range(26): c = chr(ord('a') + c) for c2 in range(26): c2 = chr(ord('a') + c2) if cnt1[c] > 0 and cnt2[c2] > 0: cnt1[c] -= 1 cnt1[c2] += 1 cnt2[c2] -= 1 cnt2[c] += 1 if sum(n > 0 for n in cnt1.values()) == sum(n > 0 for n in cnt2.values()): return True cnt2[c] -= 1 cnt2[c2] += 1 cnt1[c2] -= 1 cnt1[c] += 1 return False
c890e5
3c1902
A Bitset is a data structure that compactly stores bits. Implement the Bitset class: Bitset(int size) Initializes the Bitset with size bits, all of which are 0. void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs. void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs. void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa. boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise. boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise. int count() Returns the total number of bits in the Bitset which have value 1. String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.   Example 1: Input ["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"] [[5], [3], [1], [], [], [0], [], [], [0], [], []] Output [null, null, null, null, false, null, null, true, null, 2, "01010"] Explanation Bitset bs = new Bitset(5); // bitset = "00000". bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010". bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010". bs.flip(); // the value of each bit is flipped, so bitset = "10101". bs.all(); // return False, as not all values of the bitset are 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101". bs.flip(); // the value of each bit is flipped, so bitset = "11010". bs.one(); // return True, as there is at least 1 index with value 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010". bs.count(); // return 2, as there are 2 bits with value 1. bs.toString(); // return "01010", which is the composition of bitset.   Constraints: 1 <= size <= 100000 0 <= idx <= size - 1 At most 100000 calls will be made in total to fix, unfix, flip, all, one, count, and toString. At least one call will be made to all, one, count, or toString. At most 5 calls will be made to toString.
class Bitset: def __init__(self, size: int): self.size = size self.flipped = False self.fixed_set = set() def fix(self, idx: int) -> None: if not self.flipped: self.fixed_set.add(idx) else: self.fixed_set.discard(idx) def unfix(self, idx: int) -> None: if not self.flipped: self.fixed_set.discard(idx) else: self.fixed_set.add(idx) def flip(self) -> None: self.flipped = not self.flipped def all(self) -> bool: if not self.flipped: return len(self.fixed_set) == self.size else: return len(self.fixed_set) == 0 def one(self) -> bool: if not self.flipped: return len(self.fixed_set) > 0 else: return len(self.fixed_set) < self.size def count(self) -> int: if not self.flipped: return len(self.fixed_set) else: return self.size - len(self.fixed_set) def toString(self) -> str: if not self.flipped: return "".join("1" if i in self.fixed_set else "0" for i in range(self.size)) else: return "".join("0" if i in self.fixed_set else "1" for i in range(self.size)) # Your Bitset object will be instantiated and called as such: # obj = Bitset(size) # obj.fix(idx) # obj.unfix(idx) # obj.flip() # param_4 = obj.all() # param_5 = obj.one() # param_6 = obj.count() # param_7 = obj.toString()
1f7d37
3c1902
A Bitset is a data structure that compactly stores bits. Implement the Bitset class: Bitset(int size) Initializes the Bitset with size bits, all of which are 0. void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs. void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs. void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa. boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise. boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise. int count() Returns the total number of bits in the Bitset which have value 1. String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.   Example 1: Input ["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"] [[5], [3], [1], [], [], [0], [], [], [0], [], []] Output [null, null, null, null, false, null, null, true, null, 2, "01010"] Explanation Bitset bs = new Bitset(5); // bitset = "00000". bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010". bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010". bs.flip(); // the value of each bit is flipped, so bitset = "10101". bs.all(); // return False, as not all values of the bitset are 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101". bs.flip(); // the value of each bit is flipped, so bitset = "11010". bs.one(); // return True, as there is at least 1 index with value 1. bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010". bs.count(); // return 2, as there are 2 bits with value 1. bs.toString(); // return "01010", which is the composition of bitset.   Constraints: 1 <= size <= 100000 0 <= idx <= size - 1 At most 100000 calls will be made in total to fix, unfix, flip, all, one, count, and toString. At least one call will be made to all, one, count, or toString. At most 5 calls will be made to toString.
class Bitset(object): def __init__(self, size): """ :type size: int """ self.a, self.o, self.f = [False] * size, 0, False def fix(self, idx): """ :type idx: int :rtype: None """ if not self.a[idx] and not self.f or self.a[idx] and self.f: self.o, self.a[idx] = self.o + 1, not self.a[idx] def unfix(self, idx): """ :type idx: int :rtype: None """ if self.a[idx] and not self.f or not self.a[idx] and self.f: self.a[idx], self.o = not self.a[idx], self.o - 1 def flip(self): """ :rtype: None """ self.f, self.o = not self.f, len(self.a) - self.o def all(self): """ :rtype: bool """ return self.o == len(self.a) def one(self): """ :rtype: bool """ return self.o > 0 def count(self): """ :rtype: int """ return self.o def toString(self): """ :rtype: str """ s = [] for i in range(len(self.a)): s.append('0' if self.a[i] == self.f else '1') return ''.join(s) # Your Bitset object will be instantiated and called as such: # obj = Bitset(size) # obj.fix(idx) # obj.unfix(idx) # obj.flip() # param_4 = obj.all() # param_5 = obj.one() # param_6 = obj.count() # param_7 = obj.toString()
633241
bffa60
You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s.   Example 1: Input: s = "aacaba" Output: 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively. Example 2: Input: s = "abcd" Output: 1 Explanation: Split the string as follows ("ab", "cd").   Constraints: 1 <= s.length <= 100000 s consists of only lowercase English letters.
class Solution: def numSplits(self, s: str) -> int: a = [] d = {} for i in s: if i not in d: d[i] = 1 a.append(len(d)) d = {} b = [] for i in s[::-1]: if i not in d: d[i] = 1 b.append(len(d)) b = b[::-1] ans = 0 for i in range(0,len(s)-1): if a[i]==b[i+1]: ans+=1 return ans
126b00
bffa60
You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s.   Example 1: Input: s = "aacaba" Output: 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively. Example 2: Input: s = "abcd" Output: 1 Explanation: Split the string as follows ("ab", "cd").   Constraints: 1 <= s.length <= 100000 s consists of only lowercase English letters.
class Solution(object): def numSplits(self, s): left = collections.Counter() right = collections.Counter(s) diff = len(right) res = 0 print diff for c in s: right[c] -= 1 if right[c] == 0: diff -= 1 if left[c] == 0: diff -= 1 left[c] += 1 if diff == 0: res += 1 return res
f0de78
dcee75
Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets. A quadruplet (i, j, k, l) is increasing if: 0 <= i < j < k < l < n, and nums[i] < nums[k] < nums[j] < nums[l].   Example 1: Input: nums = [1,3,2,4,5] Output: 2 Explanation: - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. There are no other quadruplets, so we return 2. Example 2: Input: nums = [1,2,3,4] Output: 0 Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.   Constraints: 4 <= nums.length <= 4000 1 <= nums[i] <= nums.length All the integers of nums are unique. nums is a permutation.
class Solution: def countQuadruplets(self, nums: List[int]) -> int: l, r, s = [[0] * len(nums) for _ in range(len(nums) + 1)], [[0] * len(nums) for _ in range(len(nums) + 1)], 0 for i in range(len(nums) - 1): for j in range(1, nums[i] + 1): l[j][i + 1] = l[j][i] for j in range(nums[i] + 1, len(nums) + 1): l[j][i + 1] = l[j][i] + 1 for i in range(len(nums) - 1, 0, -1): for j in range(1, nums[i]): r[j][i - 1] = r[j][i] + 1 for j in range(nums[i], len(nums) + 1): r[j][i - 1] = r[j][i] for i in range(len(nums)): for j in range(i + 1, len(nums)): s += l[nums[j]][i] * r[nums[i]][j] if nums[i] > nums[j] else 0 return s
b10247
dcee75
Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets. A quadruplet (i, j, k, l) is increasing if: 0 <= i < j < k < l < n, and nums[i] < nums[k] < nums[j] < nums[l].   Example 1: Input: nums = [1,3,2,4,5] Output: 2 Explanation: - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. There are no other quadruplets, so we return 2. Example 2: Input: nums = [1,2,3,4] Output: 0 Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.   Constraints: 4 <= nums.length <= 4000 1 <= nums[i] <= nums.length All the integers of nums are unique. nums is a permutation.
class BIT(object): def __init__(self, n): self.n = n self.tree = [0] * (n + 1) def lowbit(self, x): return x & (-x) def update(self, index, val): while index <= self.n: self.tree[index] += val index += self.lowbit(index) def query(self, index): ans = 0 while index: ans += self.tree[index] index -= self.lowbit(index) return ans class Solution(object): def countQuadruplets(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) bit_left = BIT(n) ans = 0 for j in xrange(n): k = n-1 num_l = 0 while k > j: if nums[k] < nums[j]: if num_l > 0: num_i = bit_left.query(nums[k]) ans += num_i * num_l else: num_l += 1 k -= 1 bit_left.update(nums[j], 1) return ans
01192a
a866ae
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.   Example 1: Input: rods = [1,2,3,6] Output: 6 Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. Example 2: Input: rods = [1,2,3,4,5,6] Output: 10 Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. Example 3: Input: rods = [1,2] Output: 0 Explanation: The billboard cannot be supported, so we return 0.   Constraints: 1 <= rods.length <= 20 1 <= rods[i] <= 1000 sum(rods[i]) <= 5000
class Solution: def tallestBillboard(self, rods): """ :type rods: List[int] :rtype: int """ pos = {0:0} # key: current acc # value: sum of positives for rod in rods: next_pos = {} for last in pos: next_pos[last+rod] = max(next_pos.get(last+rod, 0), pos[last]+rod) next_pos[last-rod] = max(next_pos.get(last-rod, 0), pos[last]) next_pos[last] = max(next_pos.get(last, 0), pos[last]) # print(last, rod, next_pos) del pos pos = next_pos return pos[0]
9316c0
a866ae
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.   Example 1: Input: rods = [1,2,3,6] Output: 6 Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. Example 2: Input: rods = [1,2,3,4,5,6] Output: 10 Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. Example 3: Input: rods = [1,2] Output: 0 Explanation: The billboard cannot be supported, so we return 0.   Constraints: 1 <= rods.length <= 20 1 <= rods[i] <= 1000 sum(rods[i]) <= 5000
class Solution(object): def update(self, d, a, b): if a > b: a, b = b, a diff = b - a d[diff] = max(d.get(diff, 0), a) def tallestBillboard(self, rods): """ :type rods: List[int] :rtype: int """ from collections import defaultdict m = sum(rods) d = defaultdict(int) d[0] = 0 for a in rods: dd = defaultdict(int) for x, t1 in d.items(): t2 = t1 + x self.update(dd, t1, t2) self.update(dd, t1 + a, t2) self.update(dd, t1, t2 + a) d = dd return d[0]
d3a844
f5ed34
You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.   Example 1: Input: nums = [2,10,7,5,4,1,8,6] Output: 5 Explanation: The minimum element in the array is nums[5], which is 1. The maximum element in the array is nums[1], which is 10. We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back. This results in 2 + 3 = 5 deletions, which is the minimum number possible. Example 2: Input: nums = [0,-4,19,1,8,-2,-3,5] Output: 3 Explanation: The minimum element in the array is nums[1], which is -4. The maximum element in the array is nums[2], which is 19. We can remove both the minimum and maximum by removing 3 elements from the front. This results in only 3 deletions, which is the minimum number possible. Example 3: Input: nums = [101] Output: 1 Explanation: There is only one element in the array, which makes it both the minimum and maximum element. We can remove it with 1 deletion.   Constraints: 1 <= nums.length <= 100000 -100000 <= nums[i] <= 100000 The integers in nums are distinct.
class Solution: def minimumDeletions(self, nums: List[int]) -> int: n = len(nums) if n == 1: return 1 hi = max(nums) lo = min(nums) r = [i for i in range(n) if nums[i] == hi][0] l = [i for i in range(n) if nums[i] == lo][0] if r < l: l, r = r, l return min(n - (r - l - 1), r + 1, n - l)
dbeecd
f5ed34
You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.   Example 1: Input: nums = [2,10,7,5,4,1,8,6] Output: 5 Explanation: The minimum element in the array is nums[5], which is 1. The maximum element in the array is nums[1], which is 10. We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back. This results in 2 + 3 = 5 deletions, which is the minimum number possible. Example 2: Input: nums = [0,-4,19,1,8,-2,-3,5] Output: 3 Explanation: The minimum element in the array is nums[1], which is -4. The maximum element in the array is nums[2], which is 19. We can remove both the minimum and maximum by removing 3 elements from the front. This results in only 3 deletions, which is the minimum number possible. Example 3: Input: nums = [101] Output: 1 Explanation: There is only one element in the array, which makes it both the minimum and maximum element. We can remove it with 1 deletion.   Constraints: 1 <= nums.length <= 100000 -100000 <= nums[i] <= 100000 The integers in nums are distinct.
class Solution(object): def minimumDeletions(self, nums): """ :type nums: List[int] :rtype: int """ a = nums n = len(a) if len(a) == 1: return 1 i, j = sorted([a.index(min(a)), a.index(max(a))]) return min(j+1, n-i, i+1+n-j)
a013a6
c40e46
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).   Example 1: Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] Output: 13 Explanation: There are two falling paths with a minimum sum as shown. Example 2: Input: matrix = [[-19,57],[-40,-5]] Output: -59 Explanation: The falling path with a minimum sum is shown.   Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 -100 <= matrix[i][j] <= 100
class Solution(object): def minFallingPathSum(self, A): """ :type A: List[List[int]] :rtype: int """ n = len(A) dp = A[0][::] for row in A[1:]: ndp = row[::] for i in range(n): candidates = [dp[i]] if i: candidates.append(dp[i-1]) if i != n-1: candidates.append(dp[i+1]) ndp[i] += min(candidates) dp = ndp return min(dp)
50b877
c40e46
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).   Example 1: Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] Output: 13 Explanation: There are two falling paths with a minimum sum as shown. Example 2: Input: matrix = [[-19,57],[-40,-5]] Output: -59 Explanation: The falling path with a minimum sum is shown.   Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 -100 <= matrix[i][j] <= 100
class Solution: def minFallingPathSum(self, A): """ :type A: List[List[int]] :rtype: int """ n=len(A) for i in range(1,n): A[i][0]+=min(A[i-1][0],A[i-1][1]) A[i][-1]+=min(A[i-1][-1],A[i-1][-2]) for j in range(1,n-1): A[i][j]+=min(A[i-1][j-1],A[i-1][j],A[i-1][j+1]) return min(A[-1])
2b733d
b97cad
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied: t is a subsequence of the string s. The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k. Return the length of the longest ideal string. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.   Example 1: Input: s = "acfgbd", k = 2 Output: 4 Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order. Example 2: Input: s = "abcd", k = 3 Output: 4 Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.   Constraints: 1 <= s.length <= 100000 0 <= k <= 25 s consists of lowercase English letters.
class Solution: def longestIdealString(self, s: str, k: int) -> int: x = [ord(i)-97 for i in s] res = [0]*26 for i in x: cur = 0 for j in range(26): if abs(i-j) <= k: cur = max(cur, res[j]) cur += 1 res[i] = max(res[i], cur) return max(res)
360bb0
b97cad
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied: t is a subsequence of the string s. The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k. Return the length of the longest ideal string. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.   Example 1: Input: s = "acfgbd", k = 2 Output: 4 Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order. Example 2: Input: s = "abcd", k = 3 Output: 4 Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.   Constraints: 1 <= s.length <= 100000 0 <= k <= 25 s consists of lowercase English letters.
class Solution(object): def longestIdealString(self, s, k): """ :type s: str :type k: int :rtype: int """ l, m = [0] * 26, 0 for x in s: n = 1 for c in range(max(ord('a'), ord(x) - k), min(ord('z'), ord(x) + k) + 1): n = max(n, 1 + l[c - ord('a')]) l[ord(x) - ord('a')], m = n, max(m, n) return m
15be82
224e97
An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].   Example 1: Input: nums = [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations. Example 2: Input: nums = [2,2,2] Output: 1   Constraints: 1 <= nums.length <= 12 0 <= nums[i] <= 10^9
class Solution: def dfs(self, x): if x == self.n: self.ans += 1 return for i in range(self.n): if self.mark[i]: continue cur = self.a[i] if i != 0 and self.mark[i - 1] == False and self.a[i] == self.a[i - 1]: continue if x != 0 and (cur + self.rec[x - 1]) not in self.square: continue self.mark[i] = True self.rec[x] = cur self.dfs(x + 1) self.mark[i] = False self.rec[x] = None def numSquarefulPerms(self, A: 'List[int]') -> 'int': self.square = set([i ** 2 for i in range(32000)]) self.ans = 0 self.a = sorted(A) self.n = len(self.a) self.mark = [False for _ in range(self.n)] self.rec = [None for _ in range(self.n)] self.dfs(0) return self.ans
d87cb8
224e97
An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].   Example 1: Input: nums = [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations. Example 2: Input: nums = [2,2,2] Output: 1   Constraints: 1 <= nums.length <= 12 0 <= nums[i] <= 10^9
class Solution(object): def numSquarefulPerms(self, A): """ :type A: List[int] :rtype: int """ def perfect(x): s = math.sqrt(x) return s == int(s) def dfs(i, prev): if i == n: self.ans += 1 for j, c in enumerate(A): if (prev is None or con[prev][j]) and self.last[c] < j: last_used = self.last[c] self.last[c] = j dfs(i + 1, j) self.last[c] = last_used A.sort() n = len(A) self.ans = 0 self.last = collections.defaultdict(lambda: float('-inf')) con = [[0] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): if perfect(A[i] + A[j]): con[i][j] = 1 con[j][i] = 1 dfs(0, None) return self.ans
0e3e45
25c69b
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.   Example 1: Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further.   Constraints: 1 <= binary.length <= 100000 binary consist of '0' and '1'.
class Solution: def maximumBinaryString(self, binary: str) -> str: # 10110 # 10011 # 11011 if "0" not in binary: return binary N = len(binary) index = binary.index("0") ans = [] for y in range(index): ans.append(binary[y]) zeroes = 0 ones = 0 for y in range(index, N): if binary[y] == "0": zeroes += 1 else: ones += 1 #print(zeroes, ones) while zeroes >= 2: zeroes -= 1 ans.append("1") ans.append("0") while ones >= 1: ones -= 1 ans.append("1") return "".join(ans)
5db8c5
25c69b
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.   Example 1: Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further.   Constraints: 1 <= binary.length <= 100000 binary consist of '0' and '1'.
class Solution(object): def maximumBinaryString(self, binary): k = 0 while k < len(binary) and binary[k] == '1': k += 1 A = sorted(binary[k:]) for i in xrange(len(A) - 1): if A[i] == A[i + 1] == '0': A[i] = '1' return '1' * k + ''.join(A)
fc55a5
6dd2e1
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. Return the length of the shortest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.   Example 1: Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] Output: 3 Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 Example 2: Input: n = 4, edges = [[0,1],[0,2]] Output: -1 Explanation: There are no cycles in this graph.   Constraints: 2 <= n <= 1000 1 <= edges.length <= 1000 edges[i].length == 2 0 <= ui, vi < n ui != vi There are no repeated edges.
class Solution(object): def findShortestCycle(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ ne = [[] for i in range(n)] for a, b in edges: ne[a].append(b) ne[b].append(a) ans = 2147483647 for i in range(n): dis = [2147483647] * n p = [-1] * n dis[i] = 0 q = deque() q.append(i) while len(q) > 0: now = q.popleft() d = dis[now] for next_node in ne[now]: if dis[next_node] == 2147483647: dis[next_node] = d + 1 p[next_node] = now q.append(next_node) elif p[now] != next_node and p[next_node] != now: ans = min(ans, dis[now] + dis[next_node] + 1) if ans == 2147483647: return -1 return ans
a28f24
6dd2e1
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. Return the length of the shortest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.   Example 1: Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] Output: 3 Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 Example 2: Input: n = 4, edges = [[0,1],[0,2]] Output: -1 Explanation: There are no cycles in this graph.   Constraints: 2 <= n <= 1000 1 <= edges.length <= 1000 edges[i].length == 2 0 <= ui, vi < n ui != vi There are no repeated edges.
class Solution: def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: def bfs(s, t): nonlocal graph, n q = deque() dis = [inf] * n dis[s] = 0 q.append(s) while len(q) != 0: u = q.popleft() if u == t: return dis[u] for v in graph[u]: if dis[v] == inf: dis[v] = dis[u] + 1 q.append(v) return inf ans = inf graph = [set() for i in range(n)] for u, v in edges: graph[u].add(v) graph[v].add(u) for u, v in edges: graph[u].remove(v) graph[v].remove(u) ans = min(ans, bfs(u, v) + 1) graph[u].add(v) graph[v].add(u) if ans == inf: return -1 else: return ans
1f3d27
0f6fbf
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not. Return true if the array has at least one valid partition. Otherwise, return false.   Example 1: Input: nums = [4,4,4,5,6] Output: true Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. This partition is valid, so we return true. Example 2: Input: nums = [1,1,1,2] Output: false Explanation: There is no valid partition for this array.   Constraints: 2 <= nums.length <= 100000 1 <= nums[i] <= 1000000
class Solution: def validPartition(self, nums: List[int]) -> bool: n = len(nums) @cache def ans(x): if x == n: return True if x+1 < n and nums[x] == nums[x+1] and ans(x+2): return True if x+2 < n and nums[x] == nums[x+1] == nums[x+2] and ans(x+3): return True if x+2 < n and nums[x]+1 == nums[x+1] == nums[x+2]-1 and ans(x+3): return True return False return ans(0)
86181f
0f6fbf
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not. Return true if the array has at least one valid partition. Otherwise, return false.   Example 1: Input: nums = [4,4,4,5,6] Output: true Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. This partition is valid, so we return true. Example 2: Input: nums = [1,1,1,2] Output: false Explanation: There is no valid partition for this array.   Constraints: 2 <= nums.length <= 100000 1 <= nums[i] <= 1000000
class Solution(object): def validPartition(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) == 2: return nums[0] == nums[1] d = [False, nums[0] == nums[1], nums[0] == nums[1] and nums[1] == nums[2] or nums[0] + 1 == nums[1] and nums[1] + 1 == nums[2]] + [False] * (len(nums) - 3) for i in range(3, len(nums)): d[i] = nums[i] == nums[i - 1] and d[i - 2] or (nums[i] == nums[i - 1] and nums[i - 1] == nums[i - 2] or nums[i] - 1 == nums[i - 1] and nums[i - 1] - 1 == nums[i - 2]) and d[i - 3] return d[len(nums) - 1]
419ad8
808cf6
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0 Example 3: Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length <= n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
class Solution: def minMalwareSpread(self, graph, initial): """ :type graph: List[List[int]] :type initial: List[int] :rtype: int """ n = len(graph) g = [[] for _ in range(n)] for i in range(n): for j in range(n): if graph[i][j]: g[i].append(j) comp = [0 for _ in range(n)] seen = [False for _ in range(n)] cur = 0 for node in range(n): if seen[node]: continue cur += 1 q = [node] while q: x = q.pop() seen[x] = True comp[x] = cur for child in g[x]: if not seen[child]: seen[child] = True q.append(child) size = [0 for _ in range(cur+1)] size2 = [0 for _ in range(cur+1)] for v in comp: size[v] += 1 for v in initial: size2[comp[v]] += 1 res = None max_val = -1 for v in sorted(initial): component = comp[v] effect = size[component] if size2[component] == 1 else 0 if effect > max_val: max_val = effect res = v return res
f2b9c3
808cf6
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.   Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0 Example 3: Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] Output: 1   Constraints: n == graph.length n == graph[i].length 2 <= n <= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 <= initial.length <= n 0 <= initial[i] <= n - 1 All the integers in initial are unique.
class Solution(object): def expand(self, exclude): self.visited = set() for i in self.initial: if i == exclude: continue self.dfs(i) return len(self.visited) def dfs(self, cur): if cur in self.visited: return self.visited.add(cur) for to in self.graph[cur]: self.dfs(to) def minMalwareSpread(self, graph, initial): """ :type graph: List[List[int]] :type initial: List[int] :rtype: int """ initial.sort() for i in range(len(graph)): graph[i] = [j for j in range(len(graph)) if graph[i][j]] self.graph = graph self.initial = initial best = len(graph)+10 ans = -1 for i in range(len(initial)): this = self.expand(exclude = initial[i]) # print this, initial[i] if this < best: best = this ans = initial[i] return ans # class Solution(object): # def expand(self, start): # visited = set() # visited.add(start) # def dfs(self, cur, label): # if self.origin[cur] # def minMalwareSpread(self, graph, initial): # """ # :type graph: List[List[int]] # :type initial: List[int] # :rtype: int # """ # self.origin = [set() for _ in range(len(graph))] # self.graph = graph # for i in initial: # self.expand(i)
c774e7
de104a
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["babca","bbazb"] Output: 3 Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"]. Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]). Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order. Example 2: Input: strs = ["edcba"] Output: 4 Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted. Example 3: Input: strs = ["ghi","def","abc"] Output: 0 Explanation: All rows are already lexicographically sorted.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.  
class Solution: def minDeletionSize(self, A): """ :type A: List[str] :rtype: int """ a = A n = len(a) m = len(a[0]) dp = [None for _ in range(m)] dp[0] = 1 ans = 1 for j in range(1, m): dp[j] = 1 for k in range(j): flag = True for i in range(n): if a[i][k] > a[i][j]: flag = False break if not flag: continue dp[j] = max(dp[j], dp[k] + 1) ans = max(ans, dp[j]) # print(j, dp[j]) return m - ans # mark = [[None for _ in range(m)] for _ in range(n)] # for i in range(n): # mark[i][0] = -1 # for j in range(1, m): # t = j - 1 # while t != -1 and a[i][t] > a[i][j]: # t = mark[i][t] # mark[i][j] = t # print(mark[i])
ff370a
de104a
You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.   Example 1: Input: strs = ["babca","bbazb"] Output: 3 Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"]. Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]). Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order. Example 2: Input: strs = ["edcba"] Output: 4 Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted. Example 3: Input: strs = ["ghi","def","abc"] Output: 0 Explanation: All rows are already lexicographically sorted.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters.  
class Solution(object): def minDeletionSize(self, A): """ :type A: List[str] :rtype: int """ def judge(j,i): Flag=True for k in range(0,len(A)): if A[k][j]>A[k][i]: return False return True str_len=len(A[0]) DP=[1 for _ in range(0,str_len)] for i in range(1,str_len): Max=1 for j in range(0,i): if(judge(j,i)): Max=max(Max,DP[j]+1) DP[i]=Max return str_len-max(DP)
232df3
e55ee0
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: packages = [2,3,5], boxes = [[4,8],[2,8]] Output: 6 Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box. The total waste is (4-2) + (4-3) + (8-5) = 6. Example 2: Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]] Output: -1 Explanation: There is no box that the package of size 5 can fit in. Example 3: Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]] Output: 9 Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes. The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.   Constraints: n == packages.length m == boxes.length 1 <= n <= 100000 1 <= m <= 100000 1 <= packages[i] <= 100000 1 <= boxes[j].length <= 100000 1 <= boxes[j][k] <= 100000 sum(boxes[j].length) <= 100000 The elements in boxes[j] are distinct.
class Solution: def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: ma = mapa = max(packages) for b in boxes: ma = max(ma, max(b)) mod = 10 ** 9 + 7 cnt = Counter(packages) pre = [0] * (ma+1) su = [0] * (ma+1) for i in range(ma+1): pre[i] = pre[i-1] + cnt[i] su[i] = su[i-1] + cnt[i] * i ans = inf for box in boxes: box.sort() cnt = 0 if box[-1] >= mapa: for i in range(len(box)): if i == 0: cnt += pre[box[i]] * box[i] - su[box[i]] else: cnt += (pre[box[i]] - pre[box[i-1]]) * box[i] - (su[box[i]] - su[box[i-1]]) ans = min(ans, cnt) if ans == inf: return -1 return ans % mod
9e52b6
e55ee0
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 10^9 + 7.   Example 1: Input: packages = [2,3,5], boxes = [[4,8],[2,8]] Output: 6 Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box. The total waste is (4-2) + (4-3) + (8-5) = 6. Example 2: Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]] Output: -1 Explanation: There is no box that the package of size 5 can fit in. Example 3: Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]] Output: 9 Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes. The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.   Constraints: n == packages.length m == boxes.length 1 <= n <= 100000 1 <= m <= 100000 1 <= packages[i] <= 100000 1 <= boxes[j].length <= 100000 1 <= boxes[j][k] <= 100000 sum(boxes[j].length) <= 100000 The elements in boxes[j] are distinct.
from collections import Counter class Solution(object): def minWastedSpace(self, packages, boxes): """ :type packages: List[int] :type boxes: List[List[int]] :rtype: int """ m = max(packages) cnt = [0] * (m+2) tot = [0] * (m+2) def _get(i): i = min(i, m) a = b = 0 while i > 0: a += cnt[i] b += tot[i] i -= i & -i return (a, b) def _upd(i, v): x = i while i <= m+1: cnt[i] += v tot[i] += x*v i += i & -i for k, v in Counter(packages).iteritems(): _upd(k, v) best = float('inf') for arr in boxes: if max(arr) < m: continue cost = c = t = 0 for x in sorted(arr): cc, tt = _get(x) cost += (cc-c)*x - (tt-t) c, t = cc, tt best = min(best, cost) return best % (10**9+7) if best < float('inf') else -1
227b94
673724
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.   Example 1: Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.   Constraints: 2 <= asteroids.length <= 10000 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0
class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ stack = [] ans = [] for this in asteroids: if this > 0: stack.append(this) else: killed = False while stack: if -this < stack[-1]: killed = True break elif -this == stack[-1]: killed = True stack.pop() break else: stack.pop() if not killed: ans.append(this) ans.extend(stack) return ans
4ffddb
673724
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.   Example 1: Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.   Constraints: 2 <= asteroids.length <= 10000 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0
class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ ret = [] left = [] #the left side that all go right for i in range(len(asteroids)): cur = asteroids[i] if cur < 0: while left: if left[-1] > abs(cur): cur = None break elif left[-1] == abs(cur): left.pop() cur = None break else: left.pop() if cur != None: ret.append(cur) else: left.append(cur) ret.extend(left) return ret
37ce21
b45e66
You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the minimum number of groups you need to make. Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.   Example 1: Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]] Output: 3 Explanation: We can divide the intervals into the following groups: - Group 1: [1, 5], [6, 8]. - Group 2: [2, 3], [5, 10]. - Group 3: [1, 10]. It can be proven that it is not possible to divide the intervals into fewer than 3 groups. Example 2: Input: intervals = [[1,3],[5,6],[8,10],[11,13]] Output: 1 Explanation: None of the intervals overlap, so we can put all of them in one group.   Constraints: 1 <= intervals.length <= 100000 intervals[i].length == 2 1 <= lefti <= righti <= 1000000
class Solution(object): def minGroups(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ s, c, a = [], 0, 0 for i, j in intervals: s.append([i, -1]) s.append([j, 1]) s.sort() for i, j in s: c -= j a = max(a, c) return a
b4ce2a
b45e66
You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the minimum number of groups you need to make. Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.   Example 1: Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]] Output: 3 Explanation: We can divide the intervals into the following groups: - Group 1: [1, 5], [6, 8]. - Group 2: [2, 3], [5, 10]. - Group 3: [1, 10]. It can be proven that it is not possible to divide the intervals into fewer than 3 groups. Example 2: Input: intervals = [[1,3],[5,6],[8,10],[11,13]] Output: 1 Explanation: None of the intervals overlap, so we can put all of them in one group.   Constraints: 1 <= intervals.length <= 100000 intervals[i].length == 2 1 <= lefti <= righti <= 1000000
class Solution: def minGroups(self, intervals: List[List[int]]) -> int: l = [] for i, j in intervals: l.append((i, 0)) l.append((j, 1)) res = 0 cur = 0 for x, y in sorted(l): if y == 0: cur += 1 else: cur -= 1 res = max(res, cur) return res
ad4af5
5db7f9
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts.   Example 1: Input: n = 7, cuts = [1,3,4,5] Output: 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). Example 2: Input: n = 9, cuts = [5,6,1,4,2] Output: 22 Explanation: If you try the given cuts ordering the cost will be 25. There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.   Constraints: 2 <= n <= 1000000 1 <= cuts.length <= min(n - 1, 100) 1 <= cuts[i] <= n - 1 All the integers in cuts array are distinct.
sys.setrecursionlimit(10000000) class Solution: def minCost(self, n: int, cuts: List[int]) -> int: cuts = [0] + cuts + [n] cuts.sort() @lru_cache(None) def dp(l,r): # cost of cutting stick idx l to r if l+1==r: return 0 base = cuts[r]-cuts[l] # where to cut ret = inf for m in range(l+1,r): ret = min(ret,dp(l,m)+dp(m,r)) return ret+base return dp(0,len(cuts)-1)
462293
5db7f9
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts.   Example 1: Input: n = 7, cuts = [1,3,4,5] Output: 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). Example 2: Input: n = 9, cuts = [5,6,1,4,2] Output: 22 Explanation: If you try the given cuts ordering the cost will be 25. There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.   Constraints: 2 <= n <= 1000000 1 <= cuts.length <= min(n - 1, 100) 1 <= cuts[i] <= n - 1 All the integers in cuts array are distinct.
class Solution(object): def minCost(self, n, cuts): """ :type n: int :type cuts: List[int] :rtype: int """ cuts.sort() mem ={} return self.f(0,len(cuts)-1,0, n, cuts,mem) def f(self,i,j, s,e, cuts,mem): if j < i: return 0 if i == j: return (e - s) if (i,j) in mem: return mem[(i,j)] m = +float('inf') for k in range(i, j+1): cut = cuts[k] #perform this cut m = min(m , (e - s) + self.f(i, k - 1, s, cut, cuts ,mem) + self.f(k+1, j, cut,e, cuts,mem)) mem[(i,j)] = m return m