text
stringlengths
37
1.41M
''' -Medium- *DFS* *Union Find* You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between cities 1 and n. Note: A path is a sequence of roads between two cities. It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path. The test cases are generated such that there is at least one path between 1 and n. Example 1: Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]] Output: 5 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5. It can be shown that no other path has less score. Example 2: Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]] Output: 2 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2. Constraints: 2 <= n <= 105 1 <= roads.length <= 105 roads[i].length == 3 1 <= ai, bi <= n ai != bi 1 <= distancei <= 104 There are no repeated edges. There is at least one path between 1 and n. ''' from typing import List from collections import defaultdict class Solution: def minScore(self, n: int, roads: List[List[int]]) -> int: G = defaultdict(list) for u,v,w in roads: G[u].append((v,w)) G[v].append((u,w)) visited = [False]*(n+1) dmin = 10**4+1 def dfs(u): nonlocal dmin visited[u] = True for v,w in G[u]: dmin = min(dmin, w) # still explore this edge even if v has already been visited before if not visited[v]: dfs(v) dfs(1) return dmin def minScore2(self, n: int, roads: List[List[int]]) -> int: roots = [i for i in range(n)] dist = [10**4+1]*n def find(x): while x != roots[x]: roots[x] = roots[roots[x]] x = roots[x] return x def union(x, y, w): fx, fy = find(x), find(y) if fx < fy: roots[fy] = fx dist[fx] = min(dist[fx], dist[fy], w) else: roots[fx] = fy dist[fy] = min(dist[fy], dist[fx], w) for u,v,w in roads: union(u-1,v-1,w) # print(roots) # print(dist) return dist[0] if __name__ == "__main__": print(Solution().minScore(n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]])) print(Solution().minScore2(n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]])) print(Solution().minScore(6, [[4,5,7468],[6,2,7173],[6,3,8365],[2,3,7674],[5,6,7852],[1,2,8547],[2,4,1885],[2,5,5192],[1,3,4065],[1,4,7357]])) print(Solution().minScore2(6, [[4,5,7468],[6,2,7173],[6,3,8365],[2,3,7674],[5,6,7852],[1,2,8547],[2,4,1885],[2,5,5192],[1,3,4065],[1,4,7357]])) print(Solution().minScore(7, [[1,3,1484],[3,2,3876],[2,4,6823],[6,7,579],[5,6,4436],[4,5,8830]])) print(Solution().minScore2(7, [[1,3,1484],[3,2,3876],[2,4,6823],[6,7,579],[5,6,4436],[4,5,8830]]))
''' -Medium- Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. Example 1: Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. Example 2: Input: nums = [2,4,6], k = 1 Output: 0 Explanation: There is no odd numbers in the array. Example 3: Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Output: 16 Constraints: 1 <= nums.length <= 50000 1 <= nums[i] <= 10^5 1 <= k <= nums.length ''' from typing import List from collections import Counter class Solution: def numberOfSubarrays(self, nums: List[int], k: int) -> int: n = len(nums) def atMostK(m): ret = 0 left, right = 0, 0 cnt = 0 while right < n: if nums[right] % 2: cnt += 1 right += 1 while left < right and cnt > m: if nums[left] % 2: cnt -= 1 left += 1 ret += left return ret #i, j = atMostK(k), atMostK(k-1) #print(i,j) #return j-i return atMostK(k-1) - atMostK(k) if __name__ == "__main__": print(Solution().numberOfSubarrays(nums = [1,1,2,1,1], k = 3)) print(Solution().numberOfSubarrays(nums = [2,4,6], k = 1)) print(Solution().numberOfSubarrays(nums = [2,2,2,1,2,2,1,2,2,2], k = 2))
''' -Hard- You want to form a target string of lowercase letters. At the beginning, your sequence is target.length '?' marks. You also have a stamp of lowercase letters. On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to 10 * target.length turns. For example, if the initial sequence is "?????", and your stamp is "abc", then you may make "abc??", "?abc?", "??abc" in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.) If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array. For example, if the sequence is "ababc", and the stamp is "abc", then we could return the answer [0, 2], corresponding to the moves "?????" -> "abc??" -> "ababc". Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length moves. Any answers specifying more than this number of moves will not be accepted. Example 1: Input: stamp = "abc", target = "ababc" Output: [0,2] ([1,0,2] would also be accepted as an answer, as well as some other answers.) Example 2: Input: stamp = "abca", target = "aabcaca" Output: [3,0,1] Note: 1 <= stamp.length <= target.length <= 1000 stamp and target only contain lowercase letters. ''' import collections class Solution(object): def movesToStamp(self, stamp, target): """ :type stamp: str :type target: str :rtype: List[int] """ res = [] n, total = len(stamp), 0 while True: isStamped = False for size in range(n, 0, -1): for i in range(n - size + 1): t = '*'*i + stamp[i:i+size]+'*'*(n - size - i) print(size, i, t, target,isStamped) pos = target.find(t) while pos != -1: res.append(pos) isStamped = True total += size target = target[:pos]+'*'*n+target[pos+n:] pos = target.find(t) if not isStamped: break return res[::-1] if total == len(target) else [] def movesToStampDP(self, stamp, target): """ :type stamp: str :type target: str :rtype: List[int] """ """ Try to find a path of target, where path[i] equals to index of target[i] in stamp Example 1: Input: stamp = "abc", target = "ababc" path = [0,1,0,1,2] Example 2: Input: stamp = "abca", target = "aabcaca" path = [0,0,1,2,3,2,3] The rule is that, rule 0. path[i + 1] can equal to path[i] + 1 It means target[i] and target[i+1] are on the same stamp. rule 1. path[i + 1] can equal to 0. It means t[i + 1] is the start of another stamp rule 2. if path[i] == stamp.size - 1, we reach the end of a stamp. Under this stamp, it's another stamp, but not necessary the start. path[i + 1] can equal to 0 ~ stamp.size - 1. Step 2: We need to change path to required moves. This can be a medium problem on the Leetcode. """ s, t = stamp, target if s[0] != t[0] or s[-1] != t[-1]: return [] n, m = len(s), len(t) path = [0] * m pos = collections.defaultdict(set) for i, c in enumerate(s): pos[c].add(i) def dfs(i, index): path[i] = index if i == m - 1: return index == n - 1 nxt_index = set() if index == n - 1: # rule 2 nxt_index |= pos[t[i + 1]] elif s[index + 1] == t[i + 1]: # rule 0 nxt_index.add(index + 1) if s[0] == t[i + 1]: # rule 1 nxt_index.add(0) return any(dfs(i + 1, j) for j in nxt_index) def path2res(path): down, up = [], [] for i in range(len(path)): if path[i] == 0: up.append(i) elif i and path[i] - 1 != path[i - 1]: down.append(i - path[i]) return down[::-1] + up if not dfs(0, 0): return [] return path2res(path) def movesToStampMemoization(self, stamp, target): """ :type stamp: str :type target: str :rtype: List[int] """ ''' 1. stamp[0] has to be equal with target[0] 2. stamp[-1] has to be equal with target[-1] 3. We keep checking pairs of (stamp[s], target[t]). When checking (s, t). If stamp[s] equals to target[t], we can either move forward to (s+1, t+1), or we add a new stamp at index t+1 and stamp[0] has to be equal with target[t+1]. Then we move forward to (0, t+1). (If stamp[0] != target[t+1] here, there is no way to stamp without overwriting previous stamped sequence). 4. When a stamp is used up, s == len(stamp), and we can try any i that stamp[i] == target[t]. In such case, we stamp at index t-i at the begining of the sequence so that stamp[:i] will be overwritten by "later" stamps and we move forward to (i, t). 5. We finish our search when we reach the end of target or t == len(target). Based on rule #2, if i == len(stamp) as well, we have a valid sequence. ''' memo, ls, lt = {}, len(stamp), len(target) def dfs(s, t, seqs): if t == lt: memo[s, t] = seqs if s == ls else [] if (s, t) not in memo: if s == ls: for i in range(ls): cand = dfs(i, t, [t-i]+seqs) if cand: print('a,',s,t,i,cand) memo[s, t] = cand break else: memo[s, t] = [] elif target[t] == stamp[s]: cand = dfs(s+1, t+1, seqs) #print('b,',s,t,cand) memo[s, t] = cand if cand else dfs(0, t+1, seqs+[t+1]) else: memo[s, t] = [] return memo[s, t] return dfs(0, 0, [0]) if __name__ == "__main__": #print(Solution().movesToStampDP(stamp = "abca", target = "aabcaca")) print(Solution().movesToStamp(stamp = "abca", target = "aabcaca")) #print(Solution().movesToStampMemoization(stamp = "abca", target = "aabcaca"))
''' -Medium- *Array* *Two Pointers* Let's call any (contiguous) subarray B (of A) a valley if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] > B[1] > ... B[i-1] > B[i] < B[i+1] < ... < B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array A of integers, return the length of the longest valley. Return 0 if there is no valley. Example 1: Input: [4,3,2,5,3,1,4,8] Output: 5 Explanation: The largest valley is [5,3,1,4,8] which has length 5 Input: [2,2,2] Output: 0 Explanation: There is no valley. Note: 0 <= A.length <= 10000 0 <= A[i] <= 10000 Follow up: Can you solve it using only one pass? Can you solve it in O(1) space? ''' class Solution(object): def longestValley(self, A): """ :type A: List[int] :rtype: int """ if len(A) < 3: return 0 l, trough, r = 0, 0, 1 res, n = 0, len(A) while r < n : if A[r] < A[r-1]: if l < trough < r-1: res = max(res, r-l) if trough < r-1: l = r-1 trough = r elif A[r] == A[r-1]: if l < trough < r-1: res = max(res, r-l) if trough <= r-1: l = r trough = l r += 1 if l < trough < r-1: res = max(res, r-l) return res if __name__ == "__main__": print(Solution().longestValley([4,3,2,5,3,1,4,8])) print(Solution().longestValley([2,2,2,1]))
''' Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i, j < nums.length i != j a <= b b - a == k Example 1: Input: nums = [3,1,4,1,5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input: nums = [1,2,3,4,5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: nums = [1,3,1,5,4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1). Example 4: Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3 Output: 2 Example 5: Input: nums = [-1,-2,-3], k = 1 Output: 2 Constraints: 1 <= nums.length <= 104 -107 <= nums[i] <= 107 0 <= k <= 107 ''' class Solution(object): def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ res = set() m = set() for i in nums: if i-k in m: res.add(tuple(sorted((i-k, i)))) if k+i in m: res.add(tuple(sorted((k+i, i)))) m.add(i) return len(res) if __name__ == "__main__": print(Solution().findPairs([3,1,4,1,5], 2)) print(Solution().findPairs([1,2,3,4,5], 1)) print(Solution().findPairs([1,3,1,5,4], 0)) print(Solution().findPairs([1,2,4,4,3,3,0,9,2,3], 3)) print(Solution().findPairs([-1,-2,-3], 1))
''' -Hard- *DP* *Memoization* *Bitmask* *Bipartite* 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. ''' from functools import lru_cache class Solution(object): def maxStudents(self, seats): R, C = len(seats), len(seats[0]) matching = [[-1] * C for _ in range(R)] def dfs(node, seen): r, c = node # assume a virtual edge connecting students who can spy for nr, nc in [[r-1,c-1], [r,c-1],[r,c+1],[r-1,c+1],[r+1,c-1],[r+1,c+1]]: if 0 <= nr < R and 0 <= nc < C and not seen[nr][nc] and seats[nr][nc] == '.': seen[nr][nc] = True if matching[nr][nc] == -1 or dfs(matching[nr][nc], seen): #if nr == 2 and nc == 1: # print('r,c:', r, c) matching[nr][nc] = (r,c) # matching[r][c] = (nr,nc) return True return False def Hungarian(): res = 0 for c in range(0,C,2): for r in range(R): if seats[r][c] == '.': seen = [[False] * C for _ in range(R)] if dfs((r,c), seen): res += 1 return res res = Hungarian() for r in range(R): print(matching[r]) count = 0 for r in range(R): for c in range(C): if seats[r][c] == '.': count += 1 for row in range(R): for col in range(C): if seats[row][col] == '.' and matching[row][col] == -1: seats[row][col] = 'X' for r in range(R): print(seats[r]) return count - res ''' a brute force solution is to place some students row by row without violating rules, count their # and update our target maximum a better solution is to use DP with memoization (lru_cache in python). ''' def maxStudentsBitMask(self, seats): @lru_cache(None) def backtracking(row: int, prev: int): if row == m: return 0 mask, max_student = bitmasks[row], 0 ''' We can use (x >> i) & 1 to get i-th bit in state x, where >> is the right shift operation. If we are doing this in an if statement (i.e. to check whether the i-th bit is 1), we can also use x & (1 << i), where the << is the left shift operation. We can use (x & y) == x to check if x is a subset of y. The subset means every state in x could be 1 only if the corresponding state in y is 1. We can use (x & (x >> 1)) == 0 to check if there are no adjancent valid states in x. We can use a bitmask of n bits to represent the validity of each row in the classroom. The i-th bit is 1 if and only if the i-th seat is not broken. For the first example in this problem, the bitmasks will be "010010", "100001" and "010010". When we arrange the students to seat in this row, we can also use n bits to represent the students. The i-th bit is 1 if and only if the i-th seat is occupied by a student. We should notice that n bits representing students must be a subset of n bits representing seats. ''' # the loop below iterates every bit pattern for #'s between 0 and (1<<n)-1 for bits in range(1 << n): ''' using the conditionals below, only valid placement of students get picked on the current row; (mask & bits) == bits: each student occupies a valid(unbroken) seat not (bits & (bits >> 1)): no two students seats adjacent (prev & (bits << 1)): the seat to the left and on the row above not occupied (prev & (bits >> 1)): the seat to the right and on the row above not occupied ''' if (mask & bits) == bits and not (bits & (bits >> 1)): if not (prev & (bits >> 1)) and not (prev & (bits << 1)): students = bin(bits).count('1') ''' move to next row by recursion to get maximum students for all rows below ''' rest_students = backtracking(row + 1, bits) # combining # of students on the current row and from all rows # below, we can update max which is what we need max_student = max(max_student, students + rest_students) #print(row, students, format(bits, '05b'), rest_students, max_student) return max_student m, n = len(seats), len(seats[0]) bitmasks = [] for row in seats: bits = ('1' if seat == '.' else '0' for seat in row) bitmasks.append(int(''.join(bits), 2)) #for row in bitmasks: # print(format(row,'0'+str(n)+'b')) return backtracking(0, 0) if __name__ == "__main__": #''' seats = [["#",".",".",".","#"], [".","#",".","#","."], [".",".","#",".","."], [".","#",".","#","."], ["#",".",".",".","#"]] ''' #seats = [["#",".","#","#",".","#"], [".","#","#","#","#","."], ["#",".","#","#",".","#"]] ''' print(Solution().maxStudents(seats)) #print(Solution().maxStudentsBitMask(seats))
''' -Medium- For a stream of integers, implement a data structure that checks if the last k integers parsed in the stream are equal to value. Implement the DataStream class: DataStream(int value, int k) Initializes the object with an empty integer stream and the two integers value and k. boolean consec(int num) Adds num to the stream of integers. Returns true if the last k integers are equal to value, and false otherwise. If there are less than k integers, the condition does not hold true, so returns false. Example 1: Input ["DataStream", "consec", "consec", "consec", "consec"] [[4, 3], [4], [4], [4], [3]] Output [null, false, false, true, false] Explanation DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 dataStream.consec(4); // Only 1 integer is parsed, so returns False. dataStream.consec(4); // Only 2 integers are parsed. // Since 2 is less than k, returns False. dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3]. // Since 3 is not equal to value, it returns False. Constraints: 1 <= value, num <= 109 1 <= k <= 105 At most 105 calls will be made to consec. ''' from collections import deque class DataStream: def __init__(self, value: int, k: int): self.value = value self.k = k self.que = deque() self.cnt = 0 def consec(self, num: int) -> bool: self.que.append(num) if num == self.value: self.cnt += 1 if len(self.que) < self.k: return False if len(self.que) > self.k: v = self.que.popleft() if v == self.value: self.cnt -= 1 return self.cnt == len(self.que) if __name__ == "__main__": dataStream = DataStream(4, 3) # //value = 4, k = 3 print(dataStream.consec(4))# // Only 1 integer is parsed, so returns False. print(dataStream.consec(4))# // Only 2 integers are parsed. #// Since 2 is less than k, returns False. print(dataStream.consec(4))# // The 3 integers parsed are all equal to value, so returns True. print(dataStream.consec(3))# // The last k integers parsed in the stream are [4,4,3]. #// Since 3 is not equal to value, it returns False.
''' -Medium- You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. Example 1: Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] Output: 2 Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4). The maximum distance is 2 with pair (2,4). Example 2: Input: nums1 = [2,2,2], nums2 = [10,10,1] Output: 1 Explanation: The valid pairs are (0,0), (0,1), and (1,1). The maximum distance is 1 with pair (0,1). Example 3: Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] Output: 2 Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4). The maximum distance is 2 with pair (2,4). Example 4: Input: nums1 = [5,4], nums2 = [3,2] Output: 0 Explanation: There are no valid pairs, so return 0. Constraints: 1 <= nums1.length <= 10^5 1 <= nums2.length <= 10^5 1 <= nums1[i], nums2[j] <= 10^5 Both nums1 and nums2 are non-increasing. ''' from typing import List import bisect class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: A, B = nums1, nums2 res = i = j = 0 while i < len(nums1) and j < len(nums2): if A[i] <= B[j]: res = max(res, j-i) j += 1 else: i += 1 #j = i return res def maxDistance2(self, nums1: List[int], nums2: List[int]) -> int: A, B = nums1, nums2 res = 0 def bs2(a, x, start): l, r = start, len(a) while l < r: mid = l + (r-l)//2 if a[mid] < x: r = mid else: l = mid+1 return l for i in range(len(A)): j = bs2(B, A[i], 0) if j == len(B) or A[i] != B[j]: j -= 1 if i <= j: res = max(res, j-i) return res if __name__ == "__main__": print(Solution().maxDistance(nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5])) print(Solution().maxDistance(nums1 = [2,2,2], nums2 = [10,10,1])) print(Solution().maxDistance(nums1 = [30,29,19,5], nums2 = [25,25,25,25,25])) print(Solution().maxDistance(nums1 = [5,4], nums2 = [3,2])) print(Solution().maxDistance2(nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5])) print(Solution().maxDistance2(nums1 = [2,2,2], nums2 = [10,10,1])) print(Solution().maxDistance2(nums1 = [30,29,19,5], nums2 = [25,25,25,25,25])) print(Solution().maxDistance2(nums1 = [5,4], nums2 = [3,2]))
''' -Medium- *GCD* *Sorting* ou are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart. Example 1: Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]] Output: 3 Explanation: The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price. The following 3 lines can be drawn to represent the line chart: - Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4). - Line 2 (in blue) from (4,4) to (5,4). - Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1). It can be shown that it is not possible to represent the line chart using less than 3 lines. Example 2: Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]] Output: 1 Explanation: As shown in the diagram above, the line chart can be represented with a single line. Constraints: 1 <= stockPrices.length <= 105 stockPrices[i].length == 2 1 <= dayi, pricei <= 109 All dayi are distinct. ''' from typing import List from numpy import sign class Solution: def minimumLines(self, stockPrices: List[List[int]]) -> int: P = stockPrices P.sort() # print(P) # print(len(P)) if len(P) == 1: return 0 x0, y0 = P[0] x1, y1 = P[1] def gcd(a, b): while b != 0: r = a % b a, b = b, r return a x = x1 - x0 y = abs(y1 - y0) g = gcd(x, y) if g != 0: slope = (x//g, y//g, sign(y1-y0)) else: slope = (x, 0, 0) ans = 1 for i in range(2, len(P)): x0, y0 = x1, y1 x1, y1 = P[i] x = x1 - x0 y = abs(y1 - y0) g = gcd(x, y) if g != 0: s = (x//g, y//g, sign(y1-y0)) else: s = (x, 0, 0) # print(ans, s, slope, x0, y0, x1, y1, g, x, y) if s != slope: ans += 1 slope = s return ans def minimumLines2(self, stockPrices: List[List[int]]) -> int: P = stockPrices P.sort() if len(P) == 1: return 0 x0, y0 = P[0] x1, y1 = P[1] ans = 1 for i in range(2, len(P)): x2, y2 = P[i] if (y2-y1)*(x1-x0) != (y1-y0) * (x2-x1): ans += 1 x0, y0 = x1, y1 x1, y1 = x2, y2 return ans if __name__ == "__main__": # print(Solution().minimumLines(stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]])) print(Solution().minimumLines2(stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]])) # print(Solution().minimumLines(stockPrices = [[3,4],[1,2],[7,8],[2,3]])) stockPrices = [[93,6],[87,11],[26,58],[28,1],[69,87],[45,59],[29,3],[5,58],[60,94],[46,54],[38,58],[88,10],[94,7],[72,96],[2,93],[63,54],[74,22],[77,84],[33,64],[13,71],[78,59],[76,93],[3,31],[7,95],[68,32],[27,61],[96,31],[4,67],[75,36],[67,21],[8,66],[83,66],[71,58],[6,36],[34,7],[86,78]] print(Solution().minimumLines(stockPrices = stockPrices)) print(Solution().minimumLines2(stockPrices = stockPrices))
''' -Hard- You are given a 0-indexed integer array nums of length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime. For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1. Return the smallest index i at which the array can be split validly or -1 if there is no such split. Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2. Example 1: Input: nums = [4,7,8,15,3,5] Output: 2 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. The only valid split is at index 2. Example 2: Input: nums = [4,7,15,8,3,5] Output: -1 Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i. There is no valid split. Constraints: n == nums.length 1 <= n <= 104 1 <= nums[i] <= 106 ''' from typing import List from collections import Counter import math def primes_set(m): if m == 1: return set() for i in range(2, int(math.sqrt(m))+1): if m % i == 0: return primes_set(m//i) | set([i]) return set([m]) def sieve(n): A = [i for i in range(n+1)] A[1] = 0 for p in range(2, math.floor(math.sqrt(n))+1): if A[p]: j = p*p while j <= n: A[j] = 0 j += p L = [] for p in range(2, n+1): if A[p]: L.append(A[p]) return L class Solution: def findValidSplit(self, nums: List[int]) -> int: n = len(nums) dp = Counter() for i in range(n-1, 0, -1): for p in primes_set(nums[i]): dp[p] += 1 pm = primes_set(nums[0]) cop = True pm2 = set() # print(pm, dp) for p in pm: if p in dp: cop = False pm2.add(p) if cop: return 0 pm = pm2 for i in range(1, n-1): for p in primes_set(nums[i]): dp[p] -= 1 if dp[p] == 0: dp.pop(p) else: pm.add(p) # print(pm, dp) cop = True for p in pm: if p in dp: cop = False break if cop: return i return -1 if __name__ == '__main__': print(Solution().findValidSplit(nums = [4,7,8,15,3,5])) print(Solution().findValidSplit(nums = [1,1,89]))
''' -Medium- Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. Example 1: Input: n = 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 Example 2: Input: n = 0 Output: 1 Constraints: 0 <= n <= 8 ''' class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: ans = 0 for i in range(1, n+1): x, k = 1, 9 for _ in range(i-1): x *= k k -= 1 ans += 9 * x # ways to get special integers with digits less than that in n return ans+1
''' -Medium- You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note that: val1 | val2 is bitwise OR of val1 and val2. val1 & val2 is bitwise AND of val1 and val2. Example 1: Input: nums = [1,4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0,0,0) with effective value ((1 | 1) & 1) = 1 - (0,0,1) with effective value ((1 | 1) & 4) = 0 - (0,1,0) with effective value ((1 | 4) & 1) = 1 - (0,1,1) with effective value ((1 | 4) & 4) = 4 - (1,0,0) with effective value ((4 | 1) & 1) = 1 - (1,0,1) with effective value ((4 | 1) & 4) = 4 - (1,1,0) with effective value ((4 | 4) & 1) = 0 - (1,1,1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5. Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Explanation: The xor-beauty of the given array is 34. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 ''' from typing import List class Solution: def xorBeauty(self, nums: List[int]) -> int: n = len(nums) n3, n2 = n**3, n**2 bit0 = [0]*31 for a in nums: for i in range(31): if (1 << i) & a == 0: bit0[i] += 1 ones = [n3]*31 for i in range(31): for a in nums: if (1 << i) & a == 0: ones[i] -= n2 else: ones[i] -= bit0[i]**2 s = ''.join('1' if i % 2 == 1 else '0' for i in ones) # print(s[::-1]) return int(s[::-1], base = 2) if __name__ == "__main__": print(Solution().xorBeauty(nums = [1,4])) print(Solution().xorBeauty(nums = [15,45,20,2,34,35,5,44,32,30]))
''' -Medium- You are given a 0-indexed integer array nums of length n. You are initially standing at index 0. You can jump from index i to index j where i < j if: nums[i] <= nums[j] and nums[k] < nums[i] for all indexes k in the range i < k < j, or nums[i] > nums[j] and nums[k] >= nums[i] for all indexes k in the range i < k < j. You are also given an integer array costs of length n where costs[i] denotes the cost of jumping to index i. Return the minimum cost to jump to the index n - 1. Example 1: Input: nums = [3,2,4,4,1], costs = [3,7,6,4,2] Output: 8 Explanation: You start at index 0. - Jump to index 2 with a cost of costs[2] = 6. - Jump to index 4 with a cost of costs[4] = 2. The total cost is 8. It can be proven that 8 is the minimum cost needed. Two other possible paths are from index 0 -> 1 -> 4 and index 0 -> 2 -> 3 -> 4. These have a total cost of 9 and 12, respectively. Example 2: Input: nums = [0,1,2], costs = [1,1,1] Output: 2 Explanation: Start at index 0. - Jump to index 1 with a cost of costs[1] = 1. - Jump to index 2 with a cost of costs[2] = 1. The total cost is 2. Note that you cannot jump directly from index 0 to index 2 because nums[0] <= nums[1]. Constraints: n == nums.length == costs.length 1 <= n <= 105 0 <= nums[i], costs[i] <= 105 ''' class Solution(object): def minJumps(self, nums, costs): """ :type arr: List[int] :rtype: int """ A = nums n = len(nums) nxtGreatorEqual = [n]*n nxtSmaller = [n]*n dp = [float('inf')]*n stack = [] for i in range(n): while stack and A[stack[-1]] <= A[i]: nxtGreatorEqual[stack[-1]] = i stack.pop() stack.append(i) stack = [] for i in range(n): while stack and A[stack[-1]] > A[i]: nxtSmaller[stack[-1]] = i stack.pop() stack.append(i) # print(nxtGreatorEqual) # print(nxtSmaller) dp[-1] = 0 for i in range(n-2, -1, -1): if nxtGreatorEqual[i] != n: dp[i] = min(dp[i], costs[nxtGreatorEqual[i]] + dp[nxtGreatorEqual[i]]) if nxtSmaller[i] != n: dp[i] = min(dp[i], costs[nxtSmaller[i]] + dp[nxtSmaller[i]]) return dp[0] if __name__ == "__main__": print(Solution().minJumps(nums = [3,2,4,4,1], costs = [3,7,6,4,2])) print(Solution().minJumps(nums = [0,1,2], costs = [1,1,1])) print(Solution().minJumps(nums = [3,2,6,8,6,4,4,1], costs = [3,13,6,4,5,3,2,2]))
''' -Medium- *Stack* Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. Example 1: MaxStack stack = new MaxStack(); stack.push(5); stack.push(1); stack.push(5); stack.top(); -> 5 stack.popMax(); -> 5 stack.top(); -> 1 stack.peekMax(); -> 5 stack.pop(); -> 1 stack.top(); -> 5 Note: -1e^7 <= x <= 1e^7 Number of operations won't exceed 10000. The last four operations won't be called when stack is empty. ''' class MaxStack: def __init__(self): """ initialize your data structure here. """ self.s1 = [] self.s2 = [] def push(self, x: int) -> None: if not self.s2 or x >= self.s2[-1]: self.s2.append(x) self.s1.append(x) def pop(self) -> int: if self.s1[-1] == self.s2[-1]: self.s2.pop() return self.s1.pop() def top(self) -> int: return self.s1[-1] def peekMax(self) -> int: return self.s2[-1] def popMax(self) -> int: mx = self.s2.pop() j = len(self.s1)-1 while self.s1[j] != mx: j -= 1 self.s1.pop(j) return mx import heapq class MaxStackLogN(object): def __init__(self): self.soft_deleted = set() self.max_heap = [] self.recency_stack = [] self.next_id = 0 def push(self, x: int) -> None: heapq.heappush(self.max_heap, (-x, self.next_id)) self.recency_stack.append((x, self.next_id)) self.next_id -= 1 def _clean_up(self): while self.recency_stack and self.recency_stack[-1][1] in self.soft_deleted: self.soft_deleted.remove(self.recency_stack.pop()[1]) while self.max_heap and self.max_heap[0][1] in self.soft_deleted: self.soft_deleted.remove(heapq.heappop(self.max_heap)[1]) def pop(self) -> int: entry_to_return = self.recency_stack.pop() self.soft_deleted.add(entry_to_return[1]) self._clean_up() return entry_to_return[0] def top(self) -> int: return self.recency_stack[-1][0] def peekMax(self) -> int: return -self.max_heap[0][0] def popMax(self) -> int: value, time = heapq.heappop(self.max_heap) self.soft_deleted.add(time) self._clean_up() return value * -1 # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax() if __name__=="__main__": stack = MaxStack() stack.push(5) stack.push(1) stack.push(5) print(stack.top()) # -> 5 print(stack.popMax()) # -> 5 print(stack.top()) # -> 1 print(stack.peekMax()) # -> 5 print(stack.pop()) # -> 1 print(stack.top()) # -> 5 stack = MaxStackLogN() stack.push(5) stack.push(1) stack.push(5) print(stack.top()) # -> 5 print(stack.popMax()) # -> 5 print(stack.top()) # -> 1 print(stack.peekMax()) # -> 5 print(stack.pop()) # -> 1 print(stack.top()) # -> 5
''' -Hard- *Fenwick Tree* Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following: The number of elements currently in nums that are strictly less than instructions[i]. The number of elements currently in nums that are strictly greater than instructions[i]. For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 10^9 + 7 Example 1: Input: instructions = [1,5,6,2] Output: 1 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. The total cost is 0 + 0 + 0 + 1 = 1. Example 2: Input: instructions = [1,2,3,6,5,4] Output: 3 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. Example 3: Input: instructions = [1,3,3,3,2,4,2,1,2] Output: 4 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. ​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. ​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. Constraints: 1 <= instructions.length <= 10^5 1 <= instructions[i] <= 10^5 ''' class Solution(object): def createSortedArray(self, instructions): """ :type instructions: List[int] :rtype: int """ n = max(instructions) sum_array = [0] * (n + 1) def lowbit(x): return x & -x def add(x): while x <= n: sum_array[x] += 1 x += lowbit(x) def query(x): res = 0 while x > 0: res += sum_array[x] x -= lowbit(x) return res ans = 0 MOD = 10**9+7 for i in instructions: cost = min(query(i-1), query(n)-query(i)) ans = ((ans+cost)%MOD+MOD)%MOD add(i) return ans if __name__ == "__main__": print(Solution().createSortedArray([1,5,6,2])) print(Solution().createSortedArray([1,2,3,6,5,4])) print(Solution().createSortedArray([1,3,3,3,2,4,2,1,2]))
''' -Hard- $$$ *Sliding Window* You are given an integer array nums and a positive integer k. The frequency score of an array is the sum of the distinct values in the array raised to the power of their frequencies, taking the sum modulo 109 + 7. For example, the frequency score of the array [5,4,5,7,4,4] is (43 + 52 + 71) modulo (109 + 7) = 96. Return the maximum frequency score of a subarray of size k in nums. You should maximize the value under the modulo and not the actual value. A subarray is a contiguous part of an array. Example 1: Input: nums = [1,1,1,2,1,2], k = 3 Output: 5 Explanation: The subarray [2,1,2] has a frequency score equal to 5. It can be shown that it is the maximum frequency score we can have. Example 2: Input: nums = [1,1,1,1,1,1], k = 4 Output: 1 Explanation: All the subarrays of length 4 have a frequency score equal to 1. Constraints: 1 <= k <= nums.length <= 105 1 <= nums[i] <= 106 ''' from typing import List from collections import defaultdict, Counter class Solution: def maxFrequencyScore(self, nums: List[int], k: int) -> int: n, MOD = len(nums), 10**9 + 7 cur, below = defaultdict(int), defaultdict(int) ans, sums = 0, 0 ones = 0 for i,v in enumerate(nums): if v > 1: if v not in cur: cur[v] = v else: below[v] = cur[v] cur[v] *= v if v == 1: if ones == 0: sums += 1 ones += 1 else: sums += cur[v] - below[v] if i >= k: j = i-k if nums[j] == 1: ones -= 1 if ones == 0: sums -= 1 else: sums -= cur[nums[j]] - below[nums[j]] cur[nums[j]] = below[nums[j]] below[nums[j]] //= nums[j] if below[nums[j]] == 1: below[nums[j]] = 0 if cur[nums[j]] == 0: del cur[nums[j]] if i >= k-1: ans = max(ans, sums%MOD) return ans def maxFrequencyScore2(self, nums: List[int], k: int) -> int: mod = 10**9 + 7 cnt = Counter(nums[:k]) ans = cur = sum(pow(k, v, mod) for k, v in cnt.items()) % mod i = k while i < len(nums): a, b = nums[i - k], nums[i] if a != b: cur += (b - 1) * pow(b, cnt[b], mod) if cnt[b] else b cur -= (a - 1) * pow(a, cnt[a] - 1, mod) if cnt[a] > 1 else a cur %= mod cnt[b] += 1 cnt[a] -= 1 ans = max(ans, cur) i += 1 return ans from random import randint if __name__ == "__main__": print(Solution().maxFrequencyScore(nums = [1,1,1,2,1,2], k = 3)) print(Solution().maxFrequencyScore(nums = [1,1,1,1,1,1], k = 4)) n = 50000 k = randint(1, n) nums = [randint(1, 10000) for i in range(n)] print(Solution().maxFrequencyScore2(nums = nums, k = k)) print(Solution().maxFrequencyScore(nums = nums, k = k))
''' -Hard- *Kadane's Algorithm* You are given two 0-indexed integer arrays nums1 and nums2, both of length n. You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right]. For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15]. You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr. Return the maximum possible score. 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: nums1 = [60,60,60], nums2 = [10,90,10] Output: 210 Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10]. The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210. Example 2: Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20] Output: 220 Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30]. The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220. Example 3: Input: nums1 = [7,11,13], nums2 = [1,1,1] Output: 31 Explanation: We choose not to swap any subarray. The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31. Constraints: n == nums1.length == nums2.length 1 <= n <= 105 1 <= nums1[i], nums2[i] <= 104 ''' from typing import List class Solution: def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int: def kadane(nums1, nums2): # calculate how much nums2 can earn by swaping a part of the array. res = cur = 0 for i in range(len(nums1)): # Once the element in nums1 make the cur negative, reset cur to zero; else, update cur. cur = max(0, cur + nums1[i] - nums2[i]) res = max(res, cur) # return the sum after swapping a part of the array. return res + sum(nums2) # We are not sure which array is bigger so that we have to do kadane() twice. return max(kadane(nums1, nums2), kadane(nums2, nums1)) if __name__ == "__main__": print(Solution().maximumsSplicedArray(nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]))
''' -Hard- There is a long and thin painting that can be represented by a number line. You are given a 0-indexed 2D integer array paint of length n, where paint[i] = [starti, endi]. This means that on the ith day you need to paint the area between starti and endi. Painting the same area multiple times will create an uneven painting so you only want to paint each area of the painting at most once. Return an integer array worklog of length n, where worklog[i] is the amount of new area that you painted on the ith day. Example 1: Input: paint = [[1,4],[4,7],[5,8]] Output: [3,3,1] Explanation: On day 0, paint everything between 1 and 4. The amount of new area painted on day 0 is 4 - 1 = 3. On day 1, paint everything between 4 and 7. The amount of new area painted on day 1 is 7 - 4 = 3. On day 2, paint everything between 7 and 8. Everything between 5 and 7 was already painted on day 1. The amount of new area painted on day 2 is 8 - 7 = 1. Example 2: Input: paint = [[1,4],[5,8],[4,7]] Output: [3,3,1] Explanation: On day 0, paint everything between 1 and 4. The amount of new area painted on day 0 is 4 - 1 = 3. On day 1, paint everything between 5 and 8. The amount of new area painted on day 1 is 8 - 5 = 3. On day 2, paint everything between 4 and 5. Everything between 5 and 7 was already painted on day 1. The amount of new area painted on day 2 is 5 - 4 = 1. Example 3: Input: paint = [[1,5],[2,4]] Output: [4,0] Explanation: On day 0, paint everything between 1 and 5. The amount of new area painted on day 0 is 5 - 1 = 4. On day 1, paint nothing because everything between 2 and 4 was already painted on day 0. The amount of new area painted on day 1 is 0. Constraints: 1 <= paint.length <= 105 paint[i].length == 2 0 <= starti < endi <= 5 * 104 ''' from typing import List import collections import heapq from sortedcontainers import SortedList class Node: def __init__(self, l, r): self.left = None self.right = None self.l = l self.r = r self.mid = (l + r) >> 1 self.v = 0 self.add = 0 class SegmentTree2: # bottom-up segment tree def __init__(self, N, query_fn, update_fn): self.base = N self.query_fn = query_fn self.update_fn = update_fn self.tree = [0]*(2*N) self.lazy = [0]*(2*N) self.count = [1]*(2*N) H = 1 while 1 << H < N: H += 1 self.H = H for i in range(N-1, 0, -1): self.count[i] = self.count[i<<1] + self.count[(i<<1)+1] def update(self, L, R, val): L += self.base R += self.base self.push(L)# // key point self.push(R)# // key point L0, R0 = L, R while L <= R: if (L & 1) == 1: self.apply(L, val) L += 1 if (R & 1) == 0: self.apply(R, val) R -= 1 L >>= 1 R >>= 1 self.pull(L0) self.pull(R0) def query(self, L, R): result = 0 if L > R: return result L += self.base R += self.base self.push(L) self.push(R) while L <= R: if (L & 1) == 1: result = self.query_fn(result, self.tree[L]) L += 1 if (R & 1) == 0: result = self.query_fn(result, self.tree[R]) R -= 1 L >>= 1; R >>= 1 return result def apply(self, x, val): self.tree[x] = self.update_fn(self.tree[x], val * self.count[x]) if x < self.base: self.lazy[x] = self.update_fn(self.lazy[x], val) def pull(self, x): while x > 1: x >>= 1 # print(x << 1, x<<1+1) self.tree[x] = self.query_fn(self.tree[x<<1], self.tree[(x<<1) + 1]) if self.lazy[x]: self.tree[x] = self.update_fn(self.tree[x], self.lazy[x] * self.count[x]) def push(self, x): for h in range(self.H, 0, -1): y = x >> h if self.lazy[y]: self.apply(y << 1, self.lazy[y]) self.apply((y << 1) + 1, self.lazy[y]) self.lazy[y] = 0 class SegmentTree: def __init__(self): self.root = Node(1, 10**5 + 10) def modify(self, l, r, v, node=None): if l > r: return if node is None: node = self.root if node.l >= l and node.r <= r: node.v = node.r - node.l + 1 node.add = v return self.pushdown(node) if l <= node.mid: self.modify(l, r, v, node.left) if r > node.mid: self.modify(l, r, v, node.right) self.pushup(node) def query(self, l, r, node=None): if l > r: return 0 if node is None: node = self.root if node.l >= l and node.r <= r: return node.v self.pushdown(node) v = 0 if l <= node.mid: v += self.query(l, r, node.left) if r > node.mid: v += self.query(l, r, node.right) return v def pushup(self, node): node.v = node.left.v + node.right.v def pushdown(self, node): if node.left is None: node.left = Node(node.l, node.mid) if node.right is None: node.right = Node(node.mid + 1, node.r) if node.add: left, right = node.left, node.right left.v = left.r - left.l + 1 right.v = right.r - right.l + 1 left.add = node.add right.add = node.add node.add = 0 class Solution: def amountPainted(self, paint: List[List[int]]) -> List[int]: # Wrong m = len(paint) n = 5*10**4+1 n = 23 B1 = [0]*n B2 = [0]*n def query(BIT, x): sums = 0 while x > 0: sums += BIT[x] x -= x & (-x) return sums def update(BIT, x, i): while x < n: BIT[x] += i x += x & (-x) def range_update(l, r, x): update(B1, l, x) update(B1, r+1, -x) update(B2, l, x*(l-1)) update(B2, r+1, -x*r) def prefix_sum(idx): return query(B1, idx)*idx - query(B2, idx) def range_query(l, r): return prefix_sum(r-1) - prefix_sum(l-1) ans = [0]*m for i,(s,e) in enumerate(paint): a = range_query(s,e) ans[i] = (e-s) - range_query(s, e) range_update(s,e-1,1) # print(s, e, a, B1, B2) return ans def amountPainted2(self, paint: List[List[int]]) -> List[int]: tree = SegmentTree() ans = [] for i, (start, end) in enumerate(paint): l, r = start + 1, end v = tree.query(l, r) ans.append(r - l + 1 - v) tree.modify(l, r, 1) return ans def amountPainted3(self, paint): """ :type paint: List[List[int]] :rtype: List[int] """ points = collections.defaultdict(list) for i, (s, e) in enumerate(paint): points[s].append((True, i)) points[e].append((False, i)) min_heap = [] lookup = [False]*len(paint) result = [0]*len(paint) prev = -1 for pos in sorted(points.keys()): while min_heap and lookup[min_heap[0]]: heapq.heappop(min_heap) if min_heap: result[min_heap[0]] += pos-prev prev = pos for t, i in points[pos]: if t: heapq.heappush(min_heap, i) else: lookup[i] = True return result def amountPainted4(self, paint: List[List[int]]) -> List[int]: minDay = min(s for s, e in paint) maxDay = max(e for s, e in paint) ans = [0] * len(paint) # store indices of paint that are available now runningIndices = SortedList() events = [] # (day, index, type) for i, (start, end) in enumerate(paint): events.append((start, i, 1)) # 1 := entering events.append((end, i, -1)) # -1 := leaving events.sort() i = 0 # events' index for day in range(minDay, maxDay): while i < len(events) and events[i][0] == day: day, index, type = events[i] if type == 1: runningIndices.add(index) else: runningIndices.remove(index) i += 1 if runningIndices: ans[runningIndices[0]] += 1 return ans def amountPainted5(self, paint: List[List[int]]) -> List[int]: maxDay = max(e for s, e in paint) query = lambda x,y: x+y update = lambda x,y: y st = SegmentTree2(maxDay, query_fn=query, update_fn=update) res = [] for x,y in paint: cnt = st.query(x, y-1) st.update(x, y-1, 1) res.append(st.query(x, y-1)-cnt) return res def amountPainted6(self, paint: List[List[int]]) -> List[int]: # scan line method runningIndices = SortedList() events = [] # (day, index, type) ans = [0] * len(paint) for i, (start, end) in enumerate(paint): events.append((start, i, 1)) # 1 := entering events.append((end, i, -1)) # -1 := leaving events.sort() for i in range(len(events)): day, index, type = events[i] if type == 1: runningIndices.add(index) else: runningIndices.remove(index) if runningIndices: ans[runningIndices[0]] += events[i+1][0] - day return ans import random if __name__ == "__main__": # paint = [[1,4],[4,7],[5,8]] paint = [[14,18],[12,16],[4,7],[3,22]] print(Solution().amountPainted(paint)) print(Solution().amountPainted2(paint)) print(Solution().amountPainted3(paint)) print(Solution().amountPainted4(paint)) print(Solution().amountPainted5(paint)) print(Solution().amountPainted6(paint)) paint = [[1,4],[5,8],[4,7]] print(Solution().amountPainted(paint)) print(Solution().amountPainted2(paint)) print(Solution().amountPainted5(paint)) print(Solution().amountPainted6(paint)) paint = [[1,5],[2,4]] # print(Solution().amountPainted(paint)) print(Solution().amountPainted2(paint)) print(Solution().amountPainted5(paint)) print(Solution().amountPainted6(paint)) paint = [[1,10],[20,34], [8, 12], [16,19]] # print(Solution().amountPainted(paint)) print(Solution().amountPainted2(paint)) print(Solution().amountPainted6(paint)) # N, segs = 1000, set() # while len(segs) < N: # i, j = random.randint(1,1000), random.randint(1,1000) # if i < j: # segs.add((i,j)) # paint = list(segs) # print(paint) paint = [(73, 493), (454, 900), (204, 270), (54, 941)] # print(Solution().amountPainted(paint)) print(Solution().amountPainted2(paint)) print(Solution().amountPainted6(paint))
''' -Medium- *BFS* *DFS* *Memoization* Given a string s and a set of n substrings. You are supposed to remove every instance of those n substrings from s so that s is of the minimum length and output this minimum length. 样例 Example 1: Input: "ccdaabcdbb" ["ab","cd"] Output: 2 Explanation: ccdaabcdbb -> ccdacdbb -> cacdbb -> cabb -> cb (length = 2) Example 2: Input: "abcabd" ["ab","abcd"] Output: 0 Explanation: abcabd -> abcd -> "" (length = 0) ''' import re from collections import deque def findall(p, s): '''Yields all the positions of the pattern p in the string s.''' i = s.find(p) while i != -1: yield i i = s.find(p, i+1) class Solution: """ @param s: a string @param dict: a set of n substrings @return: the minimum length """ def minLengthDFS(self, s, dict): # write your code here memo = {} def dfs(str): if not str: return 0 if str in memo: return memo[str] n = len(str) for pat in dict: for i in findall(pat, str): news = str[:i]+str[i+len(pat):] n = min(n, dfs(news)) memo[str] = n return memo[str] return dfs(s) def minLength(self, s, dict): # write your code here q = deque([s]) res = len(s) memo = set([s]) while q: cur = q.popleft() res = min(res, len(cur)) for pat in dict: for i in findall(pat, cur): news = cur[:i]+cur[i+len(pat):] if news not in memo and len(news) < res: memo.add(news) q.append(news) return res if __name__ == "__main__": print(Solution().minLengthDFS("ccdaabcdbb", ["ab","cd"])) print(Solution().minLengthDFS("abcabd", ["ab","abcd"])) print(Solution().minLength("ccdaabcdbb", ["ab","cd"])) print(Solution().minLength("abcabd", ["ab","abcd"])) s = "wyewyruyiuysfhkjahjreiwoauifhjsajfhauwueihfjaskfjhaeuiwaeadjsakhkjhwaeiuwadhsajkhfkjafjiwueuwe" dic = ["fh","jh","yu","ab","bc","cd","sa","fjaskfjha","aeu","fjak","fjhaeuiwae","aeuiw","eu","iuif","yau","sfo","hkw","askadjs","jahjrei"] print(Solution().minLengthDFS(s, dic)) print(Solution().minLength(s, dic))
''' -Medium- You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. There are two types of logs: Letter-logs: All words (except the identifier) consist of lowercase English letters. Digit-logs: All words (except the identifier) consist of digits. Reorder these logs so that: The letter-logs come before all digit-logs. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. The digit-logs maintain their relative ordering. Return the final order of the logs. Example 1: Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] Explanation: The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig". The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6". Example 2: Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"] Constraints: 1 <= logs.length <= 100 3 <= logs[i].length <= 100 All the tokens of logs[i] are separated by a single space. logs[i] is guaranteed to have an identifier and at least one word after the identifier. ''' from typing import List class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: L, D = [], [] for i in range(len(logs)): s = logs[i].split() con = ''.join(s[1:]) if con.isalpha(): L.append((' '.join(s[1:]), s[0], i)) else: D.append(logs[i]) L.sort() ans = [] for _,_,i in L: ans.append(logs[i]) return ans + D
''' -Medium- *GCD* *Hash Table* You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles. Example 1: Input: rectangles = [[4,8],[3,6],[10,20],[15,30]] Output: 6 Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed): - Rectangle 0 with rectangle 1: 4/8 == 3/6. - Rectangle 0 with rectangle 2: 4/8 == 10/20. - Rectangle 0 with rectangle 3: 4/8 == 15/30. - Rectangle 1 with rectangle 2: 3/6 == 10/20. - Rectangle 1 with rectangle 3: 3/6 == 15/30. - Rectangle 2 with rectangle 3: 10/20 == 15/30. Example 2: Input: rectangles = [[4,5],[7,8]] Output: 0 Explanation: There are no interchangeable pairs of rectangles. Constraints: n == rectangles.length 1 <= n <= 105 rectangles[i].length == 2 1 <= widthi, heighti <= 105 ''' from typing import List from collections import Counter class Solution: def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: def gcd(a, b): while b != 0: r = a % b a, b = b, r return a counter = Counter() for w, h in rectangles: g = gcd(w, h) counter[(w//g, h//g)] += 1 ans = 0 for k in counter: ans += counter[k]*(counter[k]-1)//2 return ans
''' -Medium- $$$ *Monotonic Stack* *Recursion* You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree. A binary search tree is defined as follows: <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> The binary search tree is constructed as follows: <li><code>order[0]</code> will be the <strong>root</strong> of the binary search tree.</li> <li>All subsequent elements are inserted as the <strong>child</strong> of <strong>any</strong> existing node such that the binary search tree properties hold.</li> Return the depth of the binary search tree. A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: order = [2,1,4,3] Output: 3 Explanation: The binary search tree has a depth of 3 with path 2->3->4. Example 2: Input: order = [2,1,3,4] Output: 3 Explanation: The binary search tree has a depth of 3 with path 2->3->4. Input: order = [1,2,3,4] Output: 4 Explanation: The binary search tree has a depth of 4 with path 1->2->3->4. Constraints: <li><code>n == order.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>order</code> is a permutation of integers between <code>1</code> and <code>n</code>.</li> ''' from typing import List from sortedcontainers import SortedDict import math class Solution: def maxDepthBST(self, order: List[int]) -> int: if not order: return 0 if len(order) == 1: return 1 i = 1 while i < len(order) and order[i] < order[0]: i += 1 return 1+max(self.maxDepthBST(order[1:i]), self.maxDepthBST(order[i:])) def maxDepthBST2(self, order: List[int]) -> int: n, stack = len(order), [] firstGreaterRight = [n]*n for i in range(n): while stack and order[stack[-1]] < order[i]: firstGreaterRight[stack[-1]] = i stack.pop() stack.append(i) # print(firstGreaterRight) def helper(i, j): if i > j: return 0 if i == j: return 1 return 1+max(helper(i+1, firstGreaterRight[i]-1), helper(firstGreaterRight[i], j)) return helper(0, n-1) def maxDepthBST3(self, order: List[int]) -> int: sd = SortedDict({0: 0, math.inf: 0, order[0]: 1}) ans = 1 for v in order[1:]: lower = sd.bisect_left(v) - 1 higher = lower + 1 depth = 1 + max(sd.values()[lower], sd.values()[higher]) ans = max(ans, depth) sd[v] = depth return ans from random import randint import time if __name__ == '__main__': print(Solution().maxDepthBST(order = [2,1,4,3])) print(Solution().maxDepthBST2(order = [2,1,4,3])) print(Solution().maxDepthBST(order = [2,1,3,4])) print(Solution().maxDepthBST2(order = [2,1,3,4])) print(Solution().maxDepthBST(order = [1,2,3,4])) print(Solution().maxDepthBST2(order = [1,2,3,4])) N = 80000 order = [] def generate(i, j): if i > j : return k = randint(i, j) order.append(k) generate(i, k-1) generate(k+1, j) generate(1, N) print('len', len(order)) assert len(order) == N starttime = time.time() print(Solution().maxDepthBST(order = order)) print("elapsed {}s".format(time.time()-starttime)) starttime = time.time() print(Solution().maxDepthBST2(order = order)) print("elapsed {}s".format(time.time()-starttime)) starttime = time.time() print(Solution().maxDepthBST3(order = order)) print("elapsed {}s".format(time.time()-starttime))
''' -Medium- $$$ *Sorting* You are given an integer n which is the length of a 0-indexed array nums, and a 0-indexed 2D-array ranges, which is a list of sub-ranges of nums (sub-ranges may overlap). Each row ranges[i] has exactly 2 cells: ranges[i][0], which shows the start of the ith range (inclusive) ranges[i][1], which shows the end of the ith range (inclusive) These ranges cover some cells of nums and leave some cells uncovered. Your task is to find all of the uncovered ranges with maximal length. Return a 2D-array answer of the uncovered ranges, sorted by the starting point in ascending order. By all of the uncovered ranges with maximal length, we mean satisfying two conditions: Each uncovered cell should belong to exactly one sub-range There should not exist two ranges (l1, r1) and (l2, r2) such that r1 + 1 = l2 Example 1: Input: n = 10, ranges = [[3,5],[7,8]] Output: [[0,2],[6,6],[9,9]] Explanation: The ranges (3, 5) and (7, 8) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [0,0,0,1,1,1,0,1,1,0] in which we can observe that the ranges (0, 2), (6, 6) and (9, 9) aren't covered. Example 2: Input: n = 3, ranges = [[0,2]] Output: [] Explanation: In this example, the whole of the array nums is covered and there are no uncovered cells so the output is an empty array. Example 3: Input: n = 7, ranges = [[2,4],[0,3]] Output: [[5,6]] Explanation: The ranges (0, 3) and (2, 4) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [1,1,1,1,1,0,0] in which we can observe that the range (5, 6) is uncovered. Constraints: 1 <= n <= 109 0 <= ranges.length <= 106 ranges[i].length = 2 0 <= ranges[i][j] <= n - 1 ranges[i][0] <= ranges[i][1] ''' from typing import List class Solution: def findMaximalUncoveredRanges(self, n: int, ranges: List[List[int]]) -> List[List[int]]: R = ranges R.sort() cur = 0 s, e = R[0] # for i in range(1, len(R)): i = 0 ans = [] while i < len(R): while i < len(R) and R[i][0] <= e: e = max(e, R[i][1]) i += 1 if cur < s: ans.append([cur, s-1]) cur = e+1 if i == len(R): break s, e = R[i] if cur < s: ans.append([cur, s-1]) i += 1 # print(ans) cur = e+1 if cur < n: ans.append([cur,n-1]) return ans def findMaximalUncoveredRanges2(self, n: int, ranges: List[List[int]]) -> List[List[int]]: ranges.sort() last = -1 ans = [] for l, r in ranges: if last + 1 < l: ans.append([last + 1, l - 1]) last = max(last, r) if last + 1 < n: ans.append([last + 1, n - 1]) return ans if __name__ == '__main__': print(Solution().findMaximalUncoveredRanges(n = 10, ranges = [[3,5],[7,8]])) print(Solution().findMaximalUncoveredRanges(n = 3, ranges = [[0,2]])) print(Solution().findMaximalUncoveredRanges(n = 7, ranges = [[2,4],[0,3]]))
''' -Easy- The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string. To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence. Example 1: Input: n = 1 Output: "1" Explanation: This is the base case. Example 2: Input: n = 4 Output: "1211" Explanation: countAndSay(1) = "1" countAndSay(2) = say "1" = one 1 = "11" countAndSay(3) = say "11" = two 1's = "21" countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" Constraints: 1 <= n <= 30 ''' from itertools import groupby class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ s = '1' for _ in range(2, n+1): s = ''.join(str(len(list(g)))+l for l, g in groupby(s)) return s if __name__ == "__main__": print(Solution().countAndSay(19))
''' -Medium- Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 ''' class Solution(object): def minMoves2(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() res, i,j = 0, 0, len(nums)-1 while i < j: res += nums[j] - nums[i] j -= 1 i += 1 return res if __name__ == "__main__": print(Solution().minMoves2([1,10,2,9]))
''' -Medium- *Auxiliary Array* You are given a 0-indexed integer array nums of size n and a positive integer k. We call an index i in the range k <= i < n - k good if the following conditions are satisfied: The k elements that are just before the index i are in non-increasing order. The k elements that are just after the index i are in non-decreasing order. Return an array of all good indices sorted in increasing order. Example 1: Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing. Example 2: Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array. Constraints: n == nums.length 3 <= n <= 105 1 <= nums[i] <= 106 1 <= k <= n / 2 ''' from typing import List class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: A, n = nums, len(nums) dec, inc = [-1]*n, [-1]*n dec[0] = 0 inc[-1] = n-1 for i in range(1,n): if A[i] <= A[i-1]: dec[i] = dec[i-1] else: dec[i] = i for i in range(n-2, -1, -1): if A[i] <= A[i+1]: inc[i] = inc[i+1] else: inc[i] = i ans = [] for i in range(k, n-k): if i-1 - dec[i-1] + 1 >= k and inc[i+1] - (i+1) + 1>= k: ans.append(i) # print(dec) # print(inc) return ans if __name__ == "__main__": print(Solution().goodIndices(nums = [2,1,1,1,3,4,1], k = 2)) print(Solution().goodIndices(nums = [2,1,1,2], k = 2))
''' -Easy- Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: columnNumber = 1 Output: "A" Example 2: Input: columnNumber = 28 Output: "AB" Example 3: Input: columnNumber = 701 Output: "ZY" Example 4: Input: columnNumber = 2147483647 Output: "FXSHRXW" Constraints: 1 <= columnNumber <= 2^31 - 1 ''' import string class Solution(object): def convertToTitle(self, columnNumber): """ :type columnNumber: int :rtype: str """ n = columnNumber m = {x:y for x,y in zip(range(1,27), string.ascii_uppercase)} res = '' while n != 0: rem = n % 26 res += m[rem] if rem != 0 else 'Z' n = (n-1) // 26 return res[::-1] if __name__ == "__main__": print(Solution().convertToTitle(701)) print(Solution().convertToTitle(2147483647))
''' -Medium- Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class: MagicDictionary() Initializes the object. void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary. bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false. Example 1: Input ["MagicDictionary", "buildDict", "search", "search", "search", "search"] [[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]] Output [null, null, false, true, false, false] Explanation MagicDictionary magicDictionary = new MagicDictionary(); magicDictionary.buildDict(["hello", "leetcode"]); magicDictionary.search("hello"); // return False magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True magicDictionary.search("hell"); // return False magicDictionary.search("leetcoded"); // return False Constraints: 1 <= dictionary.length <= 100 1 <= dictionary[i].length <= 100 dictionary[i] consists of only lower-case English letters. All the strings in dictionary are distinct. 1 <= searchWord.length <= 100 searchWord consists of only lower-case English letters. buildDict will be called only once before search. At most 100 calls will be made to search. ''' from collections import defaultdict class Node(defaultdict): def __init__(self): super().__init__(Node) self.terminal = False class MagicDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = Node() def buildDict(self, dictionary): """ :type dictionary: List[str] :rtype: None """ for word in dictionary: cur = self.root for c in word: cur = cur[c] cur.terminal = True def search(self, searchWord): """ :type searchWord: str :rtype: bool """ def helper(cur, remain, word): if not word: return True if remain == 0 and cur.terminal else False for c in cur: if c == word[0]: if helper(cur[c], remain, word[1:]): return True elif remain == 1: if helper(cur[c], 0, word[1:]): return True return False return helper(self.root, 1, searchWord) if __name__ == "__main__": ''' magicDictionary = MagicDictionary() magicDictionary.buildDict(["hello", "leetcode"]) print(magicDictionary.search("hello")) # return False print(magicDictionary.search("hhllo")) # We can change the second 'h' to 'e' to match "hello" so we return True print(magicDictionary.search("hell")) # return False print(magicDictionary.search("leetcoded")) # return False ''' magicDictionary = MagicDictionary() magicDictionary.buildDict(["hello", "hallo", "leetcode"]) print(magicDictionary.search("hello")) # return False print(magicDictionary.search("hhllo")) # We can change the second 'h' to 'e' to match "hello" so we return True print(magicDictionary.search("hell")) # return False print(magicDictionary.search("leetcoded")) # return False
''' You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3. Constraints: The length of the given array is positive and will not exceed 20. The sum of elements in the given array will not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer. ''' from functools import lru_cache class Solution(object): def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ n = len(nums) #dp = [{} for i in range(n)] @lru_cache(None) def dfs(i, s): if i == n: return 1 if s == 0 else 0 #if s in dp[i]: return dp[i][s] l1 = dfs(i+1, s+nums[i]) l2 = dfs(i+1, s-nums[i]) #dp[i][s] = l1 + l2 #return dp[i][s] return l1+l2 return dfs(0, S) if __name__ == "__main__": print(Solution().findTargetSumWays([1, 1, 1, 1, 1], 3))
''' -Medium- There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it becomes vacant. Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n. Return the state of the prison after n days (i.e., n such changes described above). Example 1: Input: cells = [0,1,0,1,1,0,0,1], n = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0] Example 2: Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000 Output: [0,0,1,1,1,1,1,0] Constraints: cells.length == 8 cells[i] is either 0 or 1. 1 <= n <= 10^9 ''' class Solution(object): def prisonAfterNDays(self, cells, N): seen = {str(cells): N} while N: seen.setdefault(str(cells), N) N -= 1 cells = [0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, 7)] + [0] if str(cells) in seen: N %= seen[str(cells)] - N return cells def prisonAfterNDays2(self, cells, k, N): seen = set() hasCycle = False cycles = 0 for i in range(N): newcells = [0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, k)] + [0] if str(newcells) not in seen: seen.add(str(newcells)) cycles += 1 else: hasCycle = True break cells = newcells print('cycles: ', cycles) if hasCycle: N %= cycles for i in range(N): newcells = [0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, k)] + [0] cells = newcells return cells if __name__ == "__main__": print(Solution().prisonAfterNDays([0,1,0,1,1,0,0,1], 7)) print(Solution().prisonAfterNDays2([0,1,0,1,1,0,0,1], 7, 7)) print(Solution().prisonAfterNDays2([0,1,0,1,1,0,0,1], 7, 26)) print(Solution().prisonAfterNDays2([0,1,0,1,1,0,0,1,1], 8, 10**8))
''' -Medium- Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s. Return the minimum cost of deletions such that there are no two identical letters next to each other. Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change. Example 1: Input: s = "abaac", cost = [1,2,3,4,5] Output: 3 Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other). Example 2: Input: s = "abc", cost = [1,2,3] Output: 0 Explanation: You don't need to delete any character because there are no identical letters next to each other. Example 3: Input: s = "aabaa", cost = [1,2,3,4,1] Output: 2 Explanation: Delete the first and the last character, getting the string ("aba"). Constraints: s.length == cost.length 1 <= s.length, cost.length <= 10^5 1 <= cost[i] <= 10^4 s contains only lowercase English letters. ''' from typing import List class Solution: def minCost(self, s: str, cost: List[int]) -> int: n = len(s) sm, mx, c = 0, 0, '_' ans = 0 for i in range(n): if s[i] == c: sm += cost[i] mx = max(mx, cost[i]) else: ans += sm - mx c = s[i] sm, mx = cost[i], cost[i] ans += sm - mx return ans if __name__ == "__main__": print(Solution().minCost(s = "abaac", cost = [1,2,3,4,5])) print(Solution().minCost(s = "abc", cost = [1,2,3])) print(Solution().minCost(s = "aabaa", cost = [1,2,3,4,1]))
''' -Medium- Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted. Example 1: Input: n = 10, k = 1, maxPts = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: n = 6, k = 1, maxPts = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. Example 3: Input: n = 21, k = 17, maxPts = 10 Output: 0.73278 Constraints: 0 <= k <= n <= 10^4 1 <= maxPts <= 10^4 ''' class Solution: def new21Game(self, N: int, K: int, W: int) -> float: # When the game ends, the point is between K and K-1+W # What is the probability that the the point is less than N? # - If N is greater than K-1+W, probability is 1 # - If N is less than K, probability is 0 # If W == 3 and we want to find the probability to get a 5 # - You can get a card with value 1, 2, or 3 with equal probability (1/3) # - If you had a 4 and you get a 1: prob(4) * (1/3) # - If you had a 3 and you get a 2: prob(3) * (1/3) # - If you had a 2 and you get a 3: prob(2) * (1/3) # - If you had a 1, you can never reach a 5 in the next draw # - prob(5) = prob(4) / 3 + prob(3) / 3 + prob(2) /3 # To generalize: # The probability to get point K is # p(K) = p(K-1) / W + p(K-2) / W + p(K-3) / W + ... p(K-W) / W # let wsum = p(K-1) + p(K-2) + ... + p(K-W) # p(K) = wsum / W # dp is storing p(i) for i in [0 ... N] # - We need to maintain the window by # adding the new p(i), # and getting rid of the old p(i-w) # - check i >= W because we would not have negative points before drawing a card # For example, we can never get a point of 5 if we drew a card with a value of 6 # - check i < K because we cannot continue the game after reaching K # For example, if K = 21 and W = 10, the eventual point is between 21 and 30 # To get a point of 27, we can have: # - a 20 point with a 7 # - a 19 point with a 8 # - a 18 point with a 9 # - a 17 point with a 10 # - but cannot have 21 with a 6 or 22 with a 5 because the game already ends if K == 0 or N >= K + W: return 1 dp = [1.0] + [0.0] * N Wsum = 1.0 for i in range(1, N + 1): dp[i] = Wsum / W if i < K: Wsum += dp[i] if i - W >= 0: Wsum -= dp[i - W] return sum(dp[K:]) if __name__ == "__main__": print(Solution().new21Game(10, 1, 10))
''' -Hard- Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals. For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be: [1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7] Follow up: What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size? ''' class SummaryRanges(object): def __init__(self): """ Initialize your data structure here. """ self.intervals = [] def addNum(self, val): """ :type val: int :rtype: None """ if not self.intervals: self.intervals.append([val, val]) else: n = len(self.intervals) l = 0 r = n while l < r: m = l+(r-l)//2 if self.intervals[m][1] < val: l = m+1 else: r = m r -= 1 if r < 0: if val >= self.intervals[0][0] and \ val <= self.intervals[0][1]: return elif self.intervals[0][0]-val == 1: self.intervals[0] = [val, self.intervals[0][1]] else: self.intervals[0:0] = [[val, val]] elif r == n-1: if val-self.intervals[-1][1] == 1: self.intervals[-1] = [self.intervals[-1][0], val] else: self.intervals[n:n] = [[val, val]] else: if val >= self.intervals[r+1][0] and \ val <= self.intervals[r+1][1]: return elif val-self.intervals[r][1] == 1 and self.intervals[r+1][0]-val == 1: self.intervals[r:r+2] = [[self.intervals[r][0], self.intervals[r+1][1]]] elif val-self.intervals[r][1] == 1: self.intervals[r] = [self.intervals[r][0], val] elif self.intervals[r+1][0]-val == 1: self.intervals[r+1] = [val, self.intervals[r+1][1]] else: self.intervals[r+1:r+1] = [[val, val]] def getIntervals(self): """ :rtype: List[List[int]] """ return self.intervals if __name__ == "__main__": # Your SummaryRanges object will be instantiated and called as such: ''' obj = SummaryRanges() obj.addNum(1) print(obj.getIntervals()) obj.addNum(3) print(obj.getIntervals()) obj.addNum(7) print(obj.getIntervals()) obj.addNum(2) print(obj.getIntervals()) obj.addNum(6) print(obj.getIntervals()) ''' obj = SummaryRanges() obj.addNum(6) print(obj.getIntervals()) obj.addNum(6) print(obj.getIntervals()) obj.addNum(0) print(obj.getIntervals()) obj.addNum(4) print(obj.getIntervals()) obj.addNum(8) print(obj.getIntervals()) obj.addNum(7) print(obj.getIntervals()) obj.addNum(6) print(obj.getIntervals()) obj.addNum(4) print(obj.getIntervals()) obj.addNum(7) print(obj.getIntervals()) obj.addNum(5) print(obj.getIntervals())
''' -Medium- Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. Example 1: Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4 Output: 2 Explanation: Substring "aab" has 2 ocurrences in the original string. It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). Example 2: Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3 Output: 2 Explanation: Substring "aaa" occur 2 times in the string. It can overlap. Example 3: Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3 Output: 3 Example 4: Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3 Output: 0 Constraints: 1 <= s.length <= 10^5 1 <= maxLetters <= 26 1 <= minSize <= maxSize <= min(26, s.length) s only contains lowercase English letters. ''' from collections import Counter class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: n, m = len(s), Counter() left, right = 0, 0 oc = Counter() while right < n: c = s[right] m[c] += 1 right += 1 while len(m) > maxLetters: m[s[left]] -= 1 if m[s[left]] == 0: m.pop(s[left]) left += 1 while minSize <= right-left <= maxSize: oc[s[left:right]] += 1 m[s[left]] -= 1 if m[s[left]] == 0: m.pop(s[left]) left += 1 #print(oc) return max(oc.values()) if oc else 0 if __name__ == "__main__": print(Solution().maxFreq(s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4)) print(Solution().maxFreq(s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3)) print(Solution().maxFreq(s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3)) print(Solution().maxFreq(s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3))
''' -Easy- Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. Example 1: Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] Output: [1,5] Explanation: Only 1 and 5 appeared in the three arrays. Constraints: 1 <= arr1.length, arr2.length, arr3.length <= 1000 1 <= arr1[i], arr2[i], arr3[i] <= 2000 Hints Count the frequency of all elements in the three arrays. The elements that appeared in all the arrays would have a frequency of 3. ''' class Solution(object): def arraysIntersection(self, arr1, arr2, arr3): """ :type arr1: List[int] :type arr2: List[int] :type arr3: List[int] :rtype: List[int] """ # You may notice that Approach 1 does not utilize the fact that all arrays are sorted . Indeed, # instead of using a Hashmap to store the frequencies, we can use three pointers p1 , p2 , # and p3 to iterate through arr1 , arr2 , and arr3 accordingly: #Each time, we want to increment the pointer that points to the smallest number, i.e., # min(arr1[p1], arr2[p2], arr3[p3]) forward; #if the numbers pointed to by p1 , p2 , and p3 are the same, we should then store it and # move all three pointers forward. #Moreover, we don't have to move the pointer pointing to the smallest number - we only # need to move the pointer pointing to a smaller number. In this case, we avoid comparing # three numbers and finding the smallest one before deciding which one to move. You may # find the rationale behind this in the Algorithm. #!?!../Documents/1213_Intersection_of_Three_Sorted_Arrays.json:531,198!?! #Algorithm #Initiate three pointers p1 , p2 , p3 , and place them at the beginning of arr1 , arr2 , arr3 by initializing them to 0; #while they are within the boundaries: #if arr1[p1] == arr2[p2] && arr2[p2] == arr3[p3] , we should store it because it appears three times in arr1 , arr2 , and arr3 ; #else #if arr1[p1] < arr2[p2] , move the smaller one, i.e., p1 ; #else if arr2[p2] < arr3[p3] , move the smaller one, i.e., p2 ; #if neither of the above conditions is met, it means arr1[p1] >= arr2[p2] && arr2[p2] >= arr3[p3] , therefore move p3 . ans = [] # prepare three pointers to iterate through three arrays # p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly p1 = p2 = p3 = 0 while p1 < len(arr1) and p2 < len(arr2) and p3 < len(arr3): if arr1[p1] == arr2[p2] == arr3[p3]: ans.append(arr1[p1]) p1 += 1 p2 += 1 p3 += 1 else: if arr1[p1] < arr2[p2]: p1 += 1 elif arr2[p2] < arr3[p3]: p2 += 1 else: p3 += 1 return ans if __name__ == "__main__": print(Solution().arraysIntersection(arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]))
# -*- coding: utf-8 -*- """ Created on Sun Jun 25 14:20:26 2017 @author: merli """ class Solution(object): def insertAtBottom(self, s, ele): if s: tmp = s.pop() self.insertAtBottom(s, ele) s.append(tmp) else: s.append(ele) def reverseStack(self, s, level): level += 1 if s: top = s.pop() #print level, s self.reverseStack(s, level) print level, top, s self.insertAtBottom(s, top) #print level, s if __name__ == "__main__": s = [x for x in range(10)] Solution().reverseStack(s, 0) print s
''' -Medium- Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins. Example 1: Input: stones = [2,1] Output: true Explanation: The game will be played as follows: - Turn 1: Alice can remove either stone. - Turn 2: Bob removes the remaining stone. The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game. Example 2: Input: stones = [2] Output: false Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game. Example 3: Input: stones = [5,1,2,4,3] Output: false Explanation: Bob will always win. One possible way for Bob to win is shown below: - Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1. - Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4. - Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8. - Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10. - Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15. Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game. Constraints: 1 <= stones.length <= 105 1 <= stones[i] <= 104 ''' from typing import List from collections import Counter class Solution: def stoneGameIX(self, stones: List[int]) -> bool: # Important observation here is when turn came for alex or bob, # she/he can either choose one out of {"1" or "2"} and "0". Now, # at anyone turn, he/she have to take decision whether he/she will # choose {"1" or "2"} or {"0"}, and both case will yield right result. # Think about it, if alex is allowed to choose "1" (as sum formed after # choose 1 is not divisible by 3) but instead she choose "0" this will # result in reverse answer(as alex sort of skipped her turn). which is # in-fact same as alex would have choosen "1" and at then end when # snothing left out and forced to choose "0". n = len(stones) def get(k): cnt = Counter(a % 3 for a in stones) if cnt[k] < 1 : return False cnt[k] -= 1 sums = k for i in range(1, n): if cnt[1] and (sums+1) % 3 != 0: cnt[1] -= 1 sums += 1 elif cnt[2] and (sums+2) % 3 != 0: cnt[2] -= 1 sums += 2 elif cnt[0] and sums % 3 != 0: cnt[0] -= 1 else: return True if i % 2 else False return False return get(2) or get(1) if __name__ == "__main__": print(Solution().stoneGameIX(stones = [5,1,2,4,3])) print(Solution().stoneGameIX(stones = [2,1]))
''' -Medium- Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". Example 1: Input: s = "aabca" Output: 3 Explanation: The 3 palindromic subsequences of length 3 are: - "aba" (subsequence of "aabca") - "aaa" (subsequence of "aabca") - "aca" (subsequence of "aabca") Example 2: Input: s = "adc" Output: 0 Explanation: There are no palindromic subsequences of length 3 in "adc". Example 3: Input: s = "bbcbaba" Output: 4 Explanation: The 4 palindromic subsequences of length 3 are: - "bbb" (subsequence of "bbcbaba") - "bcb" (subsequence of "bbcbaba") - "bab" (subsequence of "bbcbaba") - "aba" (subsequence of "bbcbaba") Constraints: 3 <= s.length <= 105 s consists of only lowercase English letters. ''' from collections import Counter from string import ascii_lowercase class Solution: def countPalindromicSubsequence(self, s: str) -> int: #TLE # cnt = Counter(s) res = set() for c in s: tmp = set() for d in res: if len(d) == 1: tmp.add(d+c) elif len(d) == 2 and d[0] == c: tmp.add(d+c) res |= tmp if c not in res: res.add(c) # print(res) return sum(1 for r in res if len(r) == 3) def countPalindromicSubsequence2(self, s: str) -> int: cnt = [0]*26 for c in s: cnt[ord(c)-ord('a')] += 1 res = [[0]*26 for _ in range(26)] cnt1 = [0]*26 for c in s: idx1 = ord(c)-ord('a') for idx in range(26): if res[idx1][idx] > 0: continue if cnt1[idx] > 0 and cnt[idx] - (cnt1[idx] + (1 if idx==idx1 else 0)) > 0: res[idx1][idx] = 1 cnt1[idx1] += 1 return sum(sum(r) for r in res) def countPalindromicSubsequence3(self, s: str) -> int: first, last = [len(s)]*26, [0]*26 for i,c in enumerate(s): first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i) last[ord(c)-ord('a')] = i res = 0 for i in range(26): if first[i] < last[i]: res += len(set(s[first[i]+1:last[i]])) return res def countPalindromicSubsequence4(self, s): res = 0 for c in ascii_lowercase: i, j = s.find(c), s.rfind(c) if i > -1: res += len(set(s[i + 1: j])) return res if __name__ == "__main__": print(Solution().countPalindromicSubsequence(s = "aabca")) print(Solution().countPalindromicSubsequence(s = "adc")) print(Solution().countPalindromicSubsequence(s = "bbcbaba")) print(Solution().countPalindromicSubsequence2(s = "aabca")) print(Solution().countPalindromicSubsequence2(s = "adc")) print(Solution().countPalindromicSubsequence2(s = "bbcbaba")) print(Solution().countPalindromicSubsequence3(s = "aabca")) s = "tlpjzdmtwderpkpmgoyrcxttiheassztncqvnfjeyxxp" print(Solution().countPalindromicSubsequence4(s = s)) print(Solution().countPalindromicSubsequence3(s = s)) print(Solution().countPalindromicSubsequence2(s = s))
''' -Medium- *Sorting* *Greedy* You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: The value of the first element in arr must be 1. The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x. There are 2 types of operations that you can perform any number of times: Decrease the value of any element of arr to a smaller positive integer. Rearrange the elements of arr to be in any order. Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions. Example 1: Input: arr = [2,2,1,2,1] Output: 2 Explanation: We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. The largest element in arr is 2. Example 2: Input: arr = [100,1,1000] Output: 3 Explanation: One possible way to satisfy the conditions is by doing the following: 1. Rearrange arr so it becomes [1,100,1000]. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now arr = [1,2,3], which satisfies the conditions. The largest element in arr is 3. Example 3: Input: arr = [1,2,3,4,5] Output: 5 Explanation: The array already satisfies the conditions, and the largest element is 5. Constraints: 1 <= arr.length <= 105 1 <= arr[i] <= 109 ''' from typing import List class Solution: def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: arr.sort() ans, cur = 1, 1 for a in arr[1:]: if a-cur >= 1: cur += 1 ans = max(ans, cur) return ans
''' -Medium- *Difference Array* You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0. Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z'). Return the final string after all such shifts to s are applied. Example 1: Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]] Output: "ace" Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac". Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd". Finally, shift the characters from index 0 to index 2 forward. Now s = "ace". Example 2: Input: s = "dztz", shifts = [[0,0,0],[1,1,1]] Output: "catz" Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz". Finally, shift the characters from index 1 to index 1 forward. Now s = "catz". Constraints: 1 <= s.length, shifts.length <= 5 * 104 shifts[i].length == 3 0 <= starti <= endi < s.length 0 <= directioni <= 1 s consists of lowercase English letters. ''' from typing import List import string class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) diff = [0]*(n+1) t = string.ascii_lowercase m = {c:i for i,c in enumerate(t)} for st, en, d in shifts: if d: diff[st] += 1 diff[en+1] -= 1 else: diff[st] += -1 diff[en+1] -= -1 ret, sm = [], 0 for i in range(n): sm += diff[i] # ret.append(chr(ord('a') + (ord(s[i])-ord('a')+sm) % 26)) ret.append(t[(m[s[i]]+sm) % 26]) return ''.join(ret)
''' -Medium- You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge. The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i]. The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i. Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index. Example 1: Input: edges = [1,0,0,0,0,7,7,5] Output: 7 Explanation: - The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10. - The node 0 has an edge pointing to node 1. The edge score of node 1 is 0. - The node 7 has an edge pointing to node 5. The edge score of node 5 is 7. - The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11. Node 7 has the highest edge score so return 7. Example 2: Input: edges = [2,0,0,2] Output: 0 Explanation: - The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3. - The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3. Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0. Constraints: n == edges.length 2 <= n <= 105 0 <= edges[i] < n edges[i] != i ''' from typing import List class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) score = [0]*n for i in range(n): score[edges[i]] += i mx = 0 res = 0 # print(score) for i in range(n): if mx < score[i]: mx = score[i] res = i return res
''' -Hard- Given an array of digits, you can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1 Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. 1 <= n <= 109 ''' from typing import List from functools import lru_cache class Solution(object): def atMostNGivenDigitSetDP(self, digits, n): """ :type digits: List[str] :type n: int :rtype: int """ num = str(n) m = len(digits) N = len(num) res = 0 ''' 先来分析例子1,当n为 100 时,所有的一位数和两位数都是可以的,既然可以重复使用数字, 假设总共有m个数字,那么对于两位数来说,十位上和个位上分别都有m种可能,总共就是m^2 种可能,对于一位数来说,总共m种可能。那么看到这里就可以归纳出当n总共有N位的话, 我们就可以快速的求出不超过 N-1 位的所有情况综合,用个 for 循环,累加m的指数即可。 ''' for i in range(1,N): res += m ** i # compare each bit (left to right) of n to d in digits # only if i-th bit equals one of d, loop continues for i in range(N): hasSameNum = False for d in digits: if d < num[i]: # the i-th bit can use d, the rest can use all # digits so total # = m^(N-1-i) res += m**(N - 1 - i) elif d == num[i]: # no need to consider digits after d for i-th bit hasSameNum = True # if no d = i-th bit of n, we can return result if not hasSameNum: return res return res+1 def atMostNGivenDigitSet(self, digits, n): """ :type digits: List[str] :type n: int :rtype: int """ self.res = 0 digits.sort() def dfs(start, path): if path: if int(''.join(path)) <= n: # print(int(''.join(path))) self.res += 1 else: return for i in range(len(digits)): # We set the start to `i` because one element could # be used more than once path.append(digits[i]) dfs(i, path) path.pop() dfs(0, []) return self.res def atMostNGivenDigitSet2(self, digits: List[str], n: int) -> int: N = str(n) @lru_cache(None) def dfs(i, comp): # comp ----(-1 -> current number is bigger, 0 -> same, 1 smaller) if i == len(N): return comp > -1 if comp != 0: return 1 + len(digits) * dfs(i + 1, comp) ans = 1 for d in digits: if d == N[i]: ans += dfs(i + 1, 0) elif int(d) > int(N[i]): ans += dfs(i + 1, -1) else: ans += dfs(i + 1, 1) return ans return dfs(0, 0) - 1 def atMostNGivenDigitSet3(self, digits: List[str], n: int) -> int: D = list(int(d) for d in digits) N = list(int(i) for i in str(n)) @lru_cache(None) def dp(i, isPrefix, isBigger): if i == len(N): return not isBigger if not isPrefix and not isBigger: return 1 + len(D) * dp(i + 1, False, False) return 1 + sum(dp(i + 1, isPrefix and d == N[i], isBigger or (isPrefix and d > N[i])) for d in D) return dp(0, True, False) - 1 if __name__ == "__main__": print(Solution().atMostNGivenDigitSet(["1","3","5","7"], 100)) print(Solution().atMostNGivenDigitSetDP(["1","3","5","7"], 300)) #print(Solution().atMostNGivenDigitSet(["7"], 8)) print(Solution().atMostNGivenDigitSet2(["1","3","5","7"], 100)) # print(Solution().atMostNGivenDigitSet2(["1","3","5","7"], 300)) print(Solution().atMostNGivenDigitSet3(["1","3","5","7"], 100))
''' -Medium- *DFS* There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given 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. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. Example 1: Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] Output: 4 Explanation: The diagram above shows the tree. We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node. Example 2: Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] Output: 3 Explanation: The diagram above shows the tree. We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node. Constraints: 2 <= n <= 105 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree. 1 <= restricted.length < n 1 <= restricted[i] < n All the values of restricted are unique. ''' from typing import List from collections import defaultdict class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: graph = defaultdict(list) R = set(restricted) for u, v in edges: graph[u].append(v) graph[v].append(u) cnt = 0 vis = [False]*n def dfs(u): nonlocal cnt cnt += 1 vis[u] = True for v in graph[u]: if v not in R and not vis[v]: dfs(v) dfs(0) return cnt def reachableNodes2(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: graph = defaultdict(list) vis = set(restricted) for u, v in edges: graph[u].append(v) graph[v].append(u) def dfs(u): vis.add(u) for v in graph[u]: if v not in vis: dfs(v) dfs(0) return len(vis) - len(restricted) if __name__ == "__main__": print(Solution().reachableNodes(n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5])) print(Solution().reachableNodes(n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]))
''' -Hard- *Couting* *DP* *Digit DP* *Bitmask* We call a positive integer special if all of its digits are distinct. Given a positive integer n, return the number of special integers that belong to the interval [1, n]. Example 1: Input: n = 20 Output: 19 Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers. Example 2: Input: n = 5 Output: 5 Explanation: All the integers from 1 to 5 are special. Example 3: Input: n = 135 Output: 110 Explanation: There are 110 integers from 1 to 135 that are special. Some of the integers that are not special are: 22, 114, and 131. Constraints: 1 <= n <= 2 * 109 ''' from functools import lru_cache class Solution: def countSpecialNumbers(self, n: int) -> int: s, ans = str(n), 0 digits = len(s) for i in range(1, digits): x, k = 1, 9 for _ in range(i-1): x *= k k -= 1 ans += 9 * x # ways to get special integers with digits less than that in n done = [0]*10 for i in range(digits): smaller, idx = 0, ord(s[i])-ord('0') for j in range(idx): if done[j] == 0: smaller += 1 if i == 0 and s[i] > '0': smaller -= 1 aage, rem = 1, 10-i-1 for _ in range(i+1, digits): aage *= rem rem -= 1 ans += smaller * aage if done[idx] == 0: done[idx] = 1 else: return ans return ans + 1 def countSpecialNumbers2(self, n: int) -> int: # Digit DP solution s = str(n) @lru_cache(None) def dp(pos, tight, mask): # state: # pos: the position where a digit can be put, [1, len(s)] # tight: whether there is constraint on which digit can be picked: 0/1 # mask: indicate which digit has been picked [0, 2^10] if pos == len(s): return int(mask != 0) ans = 0 if tight == 1: for i in range(ord(s[pos]) - ord('0')+1): if mask & (1 << i) > 0: continue newmask = mask if mask == 0 and i == 0 else (mask | (1<<i)) if i == ord(s[pos]) - ord('0'): ans += dp(pos+1, 1, newmask) else: ans += dp(pos+1, 0, newmask) else: for i in range(10): if mask & (1 << i) > 0: continue newmask = mask if mask == 0 and i == 0 else (mask | (1<<i)) ans += dp(pos+1, 0, newmask) return ans return dp(0, 1, 0) if __name__ == "__main__": print(Solution().countSpecialNumbers(135)) print(Solution().countSpecialNumbers2(135))
''' -Medium- *Dijkstra's Algorithm* $$$ You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads, where roads[i] = [ai, bi, costi] indicates that there is a bidirectional road between cities ai and bi with a cost of traveling equal to costi. You can buy apples in any city you want, but some cities have different costs to buy apples. You are given the array appleCost where appleCost[i] is the cost of buying one apple from city i. You start at some city, traverse through various roads, and eventually buy exactly one apple from any city. After you buy that apple, you have to return back to the city you started at, but now the cost of all the roads will be multiplied by a given factor k. Given the integer k, return an array answer of size n where answer[i] is the minimum total cost to buy an apple if you start at city i. Example 1: Input: n = 4, roads = [[1,2,4],[2,3,2],[2,4,5],[3,4,1],[1,3,4]], appleCost = [56,42,102,301], k = 2 Output: [54,42,48,51] Explanation: The minimum cost for each starting city is the following: - Starting at city 1: You take the path 1 -> 2, buy an apple at city 2, and finally take the path 2 -> 1. The total cost is 4 + 42 + 4 * 2 = 54. - Starting at city 2: You directly buy an apple at city 2. The total cost is 42. - Starting at city 3: You take the path 3 -> 2, buy an apple at city 2, and finally take the path 2 -> 3. The total cost is 2 + 42 + 2 * 2 = 48. - Starting at city 4: You take the path 4 -> 3 -> 2 then you buy at city 2, and finally take the path 2 -> 3 -> 4. The total cost is 1 + 2 + 42 + 1 * 2 + 2 * 2 = 51. Example 2: Input: n = 3, roads = [[1,2,5],[2,3,1],[3,1,2]], appleCost = [2,3,1], k = 3 Output: [2,3,1] Explanation: It is always optimal to buy the apple in the starting city. Constraints: 2 <= n <= 1000 1 <= roads.length <= 1000 1 <= ai, bi <= n ai != bi 1 <= costi <= 105 appleCost.length == n 1 <= appleCost[i] <= 105 1 <= k <= 100 There are no repeated edges. ''' from typing import List import heapq from collections import defaultdict class Solution: def minCost(self, n: int, roads: List[List[int]], appleCost: List[int], k: int) -> List[int]: G = defaultdict(list) for u,v,c in roads: G[u].append((v, c)) G[v].append((u, c)) def dijkstra(city, C): pq = [(0, city)] while pq: cost, u = heapq.heappop(pq) if cost > C[u]: continue for v, c in G[u]: if C[v] > cost + c: C[v] = cost + c heapq.heappush(pq, (C[v], v)) ans = appleCost[:] for i in range(n): cost = [float('inf')]*(n+1) cost[i+1] = 0 dijkstra(i+1, cost) # print(ans[i], cost) for j in range(n): if i != j: ans[i] = min(ans[i], cost[j+1]*(k+1)+appleCost[j]) return ans def minCost2(self, n: int, roads: List[List[int]], appleCost: List[int], k: int) -> List[int]: def dijkstra(i): q = [(0, i)] dist = [float('inf')] * n dist[i] = 0 ans = float('inf') while q: d, u = heapq.heappop(q) ans = min(ans, appleCost[u] + d * (k + 1)) for v, w in g[u]: if dist[v] > dist[u] + w: dist[v] = dist[u] + w heapq.heappush(q, (dist[v], v)) return ans g = defaultdict(list) for a, b, c in roads: a, b = a - 1, b - 1 g[a].append((b, c)) g[b].append((a, c)) return [dijkstra(i) for i in range(n)] from random import randint if __name__=="__main__": print(Solution().minCost(n = 4, roads = [[1,2,4],[2,3,2],[2,4,5],[3,4,1],[1,3,4]], appleCost = [56,42,102,301], k = 2)) print(Solution().minCost(n = 3, roads = [[1,2,5],[2,3,1],[3,1,2]], appleCost = [2,3,1], k = 3)) N = 800 roads = [] appCost = [ randint(1, 100) for _ in range(N)] conn = defaultdict(set) for i in range(1, N+1): k = randint(1, N) while k == i: k = randint(1, N) if k not in conn[i]: roads.append([i, k, randint(1, 100)]) conn[i].add(k) print(len(roads)) sol1 = Solution().minCost(n = N, roads = roads, appleCost = appCost, k = 3) sol2 = Solution().minCost2(n = N, roads = roads, appleCost = appCost, k = 3)
''' -Hard- *Stack* *Monotonic Queue* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Example: Input: [2,1,5,6,2,3] Output: 10 ''' class Solution(object): def largestRectangleArea(self, heights): ''' For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and l - is the last coordinate of the bar to the left which height h[l] >= h[i] So if for any i coordinate we know his utmost higher (or of the same height) neighbors to the right and to the left, we can easily find the largest rectangle: ''' if not heights: return 0 n = len(heights) lessFromLeft = [0] * n lessFromRight = [0] * n lessFromLeft[0] = -1 lessFromRight[n-1] = n for i in range(1, n): p = i-1 ''' for example in order to left[i]; if height[i - 1] < height[i] then left[i] = i - 1; other wise we do not need to start scan from i - 1; we can start the scan from left[i - 1], because since left[i - 1] is the first position to the left of i - 1 that have height less than height[i - 1], and we know height[i - 1] >= height[i]; so left[i] must be at the left or at left[i - 1]; similar for the right array; Since we do not need to scan from scratch for each i, the time complexity can be simplified to O(n); ''' while p >= 0 and heights[p] >= heights[i]: p = lessFromLeft[p] lessFromLeft[i] = p for i in range(n-2, -1, -1): p = i+1 while p < n and heights[p] >= heights[i]: p = lessFromRight[p] lessFromRight[i] = p print(lessFromLeft) print(lessFromRight) maxArea = 0 for i in range(n): maxArea = max(maxArea, heights[i]*(lessFromRight[i]-lessFromLeft[i]-1)) return maxArea def largestRectangleAreaMonoQueue(self, heights): ''' For any bar i the maximum rectangle is of width r - l - 1 where r - is the first coordinate of the bar to the right with height h[r] < h[i]; if no such exists, set to len(heights) l - is the first coordinate of the bar to the left with height h[l] < h[i]; if no such exists, set to -1 So for any i coordinate we can easily find the rectangle formed using the ith bar as h[i]*width = h[i]*(r-l-1) ''' if not heights: return 0 n = len(heights) # rationale for setting -1 and n: # consider a bar with minimum height hmin # the rectangle it can form has height hmin # lessFromLeft will be -1 and # lessFromRight will be n for this bard # hence the width = (n - (-1)) - 1 = n, i.e., # the width of the whole histogram lessFromLeft = [-1] * n lessFromRight = [n] * n stack = [] for i,v in enumerate(heights): while stack and heights[stack[-1]] >= v: # right is from the popping out lessFromRight[stack.pop()] = i if stack: #left is from the pushing in # after popping above, what is left at the stack top is the # first smaller h than heights[i] lessFromLeft[i] = stack[-1] stack.append(i) print(lessFromLeft) print(lessFromRight) maxArea = 0 for i in range(n): maxArea = max(maxArea, heights[i]*(lessFromRight[i]-lessFromLeft[i]-1)) print(i, maxArea) return maxArea def largestRectangleAreaStack(self, heights): """ :type heights: List[int] :rtype: int """ n = len(heights) maxArea = 0 s = [] i = 0 while i < n: if (not s) or heights[i] >= heights[s[-1]]: s.append(i) i += 1 else: tp = s.pop() width = i if not s else i-1-s[-1] maxArea = max(maxArea, heights[tp]*width) while s: tp = s.pop() width = i if not s else i-1-s[-1] maxArea = max(maxArea, heights[tp]*width) return maxArea def largestRectangleAreaOnePass(self, heights): """ :type heights: List[int] :rtype: int """ heights = [0] + heights + [0] ret, n = 0, len(heights) stk = [] for i in range(n): while stk and heights[stk[-1]] > heights[i]: H = heights[stk[-1]] stk.pop() ret = max(ret, H*(i-stk[-1]-1)) stk.append(i) return ret print(Solution().largestRectangleArea([2,1,5,6,2,3])) print(Solution().largestRectangleAreaMonoQueue([2,1,5,6,2,3])) print(Solution().largestRectangleAreaMonoQueue([2,2,5,6,2,3])) print(Solution().largestRectangleAreaStack([2,1,5,6,2,3])) #print(Solution().largestRectangleArea([6, 2, 5, 4, 5, 1, 6]))
''' -Medium- Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. Implement the MyLinkedList class: MyLinkedList() Initializes the MyLinkedList object. int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1. void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. void addAtTail(int val) Append a node of value val as the last element of the linked list. void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted. void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid. Example 1: Input ["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"] [[], [1], [3], [1, 2], [1], [1], [1]] Output [null, null, null, null, 2, null, 3] Explanation MyLinkedList myLinkedList = new MyLinkedList(); myLinkedList.addAtHead(1); myLinkedList.addAtTail(3); myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 myLinkedList.get(1); // return 2 myLinkedList.deleteAtIndex(1); // now the linked list is 1->3 myLinkedList.get(1); // return 3 Constraints: 0 <= index, val <= 1000 Please do not use the built-in LinkedList library. At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex. ''' class Node(object): def __init__(self, val, next=None): self.val = val self.next = next class MyLinkedList: def __init__(self): self.head = None def get(self, index: int) -> int: cur, i = self.head, 0 while cur and i < index: cur = cur.next i += 1 return cur.val if cur else -1 def addAtHead(self, val: int) -> None: node = Node(val) node.next = self.head self.head = node def addAtTail(self, val: int) -> None: if self.head: cur = self.head while cur.next: cur = cur.next cur.next = Node(val) else: self.head = Node(val) def addAtIndex(self, index: int, val: int) -> None: dummy = Node(-1) dummy.next = self.head cur, i = self.head, 0 prev = dummy while cur and i < index: prev = cur cur = cur.next i += 1 if i == index: node = Node(val) prev.next = node node.next = cur self.head = dummy.next def deleteAtIndex(self, index: int) -> None: dummy = Node(-1) dummy.next = self.head cur, i = self.head, 0 prev = dummy while cur and i < index: prev = cur cur = cur.next i += 1 if cur: prev.next = cur.next self.head = dummy.next if __name__ == "__main__": myLinkedList = MyLinkedList() myLinkedList.addAtHead(1) myLinkedList.addAtTail(3) myLinkedList.addAtIndex(1, 2) # linked list becomes 1->2->3 print(myLinkedList.get(1)) # return 2 myLinkedList.deleteAtIndex(1) # now the linked list is 1->3 print(myLinkedList.get(1)) # return 3 myLinkedList = MyLinkedList() myLinkedList.addAtTail(3) print(myLinkedList.get(0)) # return 3 myLinkedList = MyLinkedList() myLinkedList.addAtHead(2) myLinkedList.deleteAtIndex(1) # now the linked list is 1->3 myLinkedList.addAtHead(2) myLinkedList.addAtHead(7) myLinkedList.addAtHead(3) myLinkedList.addAtHead(2) myLinkedList.addAtHead(5) myLinkedList.addAtTail(5) print(myLinkedList.get(5)) # return 3 myLinkedList.deleteAtIndex(6) # now the linked list is 1->3 myLinkedList.deleteAtIndex(4) # now the linked list is 1->3
''' -Medium- In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. Example 1: Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] Output: 14 Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. Example 2: Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] Output: 11 Explanation: The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C. Constraints: n == price.length n == needs.length 1 <= n <= 6 0 <= price[i] <= 10 0 <= needs[i] <= 10 1 <= special.length <= 100 special[i].length == n + 1 0 <= special[i][j] <= 50 ''' class Solution(object): def shoppingOffers(self, price, special, needs): """ :type price: List[int] :type special: List[List[int]] :type needs: List[int] :rtype: int """ res = sum(p*i for p,i in zip(price, needs)) def helper(offer, needs): r = [0]*len(needs) for i in range(len(needs)): if offer[i] > needs[i]: return [] r[i] = needs[i] - offer[i] return r for offer in special: r = helper(offer, needs) if r: res = min(res, self.shoppingOffers(price, special, r)+offer[-1]) return res if __name__ == "__main__": print(Solution().shoppingOffers(price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2])) print(Solution().shoppingOffers(price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]))
''' -Medium- Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function bool knows(a, b)which tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. Example 1: Input: graph = [ [1,1,0], [0,1,0], [1,1,1] ] Output: 1 Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. Example 2: Input: graph = [ [1,0,1], [1,1,0], [0,1,1] ] Output: -1 Explanation: There is no celebrity. Note: The directed graph is represented as an adjacency matrix, which is an n x n matrix where a[i][j] = 1 means person i knows person j while a[i][j] = 0 means the contrary. Remember that you won't have direct access to the adjacency matrix. ''' class Solution(object): def findCelebrity(self, n): res = 0 for i in range(n): if self.knows(res, i): res = i for i in range(i): if res != i and (self.knows(res, i) or (not self.knows(i, res))): return -1 return res def knows(self,a, b): return True
''' -Medium- Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise. Example 1: Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palindromes using all characters in s. Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" Example 2: Input: s = "leetcode", k = 3 Output: false Explanation: It is impossible to construct 3 palindromes using all the characters of s. Example 3: Input: s = "true", k = 4 Output: true Explanation: The only possible solution is to put each character in a separate string. Constraints: 1 <= s.length <= 105 s consists of lowercase English letters. 1 <= k <= 105 ''' from collections import Counter class Solution: def canConstruct(self, s: str, k: int) -> bool: n = len(s) if n < k: return False elif n == k: return True cnt = Counter(s) odd = sum(1 for x in cnt.values() if x % 2) return True if odd <= k else False if __name__ == "__main__": # print(Solution().canConstruct(s = "annabelle", k = 2)) print(Solution().canConstruct(s ="yzyzyzyzyzyzyzy", k = 2))
''' -Medium- There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day. Example 1: Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 Output: 16 Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. Example 2: Input: customers = [1], grumpy = [0], minutes = 1 Output: 1 Constraints: n == customers.length == grumpy.length 1 <= minutes <= n <= 2 * 10^4 0 <= customers[i] <= 1000 grumpy[i] is either 0 or 1. ''' from typing import List class Solution: def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int: C, G, M = customers, grumpy, minutes n = len(C) preSum = [0]*(n+1) for i in range(1,n+1): preSum[i] = preSum[i-1] + (C[i-1] if G[i-1] == 0 else 0) total = 0 for i in range(M): total += C[i] #res = total + preSum[n] - preSum[M] res = total - preSum[M] for i in range(M, n): total += C[i] - C[i-M] #res = max(res, total + preSum[n] - preSum[i+1] + preSum[i-M+1]) res = max(res, total - preSum[i+1] + preSum[i-M+1]) return res + preSum[n] def maxSatisfied2(self, customers: List[int], grumpy: List[int], minutes: int) -> int: C, G, M = customers, grumpy, minutes n = len(C) preSumi, preSumim = 0, 0 total = 0 for i in range(M): preSumi += C[i] if G[i] == 0 else 0 total += C[i] res = total - preSumi for i in range(M, n): total += C[i] - C[i-M] preSumi += C[i] if G[i] == 0 else 0 preSumim += C[i-M] if G[i-M] == 0 else 0 res = max(res, total - preSumi + preSumim) return res + preSumi if __name__ == '__main__': customers = [1,0,1,2,1,1,7,5]; grumpy = [0,1,0,1,0,1,0,1]; minutes = 3 print(Solution().maxSatisfied(customers, grumpy, minutes)) print(Solution().maxSatisfied2(customers, grumpy, minutes)) customers = [1]; grumpy = [0]; minutes = 1 print(Solution().maxSatisfied(customers, grumpy, minutes)) print(Solution().maxSatisfied2(customers, grumpy, minutes))
''' -Medium- *Greedy* *Priority Queue* There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. Example 1: Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] Output: 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. Example 2: Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] Output: 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. Constraints: n == apples.length == days.length 1 <= n <= 2 * 104 0 <= apples[i], days[i] <= 2 * 104 days[i] = 0 if and only if apples[i] = 0. ''' from typing import List import heapq class Solution: def eatenApples(self, apples: List[int], days: List[int]) -> int: pq, ans = [], 0 for i,(a,d) in enumerate(zip(apples, days)): while pq and pq[0][0] <= i: heapq.heappop(pq) if a > 0: heapq.heappush(pq, (i+d, a)) if pq and pq[0][1] > 0: ans += 1 day, j = heapq.heappop(pq) if j - 1 > 0: heapq.heappush(pq, (day, j-1)) i = len(apples) while pq: while pq and pq[0][0] <= i: heapq.heappop(pq) if pq and pq[0][1] > 0: ans += 1 day, j = heapq.heappop(pq) if j - 1 > 0: heapq.heappush(pq, (day, j-1)) i += 1 return ans def eatenApples2(self, apples: List[int], days: List[int]) -> int: pq, ans = [], 0 i, n = 0, len(apples) while i < n or pq: while pq and pq[0][0] <= i: heapq.heappop(pq) if i < len(apples) and apples[i] > 0: heapq.heappush(pq, (i+days[i], apples[i])) if pq and pq[0][1] > 0: ans += 1 day, j = heapq.heappop(pq) if j - 1 > 0: heapq.heappush(pq, (day, j-1)) i += 1 return ans if __name__ == "__main__": print(Solution().eatenApples(apples = [1,2,3,5,2], days = [3,2,1,4,2])) print(Solution().eatenApples(apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2])) print(Solution().eatenApples(apples = [3,0,0,1,2], days = [6,0,0,3,2])) print(Solution().eatenApples(apples = [2,1,10], days = [2,10,1])) print(Solution().eatenApples2(apples = [1,2,3,5,2], days = [3,2,1,4,2])) print(Solution().eatenApples2(apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2])) print(Solution().eatenApples2(apples = [3,0,0,1,2], days = [6,0,0,3,2])) print(Solution().eatenApples2(apples = [2,1,10], days = [2,10,1]))
''' -Medium- *Binary Search* You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. Example 1: Input: candies = [5,8,6], k = 3 Output: 5 Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. Example 2: Input: candies = [2,5], k = 11 Output: 0 Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0. Constraints: 1 <= candies.length <= 105 1 <= candies[i] <= 107 1 <= k <= 1012 ''' from typing import List class Solution: def maximumCandies(self, candies: List[int], k: int) -> int: A = candies n = len(candies) if sum(A) < k: return 0 l, r = 1, max(A)+1 def canAllocate(m): sums = 0 for i in A: sums += i // m return sums >= k while l < r: mid = l + (r-l)//2 if canAllocate(mid): l = mid + 1 else: r = mid # print(l,r,mid) return l-1 if __name__ == "__main__": print(Solution().maximumCandies(candies = [5,8,6], k = 3)) print(Solution().maximumCandies(candies = [5,8,6], k = 4)) print(Solution().maximumCandies(candies = [5,8,6], k = 5)) print(Solution().maximumCandies(candies = [1,2,3,4,10], k = 5)) print(Solution().maximumCandies([9,10,1,2,10,9,9,10,2,2],3))
''' -Medium- *Sliding Window* You are given an array nums consisting of positive integers. We call a subarray of an array complete if the following condition is satisfied: The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array. Return the number of complete subarrays. A subarray is a contiguous non-empty part of an array. Example 1: Input: nums = [1,3,1,2,2] Output: 4 Explanation: The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2]. Example 2: Input: nums = [5,5,5,5] Output: 10 Explanation: The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10. Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 2000 ''' from typing import List from collections import Counter class Solution: def countCompleteSubarrays(self, nums: List[int]) -> int: # O(N^2) ndis = len(set(nums)) n = len(nums) ans = 0 for i in range(n): st = set([nums[i]]) if len(st) == ndis: ans += 1 for j in range(i+1, n): st.add(nums[j]) if len(st) == ndis: ans += 1 return ans def countCompleteSubarrays2(self, nums: List[int]) -> int: # O(N) ndis = len(set(nums)) ans = 0 cnt = Counter() j = 0 proc = False for i,a in enumerate(nums): cnt[a] += 1 if len(cnt) == ndis: proc = True while len(cnt) == ndis: cnt[nums[j]] -= 1 if cnt[nums[j]] == 0: cnt.pop(nums[j]) j += 1 if proc: ans += j return ans if __name__ == "__main__": print(Solution().countCompleteSubarrays(nums = [1,3,1,2,2])) print(Solution().countCompleteSubarrays2(nums = [1,3,1,2,2])) print(Solution().countCompleteSubarrays(nums = [5,5,5,5])) print(Solution().countCompleteSubarrays2(nums = [5,5,5,5]))
''' -Medium- Design a data structure that takes an array of integers. Write a method that finds the position of the element with the minimum value between two given indices. ''' import math class RMQ(object): # Sparse Table (ST) Algorithm # O(NlogN) to construct ST table def __init__(self, nums): self.N = len(nums) self.A = nums self.M = [[0]*(int(math.log(self.N,2)+1)) for _ in range(self.N)] for i in range(self.N): self.M[i][0] = i j = 1 while 1<<j <= self.N: for i in range(self.N-(1<<j)+1): if nums[self.M[i][j-1]] <= nums[self.M[i+(1<<(j-1))][j-1]]: self.M[i][j] = self.M[i][j-1] else: self.M[i][j] = self.M[i+(1<<(j-1))][j-1] j += 1 # print(self.M) # O(1) to query the minimum def minRange(self, l, r): k = int(math.log(r-l+1, 2)) #print(k) return self.M[l][k] if self.A[self.M[l][k]] <= self.A[self.M[r-(1<<k)+1][k]] else self.M[r-(1<<k)+1][k] if __name__ == "__main__": A = [2,4,3,1,6,7,8,9,1,7] rmq = RMQ(A) print(rmq.minRange(2,7)) # 3 print(rmq.minRange(0,9)) # 3 print(rmq.minRange(0,2)) # 0 print(rmq.minRange(4,7)) # 4 A = [1,2,3,2] rmq = RMQ(A) print(rmq.minRange(2,3)) # 0
''' -Medium- *Greedy* *Backtracking* 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: n = len(pattern) candi = ''.join(str(i) for i in range(1,n+2)) res = '9'*(n+1) def helper(p, s, used): nonlocal res if len(s) == n+1: res = min(res, s) for i,c in enumerate(candi): if not used[i]: used[i] = True if p[0] == 'I' and c > s[-1]: helper(p[1:], s+c, used) if p[0] == 'D' and c < s[-1]: helper(p[1:], s+c, used) used[i] = False used = [False]*(n+1) for i,c in enumerate(candi): used[i] = True helper(pattern, c, used) used[i] = False return res def smallestNumber2(self, s: str) -> str: res = [] for i,c in enumerate(s + 'I', 1): if c == 'I': res += range(i, len(res), -1) return ''.join(map(str,res)) def smallestNumber3(self, s): res, stack = [], [] for i,c in enumerate(s + 'I', 1): stack.append(str(i)) if c == 'I': res += stack[::-1] stack = [] return ''.join(res)
''' -Medium- An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic. Given an integer n, return true if n is strictly palindromic and false otherwise. A string is palindromic if it reads the same forward and backward. Example 1: Input: n = 9 Output: false Explanation: In base 2: 9 = 1001 (base 2), which is palindromic. In base 3: 9 = 100 (base 3), which is not palindromic. Therefore, 9 is not strictly palindromic so we return false. Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic. Example 2: Input: n = 4 Output: false Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic. Therefore, we return false. Constraints: 4 <= n <= 105 ''' class Solution: def isStrictlyPalindromic(self, n: int) -> bool: def isPalin(x, k): dig = [] while x: d = x % k x //= k dig.append(d) return dig == dig[::-1] for i in range(2, n-1): if not isPalin(n, i): return False return True def isStrictlyPalindromic2(self, n: int) -> bool: # just a brain teaser return False
''' -Hard- *DP* *Greedy* Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb", p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb", p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb", p = "a*c?b" Output: false Constraints: 0 <= s.length, p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters, '?' or '*'. ''' class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ """ 这道题通配符外卡匹配问题还是小有难度的,有特殊字符 ‘*’ 和 ‘?’,其中 ‘?’ 能代替任何字符, ‘*’ 能代替任何字符串,注意跟另一道 Regular Expression Matching 正则匹配的题目区分开来。 两道题的星号的作用是不同的,注意对比区分一下。这道题最大的难点,就是对于星号的处理,可以 匹配任意字符串,简直像开了挂一样,就是说在星号对应位置之前,不管你s中有任何字符串,我大星 号都能匹配你,主角光环啊。但即便叼如斯的星号,也有其处理不了的问题,那就是一旦p中有s中不 存在的字符,那么一定无法匹配,因为星号只能增加字符,不能消除字符,再有就是星号一旦确定了 要匹配的字符串,对于星号位置后面的匹配情况也就鞭长莫及了。所以p串中星号的位置很重要,用 jStar 来表示,还有星号匹配到s串中的位置,使用 iStart 来表示,这里 iStar 和 jStar 均初 始化为 -1,表示默认情况下是没有星号的。然后再用两个变量i和j分别指向当前s串和p串中遍历到 的位置。 开始进行匹配,若i小于s串的长度,进行 while 循环。若当前两个字符相等,或着p中的字符是问号, 则i和j分别加1。若 p[j] 是星号,要记录星号的位置,jStar 赋为j,此时j再自增1,iStar 赋为i。 若当前 p[j] 不是星号,并且不能跟 p[i] 匹配上,此时就要靠星号了,若之前星号没出现过,那么 就直接跪,比如 s = "aa" 和 p = "c*",此时 s[0] 和 p[0] 无法匹配,虽然 p[1] 是星号,但 还是跪。如果星号之前出现过,可以强行续一波命,比如 s = "aa" 和 p = "*c",当发现 s[1] 和 p[1] 无法匹配时,但是好在之前 p[0] 出现了星号,把 s[1] 交给 p[0] 的星号去匹配。至于如何 知道之前有没有星号,这时就能看出 iStar 的作用了,因为其初始化为 -1,而遇到星号时,其就会 被更新为i,只要检测 iStar 的值,就能知道是否可以使用星号续命。虽然成功续了命,匹配完了s中 的所有字符,但是之后还要检查p串,此时没匹配完的p串里只能剩星号,不能有其他的字符,将连续的 星号过滤掉,如果j不等于p的长度,则返回 false, """ i, j, iStar, jStar = 0, 0, -1, -1 m, n = len(s), len(p) while i < m: if j < n and (s[i] == p[j] or p[j] == '?'): i += 1 j += 1 elif j < n and p[j] == '*': iStar, jStar = i, j j += 1 elif iStar >= 0: # now s[i] != p[j] and p[j] is not * or ? # keep using prior * to match s[i] i, j = iStar, jStar + 1 iStar += 1 else: return False while j < n and p[j] == '*': j += 1 return j == n def isMatchDP(self, s, p): """ :type s: str :type p: str :rtype: bool """ """ 对于这种玩字符串的题目,动态规划 Dynamic Programming 是一大神器,因为字符串跟其子串之间的 关系十分密切,正好适合 DP 这种靠推导状态转移方程的特性。那么先来定义dp数组吧,使用一个二维 dp 数组,其中 dp[i][j] 表示 s中前i个字符组成的子串和p中前j个字符组成的子串是否能匹配。大 小初始化为 (m+1) x (n+1),加1的原因是要包含 dp[0][0] 的情况,因为若s和p都为空的话,也应 该返回 true,所以也要初始化 dp[0][0] 为 true。还需要提前处理的一种情况是,当s为空,p为连 续的星号时的情况。由于星号是可以代表空串的,所以只要s为空,那么连续的星号的位置都应该为true, 所以先将连续星号的位置都赋为 true。然后就是推导一般的状态转移方程了,如何更新 dp[i][j], 首先处理比较 tricky 的情况,若p中第j个字符是星号,由于星号可以匹配空串,所以如果p中的前 j-1 个字符跟s中前i个字符匹配成功了( dp[i][j-1] 为true)的话,则 dp[i][j] 也能为 true。 或者若p中的前j个字符跟s中的前i-1个字符匹配成功了( dp[i-1][j] 为true )的话,则 dp[i][j] 也能为 true(因为星号可以匹配任意字符串,再多加一个任意字符也没问题)。若p中的第j个字符不是 星号,对于一般情况,假设已经知道了s中前 i-1 个字符和p中前 j-1 个字符的匹配情况(即 dp[i-1][j-1] ),现在只需要匹配s中的第i个字符跟p中的第j个字符,若二者相等(s[i-1] == p[j-1]), 或者p中的第j个字符是问号( p[j-1] == '?' ),再与上 dp[i-1][j-1] 的值,就可以更新 dp[i][j] 了, """ m, n = len(s), len(p) dp = [[False for _ in range(n+1)] for _ in range(m+1)] dp[0][0] = True for i in range(1, n+1): if p[i - 1] == '*': dp[0][i] = dp[0][i - 1] for i in range(1, m+1): for j in range(1, n+1): if p[j - 1] == '*': dp[i][j] = dp[i - 1][j] or dp[i][j - 1] else: dp[i][j] = (s[i - 1] == p[j - 1] or p[j - 1] == '?') and dp[i - 1][j - 1] return dp[m][n] if __name__ == "__main__": print(Solution().isMatch("adceb", "*a*b")) print(Solution().isMatchDP("adceb", "*a*b"))
''' -Easy- You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false. Example 1: Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank". Example 2: Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap. Example 3: Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required. Example 4: Input: s1 = "abcd", s2 = "dcba" Output: false Constraints: 1 <= s1.length, s2.length <= 100 s1.length == s2.length s1 and s2 consist of only lowercase English letters. ''' from collections import defaultdict class Solution: def areAlmostEqual(self, s1: str, s2: str) -> bool: m1, m2 = defaultdict(set), defaultdict(set) for i in range(len(s1)): m1[s1[i]].add(i) m2[s2[i]].add(i) mismatch = 0 for c in m1: if len(m1[c]) != len(m2[c]): return False mismatch += len(m1[c]) - len((m1[c] & m2[c])) if mismatch > 2: return False return True if __name__ == "__main__": print(Solution().areAlmostEqual(s1 = "bank", s2 = "kanb")) print(Solution().areAlmostEqual(s1 = "abcd", s2 = "dcba")) print(Solution().areAlmostEqual("qgqeg","gqgeq")) print(Solution().areAlmostEqual("ysmpagrkzsmmzmsssutzgpxrmoylkgemgfcperptsxjcsgojwourhxlhqkxumonfgrczmjvbhwvhpnocz", "ysmpagrqzsmmzmsssutzgpxrmoylkgemgfcperptsxjcsgojwourhxlhkkxumonfgrczmjvbhwvhpnocz"))
''' -Medium- A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class: CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree. int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode. TreeNode get_root() Returns the root node of the tree. Example 1: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] Explanation CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get_root(); // return [1, 2, 3, 4] Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 5000 root is a complete binary tree. 0 <= val <= 5000 At most 104 calls will be made to insert and get_root. ''' from typing import Optional from collections import deque # 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 CBTInserter: def __init__(self, root: Optional[TreeNode]): self.root = root def insert(self, val: int) -> int: que = deque([self.root]) node = TreeNode(val) while que: nq = deque() for i in range(len(que)): cur = que.popleft() if not cur.left: cur.left = node return cur.val else: nq.append(cur.left) if not cur.right: cur.right = node return cur.val else: nq.append(cur.right) que = nq return None def get_root(self) -> Optional[TreeNode]: return self.root
''' -Medium- Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). Example 1: Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2] Example 3: Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step. Constraints: The number of nodes in the tree is in the range [1, 3000]. 1 <= Node.val, target <= 1000 ''' from typing import Optional # 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 removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def dfs(node): if not node: return None node.left = dfs(node.left) node.right = dfs(node.right) if not node.left and not node.right and node.val == target: return None return node return dfs(root)
''' -Medium- *DP* *Stack* You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. Example 1: Input: s = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). Example 2: Input: s = "bbaaaaabb" Output: 2 Explanation: The only solution is to delete the first two characters. Constraints: 1 <= s.length <= 105 s[i] is 'a' or 'b'​​. ''' class Solution: def minimumDeletions(self, s: str) -> int: n = len(s) dp = [0]*(n+1) bcount = 0 for i in range(1, n+1): if s[i-1] == 'a': # case 1: keep current a. ==> prev chars must be a...a # so need to remove all 'b' chars before i, which is bcount # case 2: remove current a ==> prev chars must be a...ab...b # so need to remove current a and whatever makes substring before # current i valid which is dp[i]; dp[i] = min(dp[i-1]+1, bcount) else: # since it is always valid to append 'b' if substring before current i is # valid, so just copy whatever makes substring before i valid which is dp[i]; dp[i] = dp[i-1] bcount += 1 return dp[n] def minimumDeletions2(self, s: str) -> int: n = len(s) dp, dp0 = 0, 0 bcount = 0 for i in range(1, n+1): if s[i-1] == 'a': # case 1: keep current a. ==> prev chars must be a...a # so need to remove all 'b' chars before i, which is bcount # case 2: remove current a ==> prev chars must be a...ab...b # so need to remove current a and whatever makes substring before # current i valid which is dp[i]; dp = min(dp0+1, bcount) else: # since it is always valid to append 'b' if substring before current i is # valid, so just copy whatever makes substring before i valid which is dp[i]; dp = dp0 bcount += 1 dp, dp0 = dp0, dp return dp0 def minimumDeletions3(self, s: str) -> int: stack = [] res = 0 for c in s: if stack and c < stack[-1]: stack.pop() res += 1 else: stack.append(c) return res if __name__ == "__main__": print(Solution().minimumDeletions(s = "aababbab"))
''' -Easy- Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. You may return the answer in any order. Example 1: Input: ["bella","label","roller"] Output: ["e","l","l"] Example 2: Input: ["cool","lock","cook"] Output: ["c","o"] Note: 1 <= A.length <= 100 1 <= A[i].length <= 100 A[i][j] is a lowercase letter ''' import sys class Solution(object): def commonChars(self, A): """ :type A: List[str] :rtype: List[str] """ res = [] # for each lower case letter i (1-26), cnt[i] # contains the minimum number of occurrances of i # in every word cnt = [sys.maxsize] * 26 for word in A: t = [0] * 26 for c in word: t[ord(c) - ord('a')] += 1 for i in range(26): cnt[i] = min(cnt[i], t[i]) for i in range(26): for j in range(cnt[i]): res.append(chr(ord('a') + i)) return res if __name__ == "__main__": print(Solution().commonChars(["bella","label","roller"]))
''' -Medium- Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Note: If the given node has no in-order successor in the tree, return null. Example 1: Input: root = [2,1,3], p = 1 2 / \ 1 3 Output: 2 Example 2: Input: root = [5,3,6,2,4,null,null,1], p = 6 5 / \ 3 6 / \ 2 4 / 1 Output: null ''' # 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 inorderSuccessor(self, root, p): """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ """ The in-order successor of a node is the left-most node in its right sub-tree, if exists. If not, then it is the root of the smallest left sub-tree this node is in. """ successor = None if p.right is not None: node = p.right successor = node # find its left-most node while node.left is not None: node = node.left successor = node return successor else: node = root successor = None while True: if node is None: return None if node == p: break elif p.val < node.val: successor = node node = node.left else: node = node.right return successor def inorderSuccessorOnSpace(self, root, p): # write your code here """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ if not root: return None res = [] def helper(node): if not node: return helper(node.left) res.append(node) helper(node.right) helper(root) res.append(None) l, r = 0, len(res)-1 while l < r: m = l + (r-l)//2 if res[m] == p: return res[m+1] elif res[m].val < p.val: l = m+1 else: r = m return None
''' -Hard- *BFS* *Dijkstra's Algorithm* You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1). Example 1: Input: grid = [[0,1,1],[1,1,0],[1,1,0]] Output: 2 Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2). It can be shown that we need to remove at least 2 obstacles, so we return 2. Note that there may be other ways to remove 2 obstacles to create a path. Example 2: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]] Output: 0 Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 2 <= m * n <= 105 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0 ''' from typing import List from collections import deque import heapq class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: # 0-1 BFS m, n = map(len, (grid, grid[0])) dist = [[float('inf')] * n for _ in range(m)] dist[0][0] = grid[0][0] hp = deque([(dist[0][0], 0, 0)]) while hp: d, r, c = hp.popleft() if (r, c) == (m - 1, n - 1): return d for i, j in (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1): if m > i >= 0 <= j < n and grid[i][j] + d < dist[i][j]: dist[i][j] = grid[i][j] + d if grid[i][j] == 1: hp.append((dist[i][j], i, j)) else: hp.appendleft((dist[i][j], i, j)) return dist[-1][-1] def minimumObstacles2(self, grid: List[List[int]]) -> int: # Dijkstra m, n = map(len, (grid, grid[0])) dist = [[float('inf')] * n for _ in range(m)] dist[0][0] = grid[0][0] hp = [(dist[0][0], 0, 0)] while hp: o, r, c = heapq.heappop(hp) if (r, c) == (m - 1, n - 1): return o for i, j in (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1): if m > i >= 0 <= j < n and grid[i][j] + o < dist[i][j]: dist[i][j] = grid[i][j] + o heapq.heappush(hp, (dist[i][j], i, j))
''' -Hard- Given a string num that contains only digits and an integer target, return all possibilities to add the binary operators '+', '-', or '*' between the digits of num so that the resultant expression evaluates to the target value. Example 1: Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Example 2: Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Example 3: Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Example 4: Input: num = "00", target = 0 Output: ["0*0","0+0","0-0"] Example 5: Input: num = "3456237490", target = 9191 Output: [] Constraints: 1 <= num.length <= 10 num consists of only digits. -2^31 <= target <= 2^31 - 1 ''' class Solution(object): def addOperators(self, num, target): """ :type num: str :type target: int :rtype: List[str] """ res = [] def helper(num, diff, curNum, out): if len(num) == 0 and curNum == target: res.append(out) return for i in range(1, len(num)+1): cur = num[:i] if len(cur) > 1 and cur[0] == '0': return nxt = num[i:] # if num == '23': print(i, cur, nxt, len(out)) if len(out) > 0: helper(nxt, int(cur), curNum + int(cur), out + "+" + cur) helper(nxt, -int(cur), curNum - int(cur), out + "-" + cur) helper(nxt, diff * int(cur), (curNum - diff) + diff * int(cur), out + "*" + cur) else: helper(nxt, int(cur), int(cur), cur) helper(num, 0, 0, "") return res if __name__ == "__main__": print(Solution().addOperators(num = "123", target = 6)) print(Solution().addOperators(num = "123", target = 123)) print(Solution().addOperators(num = "000", target = 0))
''' -Medium- $$$ There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges. You are given the integer n. The parent node of a node with a label v is the node with the label floor (v / 2). The root of the tree is the node with the label 1. For example, if n = 7, then the node with the label 3 has the node with the label floor(3 / 2) = 1 as its parent, and the node with the label 7 has the node with the label floor(7 / 2) = 3 as its parent. You are also given an integer array queries. Initially, every node has a value 0 on it. For each query queries[i], you should flip all values in the subtree of the node with the label queries[i]. Return the total number of nodes with the value 1 after processing all the queries. Note that: Flipping the value of a node means that the node with the value 0 becomes 1 and vice versa. floor(x) is equivalent to rounding x down to the nearest integer. Example 1: Input: n = 5 , queries = [1,2,5] Output: 3 Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1. After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5. Example 2: Input: n = 3, queries = [2,3,3] Output: 1 Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1. After processing the queries, there are one red node (node with value 1): 2. Constraints: 1 <= n <= 105 1 <= queries.length <= 105 1 <= queries[i] <= n ''' from typing import List from collections import Counter class Solution: def numberofNodes(self, n: int , queries: List[int]) -> int: # wrong cnt = [0]*(n+1) for q in queries: cnt[q] += 1 def dfs(i): res = 1 if cnt[i] % 2 else 0 if i*2 <= n: res += dfs(i*2) if i*2+1 <= n: res += dfs(i*2+1) return res return dfs(1) def numberofNodes2(self, n: int , queries: List[int]) -> int: def dfs(i): if i > n: return tree[i] ^= 1 dfs(i << 1) dfs(i << 1 | 1) tree = [0] * (n + 1) cnt = Counter(queries) for i, v in cnt.items(): if v & 1: dfs(i) return sum(tree) if __name__ == '__main__': # print(Solution().numberofNodes(n = 5 , queries = [1,2,5,2])) # print(Solution().numberofNodes(n = 3, queries = [2,3,3])) print(Solution().numberofNodes2(n = 5 , queries = [1,2,5])) print(Solution().numberofNodes2(n = 3, queries = [2,3,3]))
''' -Easy- Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6] Example 2: Input: nums = [1,1] Output: [2] Constraints: n == nums.length 1 <= n <= 10^5 1 <= nums[i] <= n Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. ''' from typing import List class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: n = len(nums) for i in range(n): while nums[i] != i+1 and nums[i] != nums[nums[i]-1]: j = nums[i]-1 nums[j], nums[i] = nums[i], nums[j] res = [] for i,v in enumerate(nums, start=1): if v != i: res.append(i) return res if __name__ == '__main__': print(Solution().findDisappearedNumbers([4,3,2,7,8,2,3,1])) print(Solution().findDisappearedNumbers([1,1]))
''' -Medium- There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network. Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it's not possible, return -1. Example 1: Input: n = 4, connections = [[0,1],[0,2],[1,2]] Output: 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Example 3: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] Output: -1 Explanation: There are not enough cables. Example 4: Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]] Output: 0 Constraints: 1 <= n <= 10^5 1 <= connections.length <= min(n*(n-1)/2, 10^5) connections[i].length == 2 0 <= connections[i][0], connections[i][1] < n connections[i][0] != connections[i][1] There are no repeated connections. No two computers are connected by more than one cable. ''' from collections import defaultdict class Solution(object): def makeConnected(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: int """ if len(connections) < n-1: return -1 g = defaultdict(set) for u,v in connections: g[u].add(v) g[v].add(u) visited = [False]*n def dfs(node): visited[node] = True for nxt in g[node]: if not visited[nxt]: visited[nxt] = True dfs(nxt) islands = 0 for i in range(n): if not visited[i]: dfs(i) islands += 1 return islands-1 def makeConnectedUF(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: int """ if len(connections) < n-1: return -1 roots = [i for i in range(n)] islands = n for u,v in connections: x = self.find(roots, u) y = self.find(roots, v) if x != y: islands -= 1 roots[x] = y return islands-1 def find(self, roots, i): # this while loop is called "qiuck union"; # it "recursively" decends to the root node represented by the # node whose roots value is untouched 'i' while roots[i] != i: # path compression; set every other node in path point to its grandparent roots[i] = roots[roots[i]] i = roots[i] return i if __name__ == "__main__": print(Solution().makeConnected(4, [[0,1],[0,2],[1,2]])) print(Solution().makeConnected(6, [[0,1],[0,2],[0,3],[1,2],[1,3]])) print(Solution().makeConnected(6, [[0,1],[0,2],[0,3],[1,2]])) print(Solution().makeConnected(5, [[0,1],[0,2],[3,4],[2,3]])) print(Solution().makeConnectedUF(4, [[0,1],[0,2],[1,2]])) print(Solution().makeConnectedUF(6, [[0,1],[0,2],[0,3],[1,2],[1,3]])) print(Solution().makeConnectedUF(6, [[0,1],[0,2],[0,3],[1,2]])) print(Solution().makeConnectedUF(5, [[0,1],[0,2],[3,4],[2,3]]))
''' Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. You need to return the number of important reverse pairs in the given array. Example1: Input: [1,3,2,3,1] Output: 2 Example2: Input: [2,4,3,5,1] Output: 3 Note: The length of the given array will not exceed 50,000. All the numbers in the input array are in the range of 32-bit integer. ''' from collections import deque import bisect class Solution(object): def reversePairsBIT(self, nums): ''' here BIT is not used for storing prefix sums ''' res = 0 copy = sorted(nums) bit = [0] * (len(nums) + 1) def search(i): sum = 0 while i < len(bit): sum += bit[i] i += i & (-i) return sum def insert(i): while i > 0: bit[i] += 1 i -= i & (-i) def index(a, val): l, r = 0, len(a)-1 while l <= r: m = l + (r-l)//2 if a[m] >= val: r = m-1 else: l = m+1 return l+1 # for every number i of the array, search BIT for the presence # of elements that is 2*i+1 or bigger; the only possible elements # already in BIT are to the left of i, since until now, only those # have been inserted into BIT for ele in nums: c = index(copy, 2*ele+1) a = search(c) res += a b = index(copy, ele) insert(b) print(ele, res, a, b, c, bit) return res def reversePairs2(self, nums): ''' here BIT is not used for storing prefix sums ''' res = 0 copy = sorted(nums) bit = [0] * (len(nums) + 1) def search(i): sum = 0 while i < len(bit): sum += bit[i] i += i & (-i) return sum def insert(i): while i > 0: bit[i] += 1 i -= i & (-i) # for every number i of the array, search BIT for the presence # of elements that is 2*i+1 or bigger; the only possible elements # already in BIT are to the left of i, since until now, only those # have been inserted into BIT for ele in nums: c = bisect.bisect_left(copy, 2*ele+1) a = search(c+1) res += a b = bisect.bisect_left(copy, ele) insert(b+1) # print(ele, res, a, b, c, bit) return res def reversePairs(self, nums): count = [0] def merge(nums): if len(nums) <= 1: return nums left, right = merge(nums[:len(nums)//2]), merge(nums[len(nums)//2:]) l = r = 0 while l < len(left) and r < len(right): if left[l] <= 2 * right[r]: l += 1 else: count[0] += len(left) - l r += 1 return sorted(left+right) merge(nums) return count[0] print(Solution().reversePairs([1,3,2,3,1])) print(Solution().reversePairs2([1,3,2,3,1])) print(Solution().reversePairs([2,4,3,5,1])) print(Solution().reversePairs2([2,4,3,5,1])) print(Solution().reversePairs2([-5,-5])) # print(Solution().reversePairsBIT([2,4,3,5,1])) # print(Solution().reversePairsBIT([5,7,9,4,2,15,8]))
''' -Medium- In a given 2D binary array grid, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1's.) Now, we may change 0s to 1s so as to connect the two islands together to form 1 island. Return the smallest number of 0s that must be flipped. (It is guaranteed that the answer is at least 1.) Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1 Constraints: 2 <= grid.length == grid[0].length <= 100 grid[i][j] == 0 or grid[i][j] == 1 ''' from typing import List from collections import deque class Solution: def shortestBridge(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dirs = [(0, -1), (0, 1), (1, 0), (-1, 0)] # visited = [[False]*n for _ in range(m)] def dfs(i, j): for di, dj in dirs: x, y = i+di, j+dj if 0 <= x < m and 0 <= y < n and grid[x][y] == 1: grid[x][y] = 2 dfs(x,y) def modify(): for i in range(m): for j in range(n): if grid[i][j] == 1: grid[i][j] = 2 dfs(i,j) return modify() print(grid) que = deque() for i in range(m): for j in range(n): if grid[i][j] == 2: que.append((i,j,0)) while que: i, j, steps = que.popleft() for di, dj in dirs: x, y = i+di, j+dj if not (0 <= x < m and 0 <= y < n): continue if grid[x][y] == 0: grid[x][y] = 2 que.append((x, y, steps+1)) elif grid[x][y] == 1: return steps return 1 if __name__ == "__main__": grid = [[1,1,1,1,1], [1,0,0,0,1], [1,0,1,0,1], [1,0,0,0,1], [1,1,1,1,1]] print(Solution().shortestBridge(grid)) grid = [[0,1,0],[0,0,0],[0,0,1]] print(Solution().shortestBridge(grid))
''' -Medium- $$$ *Two Pointers* *Greedy* You are given an array nums consisting of positive integers. You can perform the following operation on the array any number of times: Choose any two adjacent elements and replace them with their sum. For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1]. Return the minimum number of operations needed to turn the array into a palindrome. Example 1: Input: nums = [4,3,2,1,2,3,1] Output: 2 Explanation: We can turn the array into a palindrome in 2 operations as follows: - Apply the operation on the fourth and fifth element of the array, nums becomes equal to [4,3,2,3,3,1]. - Apply the operation on the fifth and sixth element of the array, nums becomes equal to [4,3,2,3,4]. The array [4,3,2,3,4] is a palindrome. It can be shown that 2 is the minimum number of operations needed. Example 2: Input: nums = [1,2,3,4] Output: 3 Explanation: We do the operation 3 times in any position, we obtain the array [10] at the end which is a palindrome. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 106 ''' from typing import List class Solution: def minimumOperations(self, nums: List[int]) -> int: A, n = nums, len(nums) i, j, ans = 0, n-1, 0 a, b = A[i], A[j] while i < j: if a == b: i += 1 j -= 1 a, b = A[i], A[j] elif a < b: i += 1 a += A[i] ans += 1 else: j -=1 b += A[j] ans += 1 return ans if __name__ == "__main__": print(Solution().minimumOperations(nums = [4,3,2,1,2,3,1])) print(Solution().minimumOperations(nums = [4,3,2,1]))
''' -Medium- We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.) Example 1: Input: s = "(123)" Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"] Example 2: Input: s = "(00011)" Output: ["(0.001, 1)", "(0, 0.011)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed. Example 3: Input: s = "(0123)" Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"] Example 4: Input: s = "(100)" Output: [(10, 0)] Explanation: 1.0 is not allowed. Note: 4 <= s.length <= 12. s[0] = "(", s[s.length - 1] = ")", and the other elements in s are digits. ''' class Solution(object): def ambiguousCoordinates(self, s): """ :type s: str :rtype: List[str] """ def findAll(S): n = len(S) if n == 0 or (n > 1 and S[0] == '0' and S[n - 1] == '0'): return [] if n > 1 and S[0] == '0': return ["0." + S[1:]] if S[n - 1] == '0': return [S] res = [S] for i in range(1, n): res.append(S[:i] + "." + S[i:]) return res res = [] n = len(s) for i in range(1, n - 2): print(s[1:i+1], s[i+1:n-1]) A = findAll(s[1:i+1]) B = findAll(s[i+1:n-1]) res += ["(" + a + ", " + b + ")" for a in A for b in B] return res if __name__ == "__main__": #print(Solution().ambiguousCoordinates(s = "(123)")) print(Solution().ambiguousCoordinates(s = "(00011)"))
''' -Medium- Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Follow up: You may only use constant extra space. Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem. Example 1: Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Constraints: The number of nodes in the given tree is less than 6000. -100 <= node.val <= 100 ''' # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next #from BinaryTree import (TreeNode, constructBinaryTree, null) class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ def helper(root): if root: if root.left and root.right: root.left.next = root.right pre = root cur = pre.next while pre and cur: #print(pre.val, '(',pre.next.val,')', cur.val) if pre.right: if cur.left: pre.right.next = cur.left if cur.right and not cur.left.next: cur.left.next = cur.right pre, cur = cur, cur.next elif cur.right: pre.right.next = cur.right pre, cur = cur, cur.next else: cur = cur.next elif pre.left: if cur.left: pre.left.next = cur.left if cur.right and not cur.left.next: cur.left.next = cur.right pre, cur = cur, cur.next elif cur.right: pre.left.next = cur.right pre, cur = cur, cur.next else: cur = cur.next else: pre, cur = cur, cur.next helper(root.left) helper(root.right) helper(root) return root def connectLevelOrder(self, root): """ :type root: Node :rtype: Node """ node = root while node: tempChild = Node(0) cur = tempChild while node: if node.left: cur.next = node.left cur = cur.next if node.right: cur.next = node.right cur = cur.next node = node.next node = tempChild.next return root if __name__ == "__main__": root = Node(2) node2 = Node(1) node3 = Node(3) node4 = Node(0) node5 = Node(7) node6 = Node(9) node7 = Node(1) node8 = Node(8) node9 = Node(2) node10 = Node(1) node11 = Node(0) node12 = Node(8) node13 = Node(8) node14 = Node(7) root.left = node2 root.right = node3 node2.left = node4 node2.right = node5 node3.left = node6 node3.right = node7 node4.left = node9 node5.left = node10 node5.right = node11 node7.left = node12 node7.right = node13 node11.left = node14 #root = Solution().connect(root) root = Solution().connectLevelOrder(root) cur = root while cur: pre = cur while pre: print(pre.val, end='') pre = pre.next print("#", end='') cur = cur.left
''' -Medium- *DFS* *BFS* You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. Example 1: Input: bombs = [[2,1,3],[6,1,4]] Output: 2 Explanation: The above figure shows the positions and ranges of the 2 bombs. If we detonate the left bomb, the right bomb will not be affected. But if we detonate the right bomb, both bombs will be detonated. So the maximum bombs that can be detonated is max(1, 2) = 2. Example 2: Input: bombs = [[1,1,5],[10,10,5]] Output: 1 Explanation: Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1. Example 3: Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]] Output: 5 Explanation: The best bomb to detonate is bomb 0 because: - Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0. - Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2. - Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3. Thus all 5 bombs are detonated. Constraints: 1 <= bombs.length <= 100 bombs[i].length == 3 1 <= xi, yi, ri <= 105 ''' from typing import List from collections import defaultdict class Solution: def maximumDetonation(self, bombs: List[List[int]]) -> int: graph = defaultdict(list) n = len(bombs) for i in range(n): x1, y1, r1 = bombs[i] for j in range(i+1,n): x2, y2, r2 = bombs[j] d2 = (x1-x2)**2+ (y1-y2)**2 if d2 <= r1*r1 + 1.e-5: graph[i].append(j) if d2 <= r2*r2 + 1.e-5: graph[j].append(i) # print(graph) def dfs(i, vis): ans = 1 for j in graph[i]: if not vis[j]: vis[j] = True ans += dfs(j, vis) return ans res = 0 for i in range(n): visited = [False]*n visited[i] = True res = max(res, dfs(i, visited)) return res
''' -Medium- *Sorting* *Monotonic Stack* You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters. Example 1: Input: properties = [[5,5],[6,3],[3,6]] Output: 0 Explanation: No character has strictly greater attack and defense than the other. Example 2: Input: properties = [[2,2],[3,3]] Output: 1 Explanation: The first character is weak because the second character has a strictly greater attack and defense. Example 3: Input: properties = [[1,5],[10,4],[4,3]] Output: 1 Explanation: The third character is weak because the second character has a strictly greater attack and defense. Constraints: 2 <= properties.length <= 10^5 properties[i].length == 2 1 <= attacki, defensei <= 10^5 ''' from typing import List from collections import defaultdict class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: P = properties n, ans, max_y = len(P), 0, -1 groups = defaultdict(list) for a,d in P: groups[a].append(d) for t in sorted(list(groups.keys()))[::-1]: for q in groups[t]: if q < max_y: ans += 1 for q in groups[t]: max_y = max(max_y, q) return ans def numberOfWeakCharacters2(self, properties: List[List[int]]) -> int: P = properties P.sort(key=lambda x: (x[0], -x[1])) n, ans, max_ = len(P), 0, -1 print(P) for a, d in P[::-1]: if d < max_: ans += 1 max_ = max(max_, d) return ans def numberOfWeakCharacters3(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x: (x[0], -x[1])) stack = [] ans = 0 for a, d in properties: while stack and stack[-1] < d: stack.pop() ans += 1 stack.append(d) return ans if __name__ == "__main__": print(Solution().numberOfWeakCharacters([[5,5],[6,3],[3,6]])) print(Solution().numberOfWeakCharacters([[2,2],[3,3]])) print(Solution().numberOfWeakCharacters([[1,5],[10,4],[4,3]])) print(Solution().numberOfWeakCharacters([[1,1],[2,1],[2,2],[1,2]])) print(Solution().numberOfWeakCharacters2([[5,5],[6,3],[3,6]])) print(Solution().numberOfWeakCharacters2([[2,2],[3,3]])) print(Solution().numberOfWeakCharacters2([[1,5],[10,4],[4,3]])) print(Solution().numberOfWeakCharacters2([[1,1],[2,1],[2,2],[1,2]]))
''' -Hard- *Sliding Window* *Monotonic Queue* You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget. The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots. Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget. Example 1: Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25 Output: 3 Explanation: It is possible to run all individual and consecutive pairs of robots within budget. To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25. It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3. Example 2: Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19 Output: 0 Explanation: No robot can be run that does not exceed the budget, so we return 0. Constraints: chargeTimes.length == runningCosts.length == n 1 <= n <= 5 * 104 1 <= chargeTimes[i], runningCosts[i] <= 105 1 <= budget <= 1015 ''' from typing import List from collections import deque class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: #O(NlogN) C, R, n = chargeTimes, runningCosts, len(runningCosts) l, r = 0, n+1 preSum = [0]*(n+1) for i in range(n): preSum[i+1] = preSum[i] + R[i] def canRun(k): if k == 0: return True dq = deque() for i in range(n): j = i - k + 1 while dq and C[dq[-1]] < C[i]: dq.pop() dq.append(i) if i >= k and dq[0] < j: dq.popleft() if j >= 0 and C[dq[0]] + k*(preSum[i+1]-preSum[j]) <= budget: return True return False while l < r: mid = l + (r-l)//2 if canRun(mid): l = mid + 1 else: r = mid return l-1 def maximumRobots2(self, times: List[int], costs: List[int], budget: int) -> int: # O(N) cur = i = 0 n = len(times) d = deque() for j in range(n): cur += costs[j] while d and times[d[-1]] <= times[j]: d.pop() d.append(j) if times[d[0]] + (j - i + 1) * cur > budget: if d[0] == i: d.popleft() cur -= costs[i] i += 1 return n - i def maximumRobots3(self, times: List[int], costs: List[int], budget: int) -> int: # O(N) cur = i = 0 n = len(times) d = deque() ans = 0 for j in range(n): cur += costs[j] while d and times[d[-1]] <= times[j]: d.pop() d.append(j) while d and times[d[0]] + (j - i + 1) * cur > budget: if d[0] == i: d.popleft() cur -= costs[i] i += 1 ans = max(ans, j-i+1) return ans if __name__ == "__main__": print(Solution().maximumRobots(chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25)) print(Solution().maximumRobots(chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19)) C = [32,83,96,70,98,80,30,42,63,67,49,10,80,13,69,91,73,10] R = [49,67,92,26,18,22,38,34,36,26,32,84,39,42,88,51,8,2] print(Solution().maximumRobots(chargeTimes = C, runningCosts= R, budget=599)) print(Solution().maximumRobots3(C, R, 599))
''' -Medium- Given a 0-indexed integer array nums, return the number of subarrays of nums having an even product. Example 1: Input: nums = [9,6,7,13] Output: 6 Explanation: There are 6 subarrays with an even product: - nums[0..1] = 9 * 6 = 54. - nums[0..2] = 9 * 6 * 7 = 378. - nums[0..3] = 9 * 6 * 7 * 13 = 4914. - nums[1..1] = 6. - nums[1..2] = 6 * 7 = 42. - nums[1..3] = 6 * 7 * 13 = 546. Example 2: Input: nums = [7,3,5] Output: 0 Explanation: There are no subarrays with an even product. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 ''' from typing import List class Solution: def evenProduct(self, nums: List[int]) -> int: eidx = -1 ans = 0 for i,v in enumerate(nums): if v % 2 == 0: ans += i+1 eidx = i else: ans += eidx+1 return ans def evenProduct2(self, nums: List[int]) -> int: ans, last = 0, -1 for i, v in enumerate(nums): if v % 2 == 0: last = i ans += last + 1 return ans if __name__ == "__main__": print(Solution().evenProduct(nums = [9,6,7,13])) print(Solution().evenProduct(nums = [7,3,5])) print(Solution().evenProduct2(nums = [9,6,7,13])) print(Solution().evenProduct2(nums = [7,3,5]))
''' -Hard- *Greedy* *GCD* There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps. In one step, you can move from point (x, y) to any one of the following points: (x, y - x) (x - y, y) (2 * x, y) (x, 2 * y) Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise. Example 1: Input: targetX = 6, targetY = 9 Output: false Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned. Example 2: Input: targetX = 4, targetY = 7 Output: true Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7). Constraints: 1 <= targetX, targetY <= 109 ''' from math import gcd from collections import Counter class Solution: def isReachable(self, targetX: int, targetY: int) -> bool: g = gcd(targetX, targetY) return Counter(bin(g))['1'] == 1 def isReachable2(self, targetX: int, targetY: int) -> bool: return (True if targetX == 1 and targetY == 1 else self.isReachable2(targetX//2, targetY) if targetX % 2 == 0 else self.isReachable2(targetX, targetY//2) if targetY % 2 == 0 else self.isReachable2(targetX-targetY, targetY) if targetX > targetY else self.isReachable2(targetX, targetY-targetX) if targetY > targetX else False ) def isReachable3(self, targetX: int, targetY: int) -> bool: if targetX == 1 and targetY == 1: return True elif targetX % 2 == 0: return self.isReachable3(targetX//2, targetY) elif targetY % 2 == 0: return self.isReachable3(targetX, targetY//2) elif targetX > targetY: return self.isReachable3(targetX-targetY, targetY) elif targetY > targetX: return self.isReachable3(targetX, targetY-targetX) else: return False if __name__ == '__main__': print(Solution().isReachable(targetX = 4, targetY = 7)) print(Solution().isReachable2(targetX = 4, targetY = 7)) print(Solution().isReachable3(targetX = 4, targetY = 7))
''' -Medium- One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note: You are not allowed to reconstruct the tree. Example 1: Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Example 2: Input: preorder = "1,#" Output: false Example 3: Input: preorder = "9,#,#,1" Output: false Constraints: 1 <= preorder.length <= 10^4 preoder consist of integers in the range [0, 100] and '#' separated by commas ','. ''' class Solution(object): def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ nodes = preorder.split(',') print(nodes) cnt = 0 for c in nodes[:-1]: if c == '#': if cnt == 0: return False cnt -= 1 else: cnt += 1 return cnt == 0 and nodes[-1] == '#' if __name__ == "__main__": print(Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"))
''' -Hard- *Hash Table* Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5 ''' from typing import List import collections class Solution: def maxEqualFreq(self, nums: List[int]) -> int: # cnt records the occurence of each num, freq records the frequence of number of # occurences. max_F is the largest frequence. cnt,freq,maxF,res = collections.defaultdict(int), collections.defaultdict(int),0,0 for i,num in enumerate(nums): cnt[num] += 1 freq[cnt[num]-1] -= 1 # if cnt of num is bumped by 1, the cnt freq freq[cnt[num]] += 1 # needs to be updated: maxF = max(maxF,cnt[num]) if (maxF*freq[maxF] == i # all elements appear max_F times, except one appears once. or (maxF-1)*(freq[maxF-1]+1) == i # all elements appear max_F-1 times, except one appears max_F. or maxF == 1): # all elements appear exact once. res = i + 1 return res if __name__ == "__main__": print(Solution().maxEqualFreq([2,2,1,1,5,3,3,5])) print(Solution().maxEqualFreq([1,1,1,2,2,2,3,3,3,4,4,4,5]))
''' -Medium- 描述 Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. You don't need to care about the order of the result. 样例 Example 1: input:["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"] output: [["a","z"],["abc","bcd","xyz"],["acef"],["az","ba"]] Example 2: input:["a"] output:[["a"]] ''' from itertools import groupby from collections import defaultdict class Solution: """ @param strings: a string array @return: return a list of string array """ def groupStrings(self, strings): # write your code here # The relative distance between each letter of the string and the # first character is equal. # For example, abc and efg are mutually offset. For abc, the distance # between b and a is 1, and the distance between c and a is 2. For efg, # the distance between f and e is 1, and the distance between g and e # is 2. . # Let’s look at another example. The distance between az and yx, z # and a is 25, and the distance between x and y is also 25 (direct # subtraction is -1, which is the reason for adding 26 and taking the # remainder). # Then, in this case, all strings that are offset from each other # have a unique distance difference. According to this, the mapping # can be well grouped. groups = defaultdict(list) ans = [] for s in strings: t = '' for c in s: t += str((ord(c)+26-ord(s[0]))%26)+',' groups[t].append(s) print(groups) return list(groups.values()) if __name__=="__main__": print(Solution().groupStrings(["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]))
''' -Easy- Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). Example 1: Input: s = "abc", t = "ahbgdc" Output: true Example 2: Input: s = "axc", t = "ahbgdc" Output: false Constraints: 0 <= s.length <= 100 0 <= t.length <= 10^4 s and t consist only of lowercase English letters. Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? ''' import bisect as bi from collections import defaultdict class Solution: def isSubsequence(self, s: str, t: str) -> bool: i = j = 0 while i < len(s) and j < len(t): if s[i] == t[j]: i += 1; j += 1 else: j += 1 return i == len(s) def isSubsequence2(self, s: str, t: str) -> bool: # for followup, preprocess t # binary search the succesive position of s's character # in the index arrays of each t's character idx = defaultdict(list) for i, c in enumerate(t): idx[c].append(i) print(idx) prev = 0 for i, c in enumerate(s): j = bi.bisect_left(idx[c], prev) if j == len(idx[c]): return False prev = idx[c][j] + 1 print('prev:', prev) return True if __name__ == "__main__": print(Solution().isSubsequence(s = "abc", t = "ahbgdc")) print(Solution().isSubsequence(s = "axc", t = "ahbgdc")) print(Solution().isSubsequence2(s = "abc", t = "ahbgdc")) print(Solution().isSubsequence2(s = "axc", t = "ahbgdc"))
''' -Easy- There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional 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. You want to determine if there is a valid path that exists from vertex start to vertex end. Given edges and the integers n, start, and end, return true if there is a valid path from start to end, or false otherwise. Example 1: Input: n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2 Output: true Explanation: There are two paths from vertex 0 to vertex 2: - 0 → 1 → 2 - 0 → 2 Example 2: Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5 Output: false Explanation: There is no path from vertex 0 to vertex 5. Constraints: 1 <= n <= 2 * 10^5 0 <= edges.length <= 2 * 10^5 edges[i].length == 2 0 <= ui, vi <= n - 1 ui != vi 0 <= start, end <= n - 1 There are no duplicate edges. There are no self edges. ''' from typing import List from collections import defaultdict class Solution: def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool: graph = defaultdict(list) for u,v in edges: graph[u].append(v) graph[v].append(u) visited = [False]*n visited[start] = True def dfs(u): if u == end: return True for v in graph[u]: if not visited[v]: visited[v] = True if dfs(v): return True return False return dfs(start) if __name__ == "__main__": print(Solution().validPath(n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2)) print(Solution().validPath(n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5)) print(Solution().validPath(10, [[4,3],[1,4],[4,8],[1,7],[6,4],[4,2],[7,4],[4,0],[0,9],[5,4]], 5, 9))
''' Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lower-case English letters. ''' from collections import defaultdict class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ memo = defaultdict(list) for s in strs: memo[tuple(sorted(s))].append(s) return list(memo.values()) if __name__ == "__main__": print(Solution().groupAnagrams(["eat","tea","tan","ate","nat","bat"])) print(Solution().groupAnagrams([""])) print(Solution().groupAnagrams(["a"]))
''' -Medium- There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices. Each monkey moves simultaneously to a neighboring vertex. A neighboring vertex for a vertex i can be: the vertex (i + 1) % n in the clockwise direction, or the vertex (i - 1 + n) % n in the counter-clockwise direction. A collision happens if at least two monkeys reside on the same vertex after the movement. Return the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo 109 + 7. Note that each monkey can only move once. Example 1: Input: n = 3 Output: 6 Explanation: There are 8 total possible movements. Two ways such that they collide at some point are: - Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide. - Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide. It can be shown 6 total movements result in a collision. Example 2: Input: n = 4 Output: 14 Explanation: It can be shown that there are 14 ways for the monkeys to collide. Constraints: 3 <= n <= 109 ''' class Solution: def monkeyMove(self, n: int) -> int: MOD = 10**9 + 7 def quick(n): if n == 0: return 1 elif n % 2 == 0: x = quick(n//2) return (x*x) % MOD else: return (2*quick(n-1)) % MOD return (quick(n) - 2) % MOD if __name__ == '__main__': print(Solution().monkeyMove(500000003))
''' -Medium- Given the root of a perfect binary tree, reverse the node values at each odd level of the tree. For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2]. Return the root of the reversed tree. A binary tree is perfect if all parent nodes have two children and all leaves are on the same level. The level of a node is the number of edges along the path between it and the root node. Example 1: Input: root = [2,3,5,8,13,21,34] Output: [2,5,3,8,13,21,34] Explanation: The tree has only one odd level. The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3. Example 2: Input: root = [7,13,11] Output: [7,11,13] Explanation: The nodes at level 1 are 13, 11, which are reversed and become 11, 13. Example 3: Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2] Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1] Explanation: The odd levels have non-zero values. The nodes at level 1 were 1, 2, and are 2, 1 after the reversal. The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal. Constraints: The number of nodes in the tree is in the range [1, 214]. 0 <= Node.val <= 105 root is a perfect binary tree. ''' from typing import Optional from BinaryTree import (TreeNode) from collections import deque # 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 reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: left, right = deque(), [] que = deque([root]) lev = 0 while que: newque = deque() k, size = 0, 1 << lev for _ in range(len(que)): node = que.popleft() if node.left: newque.append(node.left) newque.append(node.right) if lev % 2 == 0: if k < size: left.append(node.left) else: right.append(node.left) k += 1 if k < size: left.append(node.right) else: right.append(node.right) k += 1 que = newque lev += 1 while left and right: l, r = left.popleft(), right.pop() l.val, r.val = r.val, l.val return root
''' -Easy- *Queue* Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means only push to back, peek/pop from front, size, and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue's standard operations. Follow-up: Can you implement the stack such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer. Example 1: Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False Constraints: 1 <= x <= 9 At most 100 calls will be made to push, pop, top, and empty. All the calls to pop and top are valid. ''' from collections import deque class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.q = deque() def push(self, x): """ Push element x onto stack. :type x: int :rtype: None """ n = len(self.q) self.q.append(x) for i in range(n): self.q.append(self.q[0]) self.q.popleft() def states(self): print(self.q) def pop(self): """ Removes the element on top of the stack and returns that element. :rtype: int """ return self.q.popleft() def top(self): """ Get the top element. :rtype: int """ return self.q[0] def empty(self): """ Returns whether the stack is empty. :rtype: bool """ return not self.q if __name__ == "__main__": # Your MyQueue object will be instantiated and called as such: obj = MyStack() obj.push(1) obj.push(2) print(obj.top()) print(obj.pop()) print(obj.empty()) obj = MyStack() obj.push(1) obj.push(2) obj.push(3) obj.push(4) obj.states()
''' -Medium- *Sorting* Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Example 1: Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Constraints: 1 <= intervals.length <= 2 * 10^4 intervals[i].length == 2 -2 * 10^4 <= starti < endi <= 2 * 10^4 ''' class Solution(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ """ sort by starting point: the minimum number of intervals to cover the whole range """ intervals.sort() last = 0 res = 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[last][1]: res += 1 if intervals[i][1] < intervals[last][1]: last = i else: last = i return res def eraseOverlapIntervals2(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ """ sort by ending point: the maximum number of intervals that are non-overlapping 为了保留更多的区间数目,在众多重合的区间里面,我们会优先选择右端点靠前的区间。 因为它对后续的影响最小,有更大的概率让更多的区间出现。 """ intervals.sort(key=lambda x: x[1]) i, cnt = 0, 0 while i < len(intervals): cnt += 1 j = i+1 while j < len(intervals) and intervals[j][0] < intervals[i][1]: j += 1 i = j return len(intervals) - cnt if __name__ == "__main__": print(Solution().eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]])) print(Solution().eraseOverlapIntervals2([[1,2],[2,3],[3,4],[1,3]]))
''' -Easy- *Prefix Sum* Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. Example 1: Input: s = "011101" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right = "1101", score = 1 + 3 = 4 left = "011" and right = "101", score = 1 + 2 = 3 left = "0111" and right = "01", score = 1 + 1 = 2 left = "01110" and right = "1", score = 2 + 1 = 3 Example 2: Input: s = "00111" Output: 5 Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 Example 3: Input: s = "1111" Output: 3 Constraints: 2 <= s.length <= 500 The string s consists of characters '0' and '1' only. ''' class Solution(object): def maxScore(self, s): """ :type s: str :rtype: int """ n = len(s) preSum = [0]*(n+1) for i in range(1,n+1): if s[i-1] == '1': preSum[i] = preSum[i-1]+1 else: preSum[i] = preSum[i-1] zeros, res = 0, 0 for i in range(n-1): if s[i] == '0': zeros += 1 res = max(res, zeros+preSum[n]-preSum[i+1]) return res if __name__ == "__main__": print(Solution().maxScore("011101")) print(Solution().maxScore("1111")) print(Solution().maxScore("00"))
''' -Medium- *Hash Table* *Bijection* Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. Example 1: Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. Example 2: Input: words = ["a","b","c"], pattern = "a" Output: ["a","b","c"] Constraints: 1 <= pattern.length <= 20 1 <= words.length <= 50 words[i].length == pattern.length pattern and words[i] are lowercase English letters. ''' class Solution(object): def findAndReplacePattern(self, words, pattern): """ :type words: List[str] :type pattern: str :rtype: List[str] """ def match(s, t): m, q = {}, set() for c, p in zip(s, t): if p not in m: if c not in q: m[p] = c q.add(c) else: return False elif m[p] != c: return False return True return [w for w in words if match(w, pattern)] if __name__ == "__main__": print(Solution().findAndReplacePattern(words = ["abc","deq","mee", "aqq","dkd","ccc"], pattern = "abb")) print(Solution().findAndReplacePattern(["ef","fq","ao","at","lx"], "ya"))
''' -Medium- You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows: If x is a negative integer, then abs(x) = -x. If x is a non-negative integer, then abs(x) = x. Example 1: Input: nums = [1,-3,2,3,-4] Output: 5 Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5. Example 2: Input: nums = [2,-5,1,-4,3,-2] Output: 8 Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8. Constraints: 1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 ''' from typing import List class Solution: def maxAbsoluteSum(self, nums: List[int]) -> int: maxPos = 0 if nums[0] < 0 else nums[0] maxNeg = 0 if nums[0] > 0 else nums[0] res = abs(nums[0]) for i in range(1, len(nums)): maxPos = max(maxPos+nums[i], nums[i]) maxNeg = min(maxNeg+nums[i], nums[i]) res = max(res, maxPos, -maxNeg) return res if __name__ == "__main__": print(Solution().maxAbsoluteSum([1,-3,2,3,-4])) print(Solution().maxAbsoluteSum([2,-5,1,-4,3,-2]))
''' -Hard- *Difference Array* *Prefix Sum* You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point. For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k. Example 1: Input: nums = [2,3,1,4,0] Output: 3 Explanation: Scores for each k are listed below: k = 0, nums = [2,3,1,4,0], score 2 k = 1, nums = [3,1,4,0,2], score 3 k = 2, nums = [1,4,0,2,3], score 3 k = 3, nums = [4,0,2,3,1], score 4 k = 4, nums = [0,2,3,1,4], score 3 So we should choose k = 3, which has the highest score. Example 2: Input: nums = [1,3,0,2,4] Output: 0 Explanation: nums will always have 3 points no matter how it shifts. So we will choose the smallest k, which is 0. Constraints: 1 <= nums.length <= 10^5 0 <= nums[i] < nums.length ''' from typing import List class Solution: def bestRotation(self, nums: List[int]) -> int: # This problem can be thought of as a transformation to a more well known problem. # After we have the transformation, we can solve it effiently. # Definitions # Let A be the input array, and N be the number of elements in the array. Let A[i] denote # the value at index i in input array A. And let K be the number of rotations. # The Transformation # For every number in the array, write the ranges which the value will yield a score of + 1. # Example: # A: [2, 3, 1, 4, 0] # Range for 2: [1, 3] (Rotating the array for any value of 1 <= K <= 3 will give us a point for 2. # Range for 3: [2, 3] # Range for 1: [0, 1] and [3, 4] # ... and so on # After doing that, the value of K that gives the highest score is the value that is common to # the most # of ranges. The question is how do we solve for that value? A simple approach would # be to keep an array, called count, with indices from 0 to 4, and add 1 to each indice for # every range that contains it. At the end the best value of k is the indice for which count # has the largest value. # Example: # count would look like this if we added + 1 for range [1, 3]: count [0, 1, 1, 1, 0]. We would # continue to add for every range. So after adding range [2, 3], count would look like [0, 1, 2, 2, 0] # ... and so on. # But this would be O(n^2). We can improve this by making a simple adaptation. To represent some # range [a, b] we can instead add +1 to only the indice a, and subtract 1 to the last b + 1 (if it exists). # This would mean that we add +1 to every index >= a, and subtract -1 to every index b + 1. After # doing this for every range, we can accumate from the front, we should get the same array count, # as we did with out n^2 version. A = nums count = [0]*len(A) for i in range(len(A)): if A[i] <= i: # in this case: A[i] <= i, to get a point we can # 1) take no moves since A[i] is already scoring a point # 2) move A[i] left to position A[i] which takes i-A[i] moves # 3) move A[i] left to all positions b.w. 1) and 2) # 4) move A[i] left and then to N-1 position which takes i+1 moves # 5) move A[i] left to i+1 position by first to N-1 and then left to i+1 which takes N-1 moves # 6) move A[i] to all positions b.w. 4) and 5) # for case 4), 5), 6), we only need to increment count[i+1] because # count[N-1+1] = count[N] does not exist # the range for case 1), 2) and 3) [mini, maxi] mini = 0 maxi = i - A[i] count[mini] += 1 if maxi + 1 < len(A): count[maxi + 1] += -1 # the range for case 4), 5) and 6) [i+1, N-1] if i + 1 < len(A): count[i+1] += 1 else: #if A[i] == len(A): # continue #no valid range # in this case: A[i] > i, to get a point we can # 1) move A[i] left and then to N-1 position which takes i+1 moves # 2) move A[i] left to i by first to N-1 and then left to i which takes N-(A[i]-i) moves # 3) move A[i] to all positions b.w. 1) and 2) # the range for case 1), 2) and 3) [mini, maxi] mini = i + 1 maxi = len(A) - (A[i] - i) count[mini] += 1 if maxi + 1 < len(A): count[maxi + 1] += -1 # count[] is in fact a difference array # we take prefixSum to recover the original array for i in range(1, len(A)): count[i] += count[i-1] #print('max score is ', max(count)) return count.index(max(count)) # the highest score is max(count) # while its index is the K that makes the highest score if __name__=="__main__": print(Solution().bestRotation(nums = [2,3,1,4,0])) print(Solution().bestRotation([1,3,0,2,4]))
class Solution(object): def knightDialer(self, N): """ :type N: int :rtype: int """ moves={1:[8,6], 2:[7, 9], 3:[4,8], 4:[0,3,9], 5:[], 6:[0,1,7], 7:[2,6], 8:[1,3], 9:[2,4], 0:[4,6]} #dp = [[set() for _ in range(N)] for _ in range(10)] res = set() def dfs(i, n, path): path.append(i) if n==N: res.add(''.join([str(p) for p in path])) return for j in moves[i]: dfs(j, n+1, path) path.pop() for i in range(10): dfs(i, 1, []) return len(res) def knightDialerDP(self, N): """ :type N: int :rtype: int Can you perform a breadth-first traversal instead, where you start at the top and “visit” function calls for N-1 hops only after you’ve visited those for N hops? Sadly, no. The values of function calls with nonzero hops absolutely require the values from smaller hop counts, so you won’t get any results until you reach the zero-hop layer and start returning numbers rather than additional function calls (note the zero-hop layer isn’t depicted here). You can however, reverse the order: visit layers with N hops only after you’ve visited layers with N-1 hops. Those of you who studied or are studying discrete mathematics will recognize all the necessary ingredients for an induction: we know that the values of zero-hop function calls are always one (the base case). We also know how to combine N-1 hop values to get N hop values, using the recurrence relation (the inductive step). We can start with a base case of zero hops and induce all values greater than zero. """ moves={1:[8,6], 2:[7, 9], 3:[4,8], 4:[0,3,9], 5:[], 6:[0,1,7], 7:[2,6], 8:[1,3], 9:[2,4], 0:[4,6]} MOD = 10**9 + 7 # base case: N=1, 1 hop should generate 1 number for each dial prior_case = [1] * 10 current_case = [0] * 10 current_num_hops = 1 while current_num_hops <= N-1: current_case = [0] * 10 current_num_hops += 1 # induction: we know the number of generated numbers for n-1 hops T_i(n-1) # the the number of generated numbers for n hops T_i(n) = sum(T_i_p(n-1)) # over all neighbors p of digit i for position in range(0, 10): for neighbor in moves[position]: current_case[position] += prior_case[neighbor] current_case[position] %= MOD prior_case = current_case return sum(prior_case) % MOD if __name__ == "__main__": N = 10 print(Solution().knightDialer(N)) print(Solution().knightDialerDP(N))
''' -Hard- *KMP* You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may replace any number of oldi characters of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] Output: true Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. Now sub = "l3e7" is a substring of s, so we return true. Example 2: Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] Output: false Explanation: The string "f00l" is not a substring of s and no replacements can be made. Note that we cannot replace '0' with 'o'. Example 3: Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] Output: true Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. Now sub = "l33tb" is a substring of s, so we return true. Constraints: 1 <= sub.length <= s.length <= 5000 0 <= mappings.length <= 1000 mappings[i].length == 2 oldi != newi s and sub consist of uppercase and lowercase English letters and digits. oldi and newi are either uppercase or lowercase English letters or digits. ''' from typing import List class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: table = [[False]*128 for _ in range(128)] for x in mappings: table[ord(x[0])][ord(x[1])] = True def match(s, t): return s == t or table[ord(t)][ord(s)] def strStr(haystack, needle): if not needle: return 0 if not haystack: return -1 if len(needle) > len(haystack): return -1 m, n = len(needle), len(haystack) def partialMatchTable(P): pt = [0]*m k = 0 for q in range(1,m): # start matching at index 1, no need to match itself while k > 0 and not match(P[k], P[q]): k = pt[k-1] # note the difference from CLRS text which has k = pt[k] if match(P[k], P[q]): k += 1 pt[q] = k return pt suffix = partialMatchTable(needle) j = 0 for i in range(n): while j > 0 and not match(haystack[i], needle[j]): j = suffix[j-1] # note the difference from CLRS text which has k = pt[k] if match(haystack[i], needle[j]): j += 1 if j == m: return i-m+1 # note the difference from CLRS text which has i-m return -1 return strStr(s, sub) != -1 if __name__ == "__main__": print(Solution().matchReplacement(s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]))
''' -Medium- 描述 It's follow up problem for Binary Tree Longest Consecutive Sequence II Given a k-ary tree, find the length of the longest consecutive sequence path. The path could be start and end at any node in the tree 样例 Example 1: Input: 5<6<7<>,5<>,8<>>,4<3<>,5<>,31<>>> Output: 5 Explanation: 5 / \ 6 4 /|\ /|\ 7 5 8 3 5 31 return 5, // 3-4-5-6-7 Example 2: Input: 1<> Output: 1 ''' """ Definition for a multi tree node. class MultiTreeNode(object): def __init__(self, x): self.val = x children = [] # children is a list of MultiTreeNode """ class ResultType: def __init__(self, globalMax, maxUp, maxDown): self.globalMax = globalMax self.maxUp = maxUp self.maxDown = maxDown class Solution: # @param {MultiTreeNode} root the root of k-ary tree # @return {int} the length of the longest consecutive sequence path def longestConsecutive3(self, root): # Write your code here return self.helper(root).globalMax def helper(self, root): if not root: return ResultType(0, 0, 0) maxUp = 0 maxDown = 0 mx = -float('inf') for child in root.children: if not child: continue childResult = self.helper(child) if child.val + 1 == root.val: maxDown = max(maxDown, childResult.maxDown + 1) if child.val - 1 == root.val: maxUp = max(maxUp, childResult.maxUp + 1) mx = max(mx, childResult.globalMax, maxUp + maxDown + 1) return ResultType(mx, maxUp, maxDown)
''' -Medium- Given a string s, determine if it is valid. A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times: Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty. Return true if s is a valid string, otherwise, return false. Example 1: Input: s = "aabcbc" Output: true Explanation: "" -> "abc" -> "aabcbc" Thus, "aabcbc" is valid. Example 2: Input: s = "abcabcababcc" Output: true Explanation: "" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc" Thus, "abcabcababcc" is valid. Example 3: Input: s = "abccba" Output: false Explanation: It is impossible to get "abccba" using the operation. Example 4: Input: s = "cababc" Output: false Explanation: It is impossible to get "cababc" using the operation. Constraints: 1 <= s.length <= 2 * 10^4 s consists of letters 'a', 'b', and 'c' ''' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ S = list(s) r = 'abc' while S: i = 0 for j in range(len(S)): S[i] = S[j] i += 1 if i > 2 and S[i-3] == r[0] and S[i-2] == r[1] and S[i-1] == r[2]: i -= 3 if i == len(S): return False S = S[:i] return True if __name__ == "__main__": print(Solution().isValid("aabcbc"))
''' -Medium- In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0). Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot. The value of |x| is defined as: x if x >= 0 -x if x < 0 Example 1: Input: neededApples = 1 Output: 8 Explanation: A square plot of side length 1 does not contain any apples. However, a square plot of side length 2 has 12 apples inside (as depicted in the image above). The perimeter is 2 * 4 = 8. Example 2: Input: neededApples = 13 Output: 16 Example 3: Input: neededApples = 1000000000 Output: 5040 Constraints: 1 <= neededApples <= 10^15 ''' class Solution: def minimumPerimeter(self, neededApples: int) -> int: side = 1 apples = 12 while True: if apples >= neededApples: return 8*side side += 1 a, b = side, 2*side apples += 4 * (b+a) * (b-a) if __name__ == "__main__": print(Solution().minimumPerimeter(13)) print(Solution().minimumPerimeter(1000000000))
''' Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 <= s.length <= 104 s consists of lowercase English letters. *Greedy* ''' from collections import defaultdict class Solution(object): def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ m = defaultdict(int) for c in s: m[c] += 1 visited = [False]*26 res = '0' for c in s: m[c] -= 1 if visited[ord(c)-ord('a')]: continue while c < res[-1] and m[res[-1]] > 0: visited[ord(res[-1])-ord('a')] = False res = res[:-1] res += c visited[ord(c)-ord('a')] = True return res[1:] if __name__ == "__main__": print(Solution().removeDuplicateLetters("bcabc")) print(Solution().removeDuplicateLetters("cbacdcbc"))
''' -Medium- Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA). Each node will have a reference to its parent node. The definition for Node is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)." Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1,2], p = 1, q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q exist in the tree. ''' # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None class Solution(object): def lowestCommonAncestor(self, p, q): """ :type node: Node :rtype: Node """ possibleparent = None ptree = set() temp = p while p: ptree.add(p) p = p.parent qtree = set() p = temp while q: qtree.add(q) if p in qtree: return p if q in ptree: return q possibleParent = q q = q.parent return possibleParent def lowestCommonAncestorFaster(self, p, q): """ :type node: Node :rtype: Node """ a, b = p, q while a != b: a = q if not a else a.parent b = p if not b else b.parent; return a