sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
b62fe4
f21ba2
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend.   Example 1: Input: events = [[1,2],[2,3],[3,4]] Output: 3 Explanation: You can attend all the three events. One way to attend them all is as shown. Attend the first event on day 1. Attend the second event on day 2. Attend the third event on day 3. Example 2: Input: events= [[1,2],[2,3],[3,4],[1,2]] Output: 4   Constraints: 1 <= events.length <= 100000 events[i].length == 2 1 <= startDayi <= endDayi <= 100000
class Solution(object): def maxEvents(self, events): events = [[s, e+1] for s, e in events] M = max(e for s,e in events) A = [[] for _ in xrange(M+1)] for s, e in events: A[s].append(e) pq = [] ans = 0 for d in range(1, M + 1): for e in A[d]: heapq.heappush(pq, e) while pq and pq[0] < d + 1: heapq.heappop(pq) if pq: heapq.heappop(pq) ans += 1 return ans
97651f
f21ba2
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend.   Example 1: Input: events = [[1,2],[2,3],[3,4]] Output: 3 Explanation: You can attend all the three events. One way to attend them all is as shown. Attend the first event on day 1. Attend the second event on day 2. Attend the third event on day 3. Example 2: Input: events= [[1,2],[2,3],[3,4],[1,2]] Output: 4   Constraints: 1 <= events.length <= 100000 events[i].length == 2 1 <= startDayi <= endDayi <= 100000
class Solution: def maxEvents(self, events: List[List[int]]) -> int: heapq.heapify(events) d = events[0][0] ret = 0 n = len(events) while events: s, e = heapq.heappop(events) if s < d: if e >= d: heapq.heappush(events, [d, e]) else: ret += 1 d = max(s, d) + 1 return ret
1bd786
2ad748
You are given an array pairs, where pairs[i] = [xi, yi], and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose values appeared in pairs. A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi. Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: 0 if ways == 0 1 if ways == 1 2 if ways > 1 A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.   Example 1: Input: pairs = [[1,2],[2,3]] Output: 1 Explanation: There is exactly one valid rooted tree, which is shown in the above figure. Example 2: Input: pairs = [[1,2],[2,3],[1,3]] Output: 2 Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. Example 3: Input: pairs = [[1,2],[2,3],[2,4],[1,5]] Output: 0 Explanation: There are no valid rooted trees.   Constraints: 1 <= pairs.length <= 100000 1 <= xi < yi <= 500 The elements in pairs are unique.
class Solution: def checkWays(self, pairs: List[List[int]]) -> int: n = 0 a = set() for x in pairs: n = max(n, x[0], x[1]) a.add(x[0]) a.add(x[1]) d = [0] * (n + 1) e = [[] for _ in range(n + 1)] for x in pairs: d[x[0]] += 1 d[x[1]] += 1 e[x[0]].append(x[1]) e[x[1]].append(x[0]) roots = set() a = list(a) def work(a): if len(a) == 1: return 1 c = 0 o = -1 for x in a: if d[x] == len(a) - 1 + len(roots): c += 1 o = x if c == 0: return 0 roots.add(o) f = set() aa = [] for x in a: if x not in roots and x not in f: q = [x] f.add(x) t = 0 while t < len(q): y = q[t] t += 1 for z in e[y]: if z not in roots and z not in f: q.append(z) f.add(z) aa.append(q) for b in aa: r = work(b) if r == 0: return 0 c = max(r, c) roots.remove(o) return c r = work(a) if r > 1: return 2 return r
681970
e3f35f
Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.   Example 1: Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple" Example 2: Input: s = "abpcplea", dictionary = ["a","b","c"] Output: "a"   Constraints: 1 <= s.length <= 1000 1 <= dictionary.length <= 1000 1 <= dictionary[i].length <= 1000 s and dictionary[i] consist of lowercase English letters.
class Solution(object): def findLongestWord(self, S, d): d.sort(key = lambda x: (-len(x), x)) for word in d: i = j = 0 while i < len(word) and j < len(S): if word[i] == S[j]: i += 1 j += 1 if i == len(word): return word return ""
de90ec
5c7164
You are given an array words of size n consisting of non-empty strings. We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i]. For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i]. Note that a string is considered as a prefix of itself.   Example 1: Input: words = ["abc","ab","bc","b"] Output: [5,4,3,2] Explanation: The answer for each string is the following: - "abc" has 3 prefixes: "a", "ab", and "abc". - There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc". The total is answer[0] = 2 + 2 + 1 = 5. - "ab" has 2 prefixes: "a" and "ab". - There are 2 strings with the prefix "a", and 2 strings with the prefix "ab". The total is answer[1] = 2 + 2 = 4. - "bc" has 2 prefixes: "b" and "bc". - There are 2 strings with the prefix "b", and 1 string with the prefix "bc". The total is answer[2] = 2 + 1 = 3. - "b" has 1 prefix: "b". - There are 2 strings with the prefix "b". The total is answer[3] = 2. Example 2: Input: words = ["abcd"] Output: [4] Explanation: "abcd" has 4 prefixes: "a", "ab", "abc", and "abcd". Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists of lowercase English letters.
ddic = defaultdict class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: Trie = lambda: ddic(Trie) trie = Trie() COUNT = 0 for word in words: cur = trie for c in word: cur[COUNT] = cur.get(COUNT, 0) + 1 cur = cur[c] cur[COUNT] = cur.get(COUNT, 0) + 1 ans = [0] * len(words) for qid, word in enumerate(words): cur = trie bns = 0 for c in word: cur = cur[c] bns += cur[COUNT] ans[qid] = bns return ans
5ecab7
5c7164
You are given an array words of size n consisting of non-empty strings. We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i]. For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i]. Note that a string is considered as a prefix of itself.   Example 1: Input: words = ["abc","ab","bc","b"] Output: [5,4,3,2] Explanation: The answer for each string is the following: - "abc" has 3 prefixes: "a", "ab", and "abc". - There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc". The total is answer[0] = 2 + 2 + 1 = 5. - "ab" has 2 prefixes: "a" and "ab". - There are 2 strings with the prefix "a", and 2 strings with the prefix "ab". The total is answer[1] = 2 + 2 = 4. - "bc" has 2 prefixes: "b" and "bc". - There are 2 strings with the prefix "b", and 1 string with the prefix "bc". The total is answer[2] = 2 + 1 = 3. - "b" has 1 prefix: "b". - There are 2 strings with the prefix "b". The total is answer[3] = 2. Example 2: Input: words = ["abcd"] Output: [4] Explanation: "abcd" has 4 prefixes: "a", "ab", "abc", and "abcd". Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.   Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists of lowercase English letters.
class Node: def __init__(self): self.val = 0 self.ch = {} class Solution(object): def sumPrefixScores(self, words): """ :type words: List[str] :rtype: List[int] """ root = Node() def _add(word): u = root for ch in word: if ch not in u.ch: u.ch[ch] = Node() u = u.ch[ch] u.val += 1 def _query(word): r = 0 u = root for ch in word: if ch not in u.ch: break u = u.ch[ch] r += u.val return r for word in words: _add(word) return [_query(word) for word in words]
4e3930
327000
Design the CombinationIterator class: CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. next() Returns the next combination of length combinationLength in lexicographical order. hasNext() Returns true if and only if there exists a next combination.   Example 1: Input ["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [["abc", 2], [], [], [], [], [], []] Output [null, "ab", true, "ac", true, "bc", false] Explanation CombinationIterator itr = new CombinationIterator("abc", 2); itr.next(); // return "ab" itr.hasNext(); // return True itr.next(); // return "ac" itr.hasNext(); // return True itr.next(); // return "bc" itr.hasNext(); // return False   Constraints: 1 <= combinationLength <= characters.length <= 15 All the characters of characters are unique. At most 10000 calls will be made to next and hasNext. It is guaranteed that all calls of the function next are valid.
class CombinationIterator: def __init__(self, characters: str, combinationLength: int): self.c = characters self.l = combinationLength self.t = [x for x in range(self.l)] def next(self) -> str: ans = "" for t0 in self.t: ans += self.c[t0] j, k = self.l - 1, len(self.c) - 1 while j >= 0 and self.t[j] == k: j -= 1 k -= 1 if j == -1: self.t[0] = -1 else: self.t[j] += 1 for p in range(j + 1, self.l): self.t[p] = self.t[p - 1] + 1 return ans def hasNext(self) -> bool: return self.t[0] != -1 # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext()
ef3306
327000
Design the CombinationIterator class: CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. next() Returns the next combination of length combinationLength in lexicographical order. hasNext() Returns true if and only if there exists a next combination.   Example 1: Input ["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [["abc", 2], [], [], [], [], [], []] Output [null, "ab", true, "ac", true, "bc", false] Explanation CombinationIterator itr = new CombinationIterator("abc", 2); itr.next(); // return "ab" itr.hasNext(); // return True itr.next(); // return "ac" itr.hasNext(); // return True itr.next(); // return "bc" itr.hasNext(); // return False   Constraints: 1 <= combinationLength <= characters.length <= 15 All the characters of characters are unique. At most 10000 calls will be made to next and hasNext. It is guaranteed that all calls of the function next are valid.
class CombinationIterator(object): def __init__(self, characters, combinationLength): """ :type characters: str :type combinationLength: int """ self.s = characters self.k = combinationLength self.it = itertools.combinations(self.s, self.k) self.todo = self.binom(len(self.s), self.k) def binom(self, n, k): r = 1 for i in xrange(1, k+1): r *= n-i+1 r /= i return r def next(self): self.todo -= 1 return "".join(next(self.it)) def hasNext(self): return bool(self.todo) # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext()
19c5d5
0edeb2
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force.   Example 1: Input: position = [1,2,3,4,7], m = 3 Output: 3 Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. Example 2: Input: position = [5,4,3,2,1,1000000000], m = 2 Output: 999999999 Explanation: We can use baskets 1 and 1000000000.   Constraints: n == position.length 2 <= n <= 100000 1 <= position[i] <= 10^9 All integers in position are distinct. 2 <= m <= position.length
class Solution: def maxDistance(self, position: List[int], m: int) -> int: position.sort() head = 0 tail = position[-1] def good(x): start = -1e100 count = 0 for p in position: if p - start >= x: start = p count += 1 return count >= m while head < tail: mid = (head + tail) // 2 if good(mid + 1): head = mid + 1 else: tail = mid return head
2a3e5b
0edeb2
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force.   Example 1: Input: position = [1,2,3,4,7], m = 3 Output: 3 Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. Example 2: Input: position = [5,4,3,2,1,1000000000], m = 2 Output: 999999999 Explanation: We can use baskets 1 and 1000000000.   Constraints: n == position.length 2 <= n <= 100000 1 <= position[i] <= 10^9 All integers in position are distinct. 2 <= m <= position.length
class Solution(object): def maxDistance(self, position, m): """ :type position: List[int] :type m: int :rtype: int """ a = sorted(position) n = len(a) def _test(d): prev = float('-inf') x = 0 for i in a: if i - prev >= d: x += 1 prev = i if x >= m: return True return False x, y = 1, max(a) while x + 1 < y: z = (x + y) >> 1 if _test(z): x = z else: y = z return x
07d440
928f56
Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. Example 2: Input: arr = [7] Output: 0 Explanation: Start index is the last index. You do not need to jump. Example 3: Input: arr = [7,6,9,6,9,6,9,7] Output: 1 Explanation: You can jump directly from index 0 to index 7 which is last index of the array.   Constraints: 1 <= arr.length <= 5 * 10000 -10^8 <= arr[i] <= 10^8
class Solution(object): def minJumps(self, A): N = len(A) indexmap = collections.defaultdict(list) for i, x in enumerate(A): indexmap[x].append(i) pq = [[0, 0]] seen = {0} explored_vals = set() while pq: dist, node = heapq.heappop(pq) if node == N-1: return dist v = A[node] if v not in explored_vals: explored_vals.add(v) for i in indexmap[v]: if i not in seen: seen.add(i) heapq.heappush(pq, [dist + 1, i]) for nei in (node-1, node+1): if 0 <= nei < N and nei not in seen: seen.add(nei) heapq.heappush(pq, [dist+1, nei]) return N-1 """ graph = collections.defaultdict(list) i = 0 for k, grp in itertools.groupby(A): w = len(list(grp)) j = i + w - 1 if i -1 >= 0: graph[i].append(i-1) graph[i-1].append(i) if i != j: graph[i].append(j) graph[j].append(i) if j + 1 < N: graph[j].append(j+1) graph[j+1].append(j) i += w queue = collections.deque([[0,0]]) seen = {0} while queue: dist, node = queue.popleft() if node == N-1: return dist for nei in graph[node]: if nei not in seen: seen.add(nei) queue.append([dist + 1, nei]) return N-1 """
2653d1
928f56
Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. Example 2: Input: arr = [7] Output: 0 Explanation: Start index is the last index. You do not need to jump. Example 3: Input: arr = [7,6,9,6,9,6,9,7] Output: 1 Explanation: You can jump directly from index 0 to index 7 which is last index of the array.   Constraints: 1 <= arr.length <= 5 * 10000 -10^8 <= arr[i] <= 10^8
class Solution: def minJumps(self, arr: List[int]) -> int: graph = collections.defaultdict(list) for i, val in enumerate(arr): graph[val].append(i) queue = collections.deque([0]) costs = {0 : 0} nsteps = 0 target = len(arr) - 1 while queue: sz = len(queue) nsteps += 1 for _ in range(sz): idx = queue.popleft() if idx == target: return nsteps - 1 if idx > 0 and (idx - 1) not in costs: queue.append(idx - 1) costs[idx - 1] = nsteps if idx + 1 not in costs: queue.append(idx + 1) costs[idx + 1] = nsteps val = arr[idx] while graph[val]: nei = graph[val].pop() if nei not in costs: costs[nei] = nsteps queue.append(nei) return -1
01f8c7
faa9f8
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7.   Example 1: Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. Example 2: Input: arr = [11,81,94,43,3] Output: 444   Constraints: 1 <= arr.length <= 3 * 10000 1 <= arr[i] <= 3 * 10000
class Solution: def sumSubarrayMins(self, A): res = 0 mo = int(10**9+7) ret1 = self.getList(A, lambda x,y: x > y) ret2 = self.getList(list(reversed(A)), lambda x,y: x >= y) # print(ret1, ret2) for i, a, i1, i2 in zip(range(len(A)), A, ret1, reversed(ret2)): res += (i1-i)*(i-(len(A)-1-i2))*a res %= mo return res def getList(self, A, cmp): stk = [] ret = [-1] * len(A); for i, a in enumerate(A): while stk and cmp(stk[-1][0], a): ret[stk.pop()[1]] = i stk.append((a,i)) while stk: ret[stk.pop()[1]] = len(A); return ret
c5ab7e
faa9f8
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7.   Example 1: Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. Example 2: Input: arr = [11,81,94,43,3] Output: 444   Constraints: 1 <= arr.length <= 3 * 10000 1 <= arr[i] <= 3 * 10000
M = 10 ** 9 + 7 class Solution(object): def sumSubarrayMins(self, A): """ :type A: List[int] :rtype: int """ last = [A[0]] index_list = [-1] for i in xrange(1, len(A)): index = i - 1 this = A[i] while index > -1: if A[i] >= A[index]: this += last[index] this %= M last.append(this) index_list.append(index) break else: next_index = index_list[index] step = index - next_index index = next_index this += step * A[i] this %= M if index == -1: index_list.append(-1) last.append(this) return sum(last) % M
d9a1c0
bfaad3
You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali]. Initially, there is a 0-indexed n x n matrix filled with 0's. For each query, you must apply one of the following changes: if typei == 0, set the values in the row with indexi to vali, overwriting any previous values. if typei == 1, set the values in the column with indexi to vali, overwriting any previous values. Return the sum of integers in the matrix after all queries are applied.   Example 1: Input: n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] Output: 23 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. Example 2: Input: n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] Output: 17 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17.   Constraints: 1 <= n <= 104 1 <= queries.length <= 5 * 104 queries[i].length == 3 0 <= typei <= 1 0 <= indexi < n 0 <= vali <= 105
class Solution: def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int: queries.reverse() rows = set() cols = set() ans = 0 for t, i, v in queries: if t == 0 and i not in cols: ans += v * (n - len(rows)) cols.add(i) if t == 1 and i not in rows: ans += v * (n - len(cols)) rows.add(i) return ans
5126db
bfaad3
You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali]. Initially, there is a 0-indexed n x n matrix filled with 0's. For each query, you must apply one of the following changes: if typei == 0, set the values in the row with indexi to vali, overwriting any previous values. if typei == 1, set the values in the column with indexi to vali, overwriting any previous values. Return the sum of integers in the matrix after all queries are applied.   Example 1: Input: n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] Output: 23 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. Example 2: Input: n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] Output: 17 Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17.   Constraints: 1 <= n <= 104 1 <= queries.length <= 5 * 104 queries[i].length == 3 0 <= typei <= 1 0 <= indexi < n 0 <= vali <= 105
class Solution(object): def matrixSumQueries(self, n, queries): """ :type n: int :type queries: List[List[int]] :rtype: int """ ans = 0 rowvisit = set() colvisit = set() for [t,index,num] in queries[::-1]: if t==0: if index in rowvisit: continue rowvisit.add(index) ans += (n - len(colvisit))* num else: if index in colvisit: continue colvisit.add(index) ans += (n - len(rowvisit)) * num return ans
41626d
398175
Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following: Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree. He tells Alice that u is the parent of v in the tree. Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj. Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true. Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0.   Example 1: Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3 Output: 3 Explanation: Root = 0, correct guesses = [1,3], [0,1], [2,4] Root = 1, correct guesses = [1,3], [1,0], [2,4] Root = 2, correct guesses = [1,3], [1,0], [2,4] Root = 3, correct guesses = [1,0], [2,4] Root = 4, correct guesses = [1,3], [1,0] Considering 0, 1, or 2 as root node leads to 3 correct guesses. Example 2: Input: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1 Output: 5 Explanation: Root = 0, correct guesses = [3,4] Root = 1, correct guesses = [1,0], [3,4] Root = 2, correct guesses = [1,0], [2,1], [3,4] Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4] Root = 4, correct guesses = [1,0], [2,1], [3,2] Considering any node as root will give at least 1 correct guess.   Constraints: edges.length == n - 1 2 <= n <= 100000 1 <= guesses.length <= 100000 0 <= ai, bi, uj, vj <= n - 1 ai != bi uj != vj edges represents a valid tree. guesses[j] is an edge of the tree. guesses is unique. 0 <= k <= guesses.length
from typing import Callable, Generic, List, TypeVar, Optional MOD = int(1e9 + 7) INF = int(1e20) # Alice 有一棵 n 个节点的树,节点编号为 0 到 n - 1 。树用一个长度为 n - 1 的二维整数数组 edges 表示,其中 edges[i] = [ai, bi] ,表示树中节点 ai 和 bi 之间有一条边。 # Alice 想要 Bob 找到这棵树的根。她允许 Bob 对这棵树进行若干次 猜测 。每一次猜测,Bob 做如下事情: # 选择两个 不相等 的整数 u 和 v ,且树中必须存在边 [u, v] 。 # Bob 猜测树中 u 是 v 的 父节点 。 # Bob 的猜测用二维整数数组 guesses 表示,其中 guesses[j] = [uj, vj] 表示 Bob 猜 uj 是 vj 的父节点。 # Alice 非常懒,她不想逐个回答 Bob 的猜测,只告诉 Bob 这些猜测里面 至少 有 k 个猜测的结果为 true 。 # 给你二维整数数组 edges ,Bob 的所有猜测和整数 k ,请你返回可能成为树根的 节点数目 。如果没有这样的树,则返回 0。 T = TypeVar("T") class Rerooting(Generic[T]): __slots__ = ("adjList", "_n", "_decrement") def __init__(self, n: int, decrement: int = 0): self.adjList = [[] for _ in range(n)] self._n = n self._decrement = decrement def addEdge(self, u: int, v: int) -> None: u -= self._decrement v -= self._decrement self.adjList[u].append(v) self.adjList[v].append(u) def rerooting( self, e: Callable[[int], T], op: Callable[[T, T], T], composition: Callable[[T, int, int, int], T], root=0, ) -> List["T"]: root -= self._decrement assert 0 <= root < self._n parents = [-1] * self._n order = [root] stack = [root] while stack: cur = stack.pop() for next in self.adjList[cur]: if next == parents[cur]: continue parents[next] = cur order.append(next) stack.append(next) dp1 = [e(i) for i in range(self._n)] dp2 = [e(i) for i in range(self._n)] for cur in order[::-1]: res = e(cur) for next in self.adjList[cur]: if parents[cur] == next: continue dp2[next] = res res = op(res, composition(dp1[next], cur, next, 0)) res = e(cur) for next in self.adjList[cur][::-1]: if parents[cur] == next: continue dp2[next] = op(res, dp2[next]) res = op(res, composition(dp1[next], cur, next, 0)) dp1[cur] = res for newRoot in order[1:]: parent = parents[newRoot] dp2[newRoot] = composition(op(dp2[newRoot], dp2[parent]), parent, newRoot, 1) dp1[newRoot] = op(dp1[newRoot], dp2[newRoot]) return dp1 class Solution: def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int: def e(root: int) -> int: return 0 def op(childRes1: int, childRes2: int) -> int: return childRes1 + childRes2 def composition(fromRes: int, parent: int, cur: int, direction: int) -> int: if direction == 0: # cur -> parent return fromRes + int((parent, cur) in ok) return fromRes + int((cur, parent) in ok) ok = set(tuple(x) for x in guesses) n = len(edges) + 1 R = Rerooting(n) for u, v in edges: R.addEdge(u, v) res = R.rerooting(e, op, composition) return sum(x >= k for x in res)
0c2a4d
398175
Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following: Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree. He tells Alice that u is the parent of v in the tree. Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj. Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true. Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0.   Example 1: Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3 Output: 3 Explanation: Root = 0, correct guesses = [1,3], [0,1], [2,4] Root = 1, correct guesses = [1,3], [1,0], [2,4] Root = 2, correct guesses = [1,3], [1,0], [2,4] Root = 3, correct guesses = [1,0], [2,4] Root = 4, correct guesses = [1,3], [1,0] Considering 0, 1, or 2 as root node leads to 3 correct guesses. Example 2: Input: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1 Output: 5 Explanation: Root = 0, correct guesses = [3,4] Root = 1, correct guesses = [1,0], [3,4] Root = 2, correct guesses = [1,0], [2,1], [3,4] Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4] Root = 4, correct guesses = [1,0], [2,1], [3,2] Considering any node as root will give at least 1 correct guess.   Constraints: edges.length == n - 1 2 <= n <= 100000 1 <= guesses.length <= 100000 0 <= ai, bi, uj, vj <= n - 1 ai != bi uj != vj edges represents a valid tree. guesses[j] is an edge of the tree. guesses is unique. 0 <= k <= guesses.length
class Solution(object): def rootCount(self, edges, guesses, k): """ :type edges: List[List[int]] :type guesses: List[List[int]] :type k: int :rtype: int """ n = len(edges)+1 nei = [set() for _ in range(n)] pp = [-1]*n xx = [set() for _ in range(n)] for a, b in edges: nei[a].add(b) nei[b].add(a) for a, b in guesses: # xx[a].add(b) xx[b].add(a) rr = [0, 0] def build(r, p): pp[r]=p if p in xx[r]: rr[0]+=1 for b in nei[r]: if b==p: continue build(b, r) build(0, -1) if rr[0]>=k: rr[1]+=1 # print rr def dfs(r, p): for b in nei[r]: if b==p: continue # change b, p if r in xx[b]: rr[0]-=1 if b in xx[r]: rr[0]+=1 if rr[0]>=k: # print r, b rr[1]+=1 dfs(b, r) if r in xx[b]: rr[0]+=1 if b in xx[r]: rr[0]-=1 dfs(0, -1) return rr[1]
c6febb
7d109d
Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition.   Example 1: Input: seats = [["#",".","#","#",".","#"],   [".","#","#","#","#","."],   ["#",".","#","#",".","#"]] Output: 4 Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. Example 2: Input: seats = [[".","#"],   ["#","#"],   ["#","."],   ["#","#"],   [".","#"]] Output: 3 Explanation: Place all students in available seats. Example 3: Input: seats = [["#",".",".",".","#"],   [".","#",".","#","."],   [".",".","#",".","."],   [".","#",".","#","."],   ["#",".",".",".","#"]] Output: 10 Explanation: Place students in available seats in column 1, 3 and 5.   Constraints: seats contains only characters '.' and'#'. m == seats.length n == seats[i].length 1 <= m <= 8 1 <= n <= 8
class Solution(object): def maxStudents(self, A): R, C = len(A), len(A[0]) for r, row in enumerate(A): for c, val in enumerate(row): if val == '.': A[r][c] = True else: A[r][c] = False # dp on state transitions legal = [[] for _ in xrange(R)] for cand in itertools.product((0, 1), repeat=C): if any(cand[i] and cand[i+1] for i in xrange(C-1)): continue for r in xrange(R): if any(cand[i] and not A[r][i] for i in xrange(C)): continue legal[r].append(cand) dp = {} for cand in legal[0]: dp[cand] = sum(cand) for r in xrange(1, R): dp2 = {} for cand, s in dp.items(): for cand2 in legal[r]: s2 = sum(cand2) v2 = dp2.get(cand2, -1) if v2 >= s+s2: continue for i in xrange(C): if cand[i]: if i-1>=0 and cand2[i-1] or i+1<C and cand2[i+1]: break else: dp2[cand2] = s2 + s dp = dp2 return max(dp.values())
01c359
7d109d
Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition.   Example 1: Input: seats = [["#",".","#","#",".","#"],   [".","#","#","#","#","."],   ["#",".","#","#",".","#"]] Output: 4 Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. Example 2: Input: seats = [[".","#"],   ["#","#"],   ["#","."],   ["#","#"],   [".","#"]] Output: 3 Explanation: Place all students in available seats. Example 3: Input: seats = [["#",".",".",".","#"],   [".","#",".","#","."],   [".",".","#",".","."],   [".","#",".","#","."],   ["#",".",".",".","#"]] Output: 10 Explanation: Place students in available seats in column 1, 3 and 5.   Constraints: seats contains only characters '.' and'#'. m == seats.length n == seats[i].length 1 <= m <= 8 1 <= n <= 8
class Solution: def maxStudents(self, seats: List[List[str]]) -> int: storage = [] for index,row in enumerate(seats): storage.append(dict()) allrows = self.generateAllRows(row) for arangement in allrows: if len(storage)==1: storage[-1][arangement] = len(arangement) else: nogood = set() for taken in arangement: nogood.add(taken+1) nogood.add(taken-1) if taken in nogood: good = False bestprevrow = 0 for prevarangement in storage[-2]: good = True for taken in prevarangement: if taken in nogood: good = False break if good: if storage[-2][prevarangement]>bestprevrow: bestprevrow = storage[-2][prevarangement] storage[-1][arangement] = len(arangement)+bestprevrow return max(storage[-1].values()) def generateAllRows(self,row,pos = 0): # returns a list of format [[a,b,c],...] where a,b and c are indecies where students can sit if len(row)<=pos: return [tuple()] if row[pos] == '#': return self.generateAllRows(row,pos+1) else: temp = self.generateAllRows(row,pos+1) temp2 = [] for a in temp: if pos+1 not in a: temp2.append(a+(pos,)) return temp+temp2
8fa113
4060a1
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes. The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed. You are given an integer array nums representing how much money is stashed in each house. More formally, the ith house from the left has nums[i] dollars. You are also given an integer k, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k houses. Return the minimum capability of the robber out of all the possible ways to steal at least k houses.   Example 1: Input: nums = [2,3,5,9], k = 2 Output: 5 Explanation: There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. Example 2: Input: nums = [2,7,9,3,1], k = 2 Output: 2 Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= k <= (nums.length + 1)/2
class Solution(object): def minCapability(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def i(m): c = [0 if nums[0] > m else 1, 0 if nums[1] > m and nums[0] > m else 1] + [0] * (len(nums) - 2) for i in range(2, len(nums)): c[i] = c[i - 1] if nums[i] > m else max(c[i - 2] + 1, c[i - 1]) return c[-1] >= k if len(nums) == 1: return nums[0] l, r = 0, 1000000000 while l < r: r, l = (l + r) / 2 if i((l + r) / 2) else r, l if i((l + r) / 2) else (l + r) / 2 + 1 return l
600e6b
4060a1
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes. The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed. You are given an integer array nums representing how much money is stashed in each house. More formally, the ith house from the left has nums[i] dollars. You are also given an integer k, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k houses. Return the minimum capability of the robber out of all the possible ways to steal at least k houses.   Example 1: Input: nums = [2,3,5,9], k = 2 Output: 5 Explanation: There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. Example 2: Input: nums = [2,7,9,3,1], k = 2 Output: 2 Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9 1 <= k <= (nums.length + 1)/2
class Solution: def minCapability(self, nums: List[int], k: int) -> int: snums = sorted(nums) to_ret = snums[-1] s, e = k-2, len(snums)-1 # 不够大,够大 while e > s + 1 : mid = (s+e) // 2 maxv = snums[mid] usen = 0 usei = -2 for i, t in enumerate(nums) : if i == usei + 1 or t > maxv: continue usei = i usen += 1 if usen >= k : to_ret = maxv e = mid else : s = mid return to_ret
04e70a
fe4368
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing. A 0-indexed string num of length n + 1 is created using the following conditions: num consists of the digits '1' to '9', where each digit is used at most once. If pattern[i] == 'I', then num[i] < num[i + 1]. If pattern[i] == 'D', then num[i] > num[i + 1]. Return the lexicographically smallest possible string num that meets the conditions.   Example 1: Input: pattern = "IIIDIDDD" Output: "123549876" Explanation: At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1]. At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1]. Some possible values of num are "245639871", "135749862", and "123849765". It can be proven that "123549876" is the smallest possible num that meets the conditions. Note that "123414321" is not possible because the digit '1' is used more than once. Example 2: Input: pattern = "DDD" Output: "4321" Explanation: Some possible values of num are "9876", "7321", and "8742". It can be proven that "4321" is the smallest possible num that meets the conditions.   Constraints: 1 <= pattern.length <= 8 pattern consists of only the letters 'I' and 'D'.
class Solution: def smallestNumber(self, pattern: str) -> str: def solve(p, digits): if not p: return min(digits) for d in sorted(digits): rem = digits[:] rem.remove(d) rest = solve(p[1:], rem) if p[0] == 'I': if d < rest[0]: return d + rest else: if d > rest[0]: return d + rest return solve(pattern, list('123456789'))
0a4caa
fe4368
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing. A 0-indexed string num of length n + 1 is created using the following conditions: num consists of the digits '1' to '9', where each digit is used at most once. If pattern[i] == 'I', then num[i] < num[i + 1]. If pattern[i] == 'D', then num[i] > num[i + 1]. Return the lexicographically smallest possible string num that meets the conditions.   Example 1: Input: pattern = "IIIDIDDD" Output: "123549876" Explanation: At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1]. At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1]. Some possible values of num are "245639871", "135749862", and "123849765". It can be proven that "123549876" is the smallest possible num that meets the conditions. Note that "123414321" is not possible because the digit '1' is used more than once. Example 2: Input: pattern = "DDD" Output: "4321" Explanation: Some possible values of num are "9876", "7321", and "8742". It can be proven that "4321" is the smallest possible num that meets the conditions.   Constraints: 1 <= pattern.length <= 8 pattern consists of only the letters 'I' and 'D'.
class Solution(object): def smallestNumber(self, pattern): """ :type pattern: str :rtype: str """ m, s, t, i = 0, [], set(), 0 while i < len(pattern): c, j = pattern[i], i while j < len(pattern) and pattern[j] == c: j += 1 n = m + j - i while i < j: if c == 'I': for k in range(1, 10): if not k in t: s.append(str(k)) t.add(k) break else: s.append(str(m + j - i + 1)) t.add(m + j - i + 1) i += 1 m = n for k in range(1, 10): if not k in t: s.append(str(k)) t.add(k) break return ''.join(s)
13c474
d6634e
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Cover all the empty cells. Do not cover any of the occupied cells. We can put as many stamps as we want. Stamps can overlap with each other. Stamps are not allowed to be rotated. Stamps must stay completely inside the grid. Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.   Example 1: Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3 Output: true Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells. Example 2: Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 Output: false Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.   Constraints: m == grid.length n == grid[r].length 1 <= m, n <= 100000 1 <= m * n <= 2 * 100000 grid[r][c] is either 0 or 1. 1 <= stampHeight, stampWidth <= 100000
class Solution: def possibleToStamp(self, grid: List[List[int]], p: int, q: int) -> bool: r, c = len(grid), len(grid[0]) psa = [[0]*(c+1) for i in range(r+1)] for i in range(r): for j in range(c): psa[i+1][j+1] = psa[i][j+1]+psa[i+1][j]-psa[i][j]+grid[i][j] dif = [[0]*(c+1) for i in range(r+1)] for i in range(r-p+1): for j in range(c-q+1): rect = psa[i+p][j+q]-psa[i][j+q]-psa[i+p][j]+psa[i][j] if rect == 0: #print('test', i, j) dif[i][j] += 1 dif[i+p][j] -= 1 dif[i][j+q] -= 1 dif[i+p][j+q] +=1 for i in range(r+1): for j in range(c): dif[i][j+1] += dif[i][j] for j in range(c+1): for i in range(r): dif[i+1][j] += dif[i][j] for i in range(r): for j in range(c): if grid[i][j]+dif[i][j]== 0: return False return True
ad37f5
d6634e
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Cover all the empty cells. Do not cover any of the occupied cells. We can put as many stamps as we want. Stamps can overlap with each other. Stamps are not allowed to be rotated. Stamps must stay completely inside the grid. Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.   Example 1: Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3 Output: true Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells. Example 2: Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 Output: false Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.   Constraints: m == grid.length n == grid[r].length 1 <= m, n <= 100000 1 <= m * n <= 2 * 100000 grid[r][c] is either 0 or 1. 1 <= stampHeight, stampWidth <= 100000
class Solution(object): def possibleToStamp(self, M, h, w): m, n = len(M), len(M[0]) A = [[0] * (n + 1) for _ in range(m + 1)] good = [[0] * n for _ in range(m)] for i in xrange(m): for j in xrange(n): A[i+1][j+1] = A[i+1][j] + A[i][j+1] - A[i][j] + (1 - M[i][j]) if i + 1 >= h and j + 1 >= w: x, y = i+1-h, j+1-w if A[i+1][j+1] - A[x][j+1] - A[i+1][y] + A[x][y] == w*h: good[i][j] += 1 # for r in A: print r # for r in good: print r B = [[0] * (n + 1) for _ in range(m + 1)] for i in xrange(m): for j in xrange(n): B[i+1][j+1] = B[i+1][j] + B[i][j+1] - B[i][j] + good[i][j] for i in xrange(m): for j in xrange(n): if M[i][j] == 1: continue x,y = min(i+h,m),min(j+w,n) if B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0: return False return True
95a144
341568
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path.   Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 1 <= grid[i][j] <= 4
class Solution: def minCost(self, grid: List[List[int]]) -> int: directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] rows = len(grid) cols = len(grid[0]) pq = [] heapq.heappush(pq, (0, 0, 0)) best = {} best[(0, 0)] = 0 while len(pq) > 0: d, x, y = heapq.heappop(pq) if x == rows - 1 and y == cols - 1: return d for i, (dx, dy) in enumerate(directions): nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols: cost = 1 if i + 1 == grid[x][y]: cost = 0 newd = d + cost if (nx, ny) not in best or best[(nx, ny)] > newd: heapq.heappush(pq, (newd, nx, ny)) best[(nx, ny)] = newd return 0
1db026
341568
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path.   Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 1 <= grid[i][j] <= 4
class Solution(object): def minCost(self, grid): """ :type grid: List[List[int]] :rtype: int """ f = {} h = set() f[(0, 0)] = 0 q = [(0, 0)] t = 0 h.add((0, 0)) d = {1: (0, 1), 2: (0, -1), 3: (1, 0), 4: (-1, 0)} while t < len(q): x = q[t] t += 1 h.remove(x) for i in d: y = (x[0] + d[i][0], x[1] + d[i][1]) if not (0 <= y[0] < len(grid) and 0 <= y[1] < len(grid[0])): continue c = 0 if grid[x[0]][x[1]] == i else 1 if y not in f or f[y] > f[x] + c: f[y] = f[x] + c if y not in h: h.add(y) q.append(y) return f[(len(grid) - 1, len(grid[0]) - 1)]
63e34d
c01348
Given strings s1 and s2, return the minimum contiguous substring part of s1, so that s2 is a subsequence of the part. If there is no such window in s1 that covers all characters in s2, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index. Example 1: Input: s1 = "abcdebdde", s2 = "bde" Output: "bcde" Explanation: "bcde" is the answer because it occurs before "bdde" which has the same length. "deb" is not a smaller window because the elements of s2 in the window must occur in order. Example 2: Input: s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u" Output: "" Constraints: 1 <= s1.length <= 2 * 10000 1 <= s2.length <= 100 s1 and s2 consist of lowercase English letters.
class Solution(object): def minWindow(self, S, T): """ :type S: str :type T: str :rtype: str """ m=len(S) n=len(T) dp=[[float('inf')]*(m+1) for _ in xrange(n+1)] for i in xrange(m+1): dp[n][i]=0 for i in xrange(n-1,-1,-1): for j in xrange(m-1,-1,-1): dp[i][j]=1+(dp[i+1][j+1] if S[j]==T[i] else dp[i][j+1]) best=float('inf') pos=-1 for j in xrange(m-n+1): if dp[0][j]<best: best=dp[0][j] pos=j return '' if pos==-1 else S[pos:pos+best]
7a6a47
c01348
Given strings s1 and s2, return the minimum contiguous substring part of s1, so that s2 is a subsequence of the part. If there is no such window in s1 that covers all characters in s2, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index. Example 1: Input: s1 = "abcdebdde", s2 = "bde" Output: "bcde" Explanation: "bcde" is the answer because it occurs before "bdde" which has the same length. "deb" is not a smaller window because the elements of s2 in the window must occur in order. Example 2: Input: s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u" Output: "" Constraints: 1 <= s1.length <= 2 * 10000 1 <= s2.length <= 100 s1 and s2 consist of lowercase English letters.
class Solution: def minWindow(self, S, T): """ :type S: str :type T: str :rtype: str """ if len(T) == 1: for c in S: if c == T[0]: return c return "" m = len(S) n = len(T) ans = [-1]*n res = (-1, -1) cnt = 200000 for i in range(m): for j in range(n-1, -1, -1): if S[i] == T[j]: if j == 0: ans[j] = i else: ans[j] = max(ans[j], ans[j-1]) if ans[-1] > -1: if i - ans[-1] + 1 < cnt: res = (ans[-1], i) cnt = i - ans[-1] + 1 if res[0] != -1: return S[res[0]:res[1]+1] return ""
22ede6
486b67
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).   Example 1: Input: root = [1,3,2,5,3,null,9] Output: [1,3,9] Example 2: Input: root = [1,2,3] Output: [1,3]   Constraints: The number of nodes in the tree will be in the range [0, 10000]. -2^31 <= Node.val <= 2^31 - 1
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def largestValues(self, root): return self.findValueMostElement(root) def findValueMostElement(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] from collections import deque bag = deque([(root,0)]) pdx = -1 out = [] while len(bag): n,r = bag.pop() if r != pdx: pdx = r out.append(n.val) else: out[-1] = max(out[-1], n.val) if n.left is not None: bag.appendleft((n.left,r+1)) if n.right is not None: bag.appendleft((n.right,r+1)) return out
be1a9c
023b9a
A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Adding scenic locations, one at a time. Querying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added. Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: SORTracker() Initializes the tracker system. void add(string name, int score) Adds a scenic location with name and score to the system. string get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).   Example 1: Input ["SORTracker", "add", "add", "get", "add", "get", "add", "get", "add", "get", "add", "get", "get"] [[], ["bradford", 2], ["branford", 3], [], ["alps", 2], [], ["orland", 2], [], ["orlando", 3], [], ["alpine", 2], [], []] Output [null, null, null, "branford", null, "alps", null, "bradford", null, "bradford", null, "bradford", "orland"] Explanation SORTracker tracker = new SORTracker(); // Initialize the tracker system. tracker.add("bradford", 2); // Add location with name="bradford" and score=2 to the system. tracker.add("branford", 3); // Add location with name="branford" and score=3 to the system. tracker.get(); // The sorted locations, from best to worst, are: branford, bradford. // Note that branford precedes bradford due to its higher score (3 > 2). // This is the 1st time get() is called, so return the best location: "branford". tracker.add("alps", 2); // Add location with name="alps" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford. // Note that alps precedes bradford even though they have the same score (2). // This is because "alps" is lexicographically smaller than "bradford". // Return the 2nd best location "alps", as it is the 2nd time get() is called. tracker.add("orland", 2); // Add location with name="orland" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford, orland. // Return "bradford", as it is the 3rd time get() is called. tracker.add("orlando", 3); // Add location with name="orlando" and score=3 to the system. tracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland. // Return "bradford". tracker.add("alpine", 2); // Add location with name="alpine" and score=2 to the system. tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "bradford". tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "orland".   Constraints: name consists of lowercase English letters, and is unique among all locations. 1 <= name.length <= 10 1 <= score <= 100000 At any time, the number of calls to get does not exceed the number of calls to add. At most 4 * 10000 calls in total will be made to add and get.
from sortedcontainers import SortedList class SORTracker: def __init__(self): self.data = SortedList([]) self.cnt = 0 def add(self, name: str, score: int) -> None: self.data.add((-score, name)) def get(self) -> str: self.cnt += 1 return self.data[self.cnt - 1][1] # Your SORTracker object will be instantiated and called as such: # obj = SORTracker() # obj.add(name,score) # param_2 = obj.get()
978744
023b9a
A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Adding scenic locations, one at a time. Querying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added. Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: SORTracker() Initializes the tracker system. void add(string name, int score) Adds a scenic location with name and score to the system. string get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).   Example 1: Input ["SORTracker", "add", "add", "get", "add", "get", "add", "get", "add", "get", "add", "get", "get"] [[], ["bradford", 2], ["branford", 3], [], ["alps", 2], [], ["orland", 2], [], ["orlando", 3], [], ["alpine", 2], [], []] Output [null, null, null, "branford", null, "alps", null, "bradford", null, "bradford", null, "bradford", "orland"] Explanation SORTracker tracker = new SORTracker(); // Initialize the tracker system. tracker.add("bradford", 2); // Add location with name="bradford" and score=2 to the system. tracker.add("branford", 3); // Add location with name="branford" and score=3 to the system. tracker.get(); // The sorted locations, from best to worst, are: branford, bradford. // Note that branford precedes bradford due to its higher score (3 > 2). // This is the 1st time get() is called, so return the best location: "branford". tracker.add("alps", 2); // Add location with name="alps" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford. // Note that alps precedes bradford even though they have the same score (2). // This is because "alps" is lexicographically smaller than "bradford". // Return the 2nd best location "alps", as it is the 2nd time get() is called. tracker.add("orland", 2); // Add location with name="orland" and score=2 to the system. tracker.get(); // Sorted locations: branford, alps, bradford, orland. // Return "bradford", as it is the 3rd time get() is called. tracker.add("orlando", 3); // Add location with name="orlando" and score=3 to the system. tracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland. // Return "bradford". tracker.add("alpine", 2); // Add location with name="alpine" and score=2 to the system. tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "bradford". tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland. // Return "orland".   Constraints: name consists of lowercase English letters, and is unique among all locations. 1 <= name.length <= 10 1 <= score <= 100000 At any time, the number of calls to get does not exceed the number of calls to add. At most 4 * 10000 calls in total will be made to add and get.
from sortedcontainers import SortedList class SORTracker(object): def __init__(self): self.A = SortedList() self.i = 0 def add(self, name, score): self.A.add([-score, name]) def get(self): self.i += 1 return self.A[self.i - 1][1] # Your SORTracker object will be instantiated and called as such: # obj = SORTracker() # obj.add(name,score) # param_2 = obj.get()
7b51a6
4be4f2
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.   Example 1: Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] Output: 3 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. Example 2: Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] Output: 2 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.   Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m, n <= 500 grid1[i][j] and grid2[i][j] are either 0 or 1.
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: h,w=len(grid1),len(grid1[0]) vis=[[0]*w for _ in range(h)] def bfs(y,x): notIn1=False if grid1[y][x]==0: notIn1=True q=[(y,x)] vis[y][x]=1 qi=0 dirs=[0,1,0,-1,0] while qi < len(q): y,x=q[qi] qi+=1 for k in range(4): ny,nx=y+dirs[k],x+dirs[k+1] if 0<=ny<h and 0<=nx<w and grid2[ny][nx] and not vis[ny][nx]: vis[ny][nx]=1 q.append((ny,nx)) if grid1[ny][nx]==0: notIn1=True if notIn1: return 0 else: return 1 ans=0 for y in range(h): for x in range(w): if grid2[y][x] and not vis[y][x]: ans+=bfs(y,x) return ans
950540
4be4f2
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.   Example 1: Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] Output: 3 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. Example 2: Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] Output: 2 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.   Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m, n <= 500 grid1[i][j] and grid2[i][j] are either 0 or 1.
class Solution(object): def countSubIslands(self, grid1, grid2): """ :type grid1: List[List[int]] :type grid2: List[List[int]] :rtype: int """ n = len(grid1) m = len(grid1[0]) mx = [0, 1, 0, -1] my = [1, 0, -1, 0] idx = 2 for i in range(n): for j in range(m): if grid1[i][j] == 1: q = [[i, j]] grid1[i][j] = idx while len(q) > 0: x, y = q[0] q = q[1:] for k in range(4): nx = x + mx[k] ny = y + my[k] if nx >= 0 and nx < n and ny >= 0 and ny < m and grid1[nx][ny] == 1: q.append([nx, ny]) grid1[nx][ny] = idx idx += 1 for i in range(n): for j in range(m): if grid2[i][j] == 1: q = [[i, j]] grid2[i][j] = idx while len(q) > 0: x, y = q[0] q = q[1:] for k in range(4): nx = x + mx[k] ny = y + my[k] if nx >= 0 and nx < n and ny >= 0 and ny < m and grid2[nx][ny] == 1: q.append([nx, ny]) grid2[nx][ny] = idx idx += 1 fdict = dict() for i in range(n): for j in range(m): if grid2[i][j] != 0: x = grid2[i][j] if not x in fdict: fdict[x] = dict() fdict[x][grid1[i][j]] = 1 ans = 0 for v in fdict: if len(fdict[v].keys()) == 1 and fdict[v].keys()[0] != 0: ans += 1 return ans
997723
de0eaf
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.   Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1]. Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5 Explanation: The repeated subarray with maximum length is [0,0,0,0,0].   Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 100
class Solution: def findLength(self, a, b): """ :type A: List[int] :type B: List[int] :rtype: int """ ans = 0 n,m = len(a),len(b) pre = [0]*(m+1) for i in range(1,n+1): cur = [0] for j in range(1,m+1): val = 0 if a[i-1]==b[j-1]: val = pre[j-1]+1 cur.append(val) ans=max(ans,cur[-1]) pre = cur return ans
83dcda
de0eaf
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.   Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1]. Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5 Explanation: The repeated subarray with maximum length is [0,0,0,0,0].   Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 100
class Solution(object): def findLength(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ l1 = len(A) l2 = len(B) f = [[0]*l2 for _ in range(l1)] for i in range(l1): for j in range(l2): if A[i] == B[j]: if i>0 and j>0: this = f[i-1][j-1] + 1 else: this = 1 if f[i][j] < this: f[i][j] = this # if i>0 and f[i][j] < f[i-1][j]: # f[i][j] = f[i-1][j] # if j>0 and f[i][j] < f[i][j-1]: # f[i][j] = f[i][j-1] # print f[2][4] # print A[2], B[4] # print f[1][3] return max(map(max, f))
125a18
0033e5
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3]. Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order. It is guaranteed an answer exists.   Example 1: Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2] Example 2: Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2]   Constraints: 1 <= req_skills.length <= 16 1 <= req_skills[i].length <= 16 req_skills[i] consists of lowercase English letters. All the strings of req_skills are unique. 1 <= people.length <= 60 0 <= people[i].length <= 16 1 <= people[i][j].length <= 16 people[i][j] consists of lowercase English letters. All the strings of people[i] are unique. Every skill in people[i] is a skill in req_skills. It is guaranteed a sufficient team exists.
class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: people = [(lst, i) for i, lst in enumerate(people)] people.sort(key=lambda x : len(x[0]), reverse=True) reqs = {skill : i for i, skill in enumerate(req_skills)} n = len(reqs) nstates = (1 << n) dp = [list(range(len(people))) for state in range(nstates)] dp[0] = [] for lst, i in people: skill = 0 for item in lst: idx = reqs.get(item, None) if idx is not None: skill |= (1 << idx) for key, value in enumerate(dp): new = (skill | key) if new != key and len(dp[new]) > len(value) + 1: dp[new] = value + [i] return sorted(dp[nstates - 1])
7a856e
0033e5
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3]. Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order. It is guaranteed an answer exists.   Example 1: Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2] Example 2: Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2]   Constraints: 1 <= req_skills.length <= 16 1 <= req_skills[i].length <= 16 req_skills[i] consists of lowercase English letters. All the strings of req_skills are unique. 1 <= people.length <= 60 0 <= people[i].length <= 16 1 <= people[i][j].length <= 16 people[i][j] consists of lowercase English letters. All the strings of people[i] are unique. Every skill in people[i] is a skill in req_skills. It is guaranteed a sufficient team exists.
class Solution(object): def smallestSufficientTeam(self, req_skills, people): """ :type req_skills: List[str] :type people: List[List[str]] :rtype: List[int] """ n = len(req_skills) m = len(people) d = {s:1<<i for i, s in enumerate(req_skills)} p = [sum(d[s] for s in person) for person in people] f = [(float('inf'), None)]*(1<<n) f[0] = (0, []) for i, v in enumerate(p): for w in xrange(1<<n): if not ~w&v: continue if f[w|v][0] <= f[w][0] + 1: continue f[w|v] = (f[w][0]+1, f[w][1]+[i]) return f[-1][1]
1c7d11
515d08
You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0). Starting from the cell (i, j), you can move to one of the following cells: Cells (i, k) with j < k <= grid[i][j] + j (rightward movement), or Cells (k, j) with i < k <= grid[i][j] + i (downward movement). Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1). If there is no valid path, return -1.   Example 1: Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] Output: 4 Explanation: The image above shows one of the paths that visits exactly 4 cells. Example 2: Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] Output: 3 Explanation: The image above shows one of the paths that visits exactly 3 cells. Example 3: Input: grid = [[2,1,0],[1,0,0]] Output: -1 Explanation: It can be proven that no path exists.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10^5 1 <= m * n <= 10^5 0 <= grid[i][j] < m * n grid[m - 1][n - 1] == 0
class Solution(object): def minimumVisitedCells(self, grid): """ :type grid: List[List[int]] :rtype: int """ r, c, q, e = [0] * len(grid), [0] * len(grid[0]), deque([[0, 0]]), 1 while q: for i in range(len(q), 0, -1): if q[0][0] == len(grid) - 1 and q[0][1] == len(grid[0]) - 1: return e r[q[0][0]], c[q[0][1]] = max(r[q[0][0]], q[0][1] + 1), max(c[q[0][1]], q[0][0] + 1) while r[q[0][0]] < len(grid[0]) and r[q[0][0]] <= q[0][1] + grid[q[0][0]][q[0][1]]: q.append([q[0][0], r[q[0][0]]]) r[q[0][0]] += 1 while c[q[0][1]] < len(grid) and c[q[0][1]] <= q[0][0] + grid[q[0][0]][q[0][1]]: q.append([c[q[0][1]], q[0][1]]) c[q[0][1]] += 1 q.popleft() e += 1 return -1
9d673b
515d08
You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0). Starting from the cell (i, j), you can move to one of the following cells: Cells (i, k) with j < k <= grid[i][j] + j (rightward movement), or Cells (k, j) with i < k <= grid[i][j] + i (downward movement). Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1). If there is no valid path, return -1.   Example 1: Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] Output: 4 Explanation: The image above shows one of the paths that visits exactly 4 cells. Example 2: Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] Output: 3 Explanation: The image above shows one of the paths that visits exactly 3 cells. Example 3: Input: grid = [[2,1,0],[1,0,0]] Output: -1 Explanation: It can be proven that no path exists.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10^5 1 <= m * n <= 10^5 0 <= grid[i][j] < m * n grid[m - 1][n - 1] == 0
from sortedcontainers import SortedList class Solution: def minimumVisitedCells(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) f = [[-1] * n for _ in range(m)] f[0][0] = 1 rows = [SortedList(range(0, n)) for _ in range(m)] cols = [SortedList(range(0, m)) for _ in range(n)] q = [[0, 0]] index = 0 while index < len(q): x, y = q[index] index += 1 sl = rows[x] while True: pos = sl.bisect_left(y + 1) if pos == len(sl): break ny = sl[pos] if ny > y + grid[x][y]: break f[x][ny] = f[x][y] + 1 q.append([x, ny]) del sl[pos] cols[ny].remove(x) sl = cols[y] while True: pos = sl.bisect_left(x + 1) if pos == len(sl): break nx = sl[pos] if nx > x + grid[x][y]: break f[nx][y] = f[x][y] + 1 q.append([nx, y]) del sl[pos] rows[nx].remove(y) return f[-1][-1]
a535b7
46d6e8
Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPart>, and a <RepeatingPart>. The number will be represented in one of the following three ways: <IntegerPart> For example, 12, 0, and 123. <IntegerPart><.><NonRepeatingPart> For example, 0.5, 1., 2.12, and 123.0001. <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> For example, 0.1(6), 1.(9), 123.00(1212). The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).   Example 1: Input: s = "0.(52)", t = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2: Input: s = "0.1666(6)", t = "0.166(66)" Output: true Example 3: Input: s = "0.9(9)", t = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".   Constraints: Each part consists only of digits. The <IntegerPart> does not have leading zeros (except for the zero itself). 1 <= <IntegerPart>.length <= 4 0 <= <NonRepeatingPart>.length <= 4 1 <= <RepeatingPart>.length <= 4
from fractions import Fraction def parse(x): i, n, r = 0, "", "" s = 1 for c in x: if s == 1 and c.isdigit(): i = i * 10 + int(c) elif s == 1 and c == '.': s = 2 elif s == 2 and c.isdigit(): n += c elif s == 2 and c == '(': s = 3 elif s == 3 and c.isdigit(): r += c else: pass if not n and not r: return Fraction(i, 1) if not r: return Fraction(int(str(i) + n), 10 ** len(n)) return Fraction(int(str(i) + n + r) - int(str(i) + n), 10 ** (len(n) + len(r)) - 10 ** len(n)) class Solution: def isRationalEqual(self, s, t): """ :type S: str :type T: str :rtype: bool """ a = parse(s) b = parse(t) return a == b
b38d34
46d6e8
Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPart>, and a <RepeatingPart>. The number will be represented in one of the following three ways: <IntegerPart> For example, 12, 0, and 123. <IntegerPart><.><NonRepeatingPart> For example, 0.5, 1., 2.12, and 123.0001. <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> For example, 0.1(6), 1.(9), 123.00(1212). The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).   Example 1: Input: s = "0.(52)", t = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2: Input: s = "0.1666(6)", t = "0.166(66)" Output: true Example 3: Input: s = "0.9(9)", t = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".   Constraints: Each part consists only of digits. The <IntegerPart> does not have leading zeros (except for the zero itself). 1 <= <IntegerPart>.length <= 4 0 <= <NonRepeatingPart>.length <= 4 1 <= <RepeatingPart>.length <= 4
class Solution(object): def isRationalEqual(self, S, T): """ :type S: str :type T: str :rtype: bool """ if '(' in S: S = S[:S.index('(')] + S[S.index('(')+1:-1]*100 print S if '(' in T: T = T[:T.index('(')] + T[T.index('(')+1:-1]*100 print T return eval(S) == eval(T)
37becb
b08e4d
Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c. Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order.   Example 1: Input: s = "adefaddaccc" Output: ["e","f","ccc"] Explanation: The following are all the possible substrings that meet the conditions: [   "adefaddaccc"   "adefadda",   "ef",   "e", "f",   "ccc", ] If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist. Example 2: Input: s = "abbaccd" Output: ["d","bb","cc"] Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.   Constraints: 1 <= s.length <= 100000 s contains only lowercase English letters.
import heapq class Solution: def maxNumOfSubstrings(self, s: str) -> List[str]: first = {} last = {} for i in range(len(s)): c = s[i] last[c] = i for i in range(len(s)-1,-1,-1): c = s[i] first[c] = i intervals = set() lookup = {} for c in first: st = first[c] ed = last[c] visible = set() for i in range(st,ed+1): visible.add(s[i]) lookup[c] = visible for c in first: seen = set() def dfs(cur,seen): seen.add(cur) for n in lookup[cur]: if n not in seen: dfs(n,seen) dfs(c,seen) lower = min(first[c] for c in seen) upper = max(last[c] for c in seen) intervals.add((lower, upper)) pq = [] intervals = list(intervals) intervals.sort(key = lambda x : x[1] - x[0]) ans = [] taken = set() for a,b in intervals: if any(x in taken for x in range(a,b+1)): continue taken.add(a) taken.add(b) ans.append(s[a:b+1]) return ans
db806b
b08e4d
Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c. Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order.   Example 1: Input: s = "adefaddaccc" Output: ["e","f","ccc"] Explanation: The following are all the possible substrings that meet the conditions: [   "adefaddaccc"   "adefadda",   "ef",   "e", "f",   "ccc", ] If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist. Example 2: Input: s = "abbaccd" Output: ["d","bb","cc"] Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.   Constraints: 1 <= s.length <= 100000 s contains only lowercase English letters.
from itertools import count class Solution(object): def maxNumOfSubstrings(self, s): """ :type s: str :rtype: List[str] """ first = {} last = {} for i, c in enumerate(s): if c not in first: first[c] = i last[c] = i best = [-1] r = [] dep = {} depth = count() def dfs(i): p = i c = s[i] low = dep[c] = next(depth) j = last[c] while i <= j: if s[i] == c: i += 1 continue if s[i] in dep: low = min(low, dep[s[i]]) i += 1 continue i, t = dfs(i) low = min(low, t) j = max(j, i) i += 1 if low >= dep[c] and p > best[0]: r.append(s[p:j+1]) best[0] = j return j, low for i, c in enumerate(s): if c not in dep: dfs(i) return r