sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
7247df
173c4b
The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1. For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different. You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive). Return an array ans where ans[i] is the answer to the ith query. A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as: x if x >= 0. -x if x < 0.   Example 1: Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]] Output: [2,1,4,1] Explanation: The queries are processed as follows: - queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2. - queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1. - queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4. - queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1. Example 2: Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]] Output: [-1,1,1,3] Explanation: The queries are processed as follows: - queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the elements are the same. - queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1. - queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1. - queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.   Constraints: 2 <= nums.length <= 100000 1 <= nums[i] <= 100 1 <= queries.length <= 2 * 10000 0 <= li < ri < nums.length
class Solution(object): def minDifference(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: List[int] """ count = [[0] * 101 for _ in range(len(nums))] for i in range(len(nums)): if i > 0: for j in range(1, 101): count[i][j] = count[i - 1][j] count[i][nums[i]] += 1 ans = [None] * len(queries) for i in range(len(queries)): p = None ans[i] = 10000 for j in range(1, 101): if count[queries[i][1]][j] > (count[queries[i][0] - 1][j] if queries[i][0] > 0 else 0): if p == None: p = j else: ans[i] = min(ans[i], j - p) p = j if ans[i] > 105: ans[i] = -1 return ans
f7d165
aa3ce9
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 <= 100000
class Solution: def maximumDetonation(self, bombs: List[List[int]]) -> int: n = len(bombs) data = [[] for _ in range(n)] for i in range(n): for j in range(n): if i == j: continue if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2: data[i].append(j) val = 0 for i in range(n): vis = {i} q = [i] h = 0 while h < len(q): for j in data[q[h]]: if j not in vis: vis.add(j) q.append(j) h += 1 if len(q) > val: val = len(q) res = i return val
d4d692
aa3ce9
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 <= 100000
class Solution(object): def maximumDetonation(self, A): n = len(A) G = [[] for i in xrange(n)] for i in xrange(n): for j in xrange(i+1, n): x1,y1,r1 = A[i] x2,y2,r2 = A[j] if (x1-x2)**2 + (y1-y2)**2 <= r1 ** 2: G[i].append(j) if (x1-x2)**2 + (y1-y2)**2 <= r2 ** 2: G[j].append(i) def test(i): bfs = [i] seen = {i} for i in bfs: for j in G[i]: if j in seen: continue bfs.append(j) seen.add(j) return len(bfs) return max(map(test, range(n)))
18bc28
831c18
The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.   Example 1: Input: nums = [1,3,1], k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0. Example 2: Input: nums = [1,1,1], k = 2 Output: 0 Example 3: Input: nums = [1,6,1], k = 3 Output: 5   Constraints: n == nums.length 2 <= n <= 10000 0 <= nums[i] <= 1000000 1 <= k <= n * (n - 1) / 2
from bisect import bisect class Solution: def smallestDistancePair(self, arr, k): """ :type nums: List[int] :type k: int :rtype: int """ n = len(arr) arr.sort() def countpairs(arr,diff,n): res = 0 for i in range(n): pos = bisect(arr,arr[i]+diff) res += (pos-i-1) return res maxd = arr[n-1]-arr[0] mind = maxd for i in range(n-1): mind = min(mind,arr[i+1]-arr[i]) while mind<maxd: mid = (mind+maxd)>>1 count = countpairs(arr,mid,n) if count<k: mind = mid + 1 else: maxd = mid return(mind)
a34ecd
831c18
The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.   Example 1: Input: nums = [1,3,1], k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0. Example 2: Input: nums = [1,1,1], k = 2 Output: 0 Example 3: Input: nums = [1,6,1], k = 3 Output: 5   Constraints: n == nums.length 2 <= n <= 10000 0 <= nums[i] <= 1000000 1 <= k <= n * (n - 1) / 2
class Solution(object): def smallestDistancePair(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() lnum = len(nums) def bsCount(base, limit): l = base r = lnum-1 while l<=r: m = (l+r)/2 if nums[m] - nums[base] <= limit: l = m + 1 else: r = m - 1 ans = base if base<=l<lnum and nums[l] - nums[base] <= limit and ans<l: ans = l if base<=r<lnum and nums[r] - nums[base] <= limit and ans<r: ans = r if base<=m<lnum and nums[m] - nums[base] <= limit and ans<m: ans = m return ans - base l = 0 r = nums[-1]-nums[0] while l <= r: m = (l+r)/2 count = 0 for base in range(lnum): count += bsCount(base, m) if count > k: break # if count == k: # return m if count >= k: r = m - 1 else: l = m + 1 return l
7bdfcd
c89d0b
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it. For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7]. Return the minimum number of operations to make an array that is sorted in non-decreasing order.   Example 1: Input: nums = [3,9,3] Output: 2 Explanation: Here are the steps to sort the array in non-decreasing order: - From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3] - From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3] There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2. Example 2: Input: nums = [1,2,3,4,5] Output: 0 Explanation: The array is already in non-decreasing order. Therefore, we return 0.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution: def minimumReplacement(self, nums: List[int]) -> int: res = 0 n = len(nums) x = nums[n-1] for i in range(n-2, -1, -1): if nums[i] <= x: x = nums[i] else: m = (nums[i]+x-1)//x res += m-1 x = nums[i]//m return res
d3e901
c89d0b
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it. For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7]. Return the minimum number of operations to make an array that is sorted in non-decreasing order.   Example 1: Input: nums = [3,9,3] Output: 2 Explanation: Here are the steps to sort the array in non-decreasing order: - From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3] - From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3] There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2. Example 2: Input: nums = [1,2,3,4,5] Output: 0 Explanation: The array is already in non-decreasing order. Therefore, we return 0.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 10^9
class Solution(object): def minimumReplacement(self, nums): """ :type nums: List[int] :rtype: int """ def split(num,maximum): tot = (num-1)//maximum + 1 return [num//tot,tot] n = len(nums) maximum = nums[-1] ans = -n+1 for i in range(n-2,-1,-1): curr,sub = split(nums[i],maximum) # print(curr,sub,maximum) maximum = min(maximum,curr) ans += sub return ans
004fc9
f326e7
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval.   Example 1: Input: hours = [9,9,6,0,6,6,9] Output: 3 Explanation: The longest well-performing interval is [9,9,6]. Example 2: Input: hours = [6,6,6] Output: 0   Constraints: 1 <= hours.length <= 10000 0 <= hours[i] <= 16
class Solution: def longestWPI(self, hours: List[int]) -> int: hours = [1 if h > 8 else -1 for h in hours] s = 0 ans = 0 memo = {0 : -1} for i, v in enumerate(hours): s += v if s > 0: ans = i + 1 if s not in memo: memo[s] = i if (s - 1) in memo: ans = max(ans, i - memo[s - 1]) return ans
bc8da2
f326e7
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval.   Example 1: Input: hours = [9,9,6,0,6,6,9] Output: 3 Explanation: The longest well-performing interval is [9,9,6]. Example 2: Input: hours = [6,6,6] Output: 0   Constraints: 1 <= hours.length <= 10000 0 <= hours[i] <= 16
class Solution(object): def longestWPI(self, hours): """ :type hours: List[int] :rtype: int """ r = s = 0 b = {} for i, v in enumerate(hours): s += 1 if v > 8 else -1 if s < 0 and s not in b: b[s] = i if s > 0: r = max(r, i+1) else: r = max(r, i - b.get(s-1, float('inf'))) return r
1fb84e
486c37
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 * 10^9
special = set() for sz in range(1, 9): for choice in permutations('0123456789', sz): s = int("".join(choice)) special.add(s) for choice in permutations('0123456789', 9): s = int("".join(choice)) special.add(s) for choice in permutations('023456789', 9): s = int('1' + "".join(choice)) special.add(s) special = sorted(special) class Solution: def countSpecialNumbers(self, n: int) -> int: return bisect.bisect(special, n) - 1
9640fd
486c37
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 * 10^9
class Solution(object): def countSpecialNumbers(self, n): """ :type n: int :rtype: int """ def c(n, m): r = 1 for i in range(n): r, m = r * m, m - 1 return r def e(i, v, j): if i == len(str(n)): return 1 elif not j: return c(len(str(n)) - i, 10 - i) r = 0 for k in range(0 if i > 0 else 1, ord(str(n)[i]) - ord('0') + 1): if not v[k]: v[k] = True r, v[k] = r + e(i + 1, v, k == ord(str(n)[i]) - ord('0')), False return r r = 0 for i in range(0, len(str(n)) - 1): r += 9 * c(i, 9) r += e(0, [False] * 10, True) return r
8dcd24
be02cd
You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes. You are also given an integer cars representing the total number of cars waiting in the garage to be repaired. Return the minimum time taken to repair all the cars. Note: All the mechanics can repair the cars simultaneously.   Example 1: Input: ranks = [4,2,3,1], cars = 10 Output: 16 Explanation: - The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes. - The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes. - The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes. - The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​ Example 2: Input: ranks = [5,1,8], cars = 6 Output: 16 Explanation: - The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes. - The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. - The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​   Constraints: 1 <= ranks.length <= 100000 1 <= ranks[i] <= 100 1 <= cars <= 1000000
class Solution: def repairCars(self, fuck: List[int], cars: int) -> int: low, high = 0, 10**15 def solve(m): rem = cars for i in range(len(fuck)): x = m // fuck[i] x = int(math.sqrt(x)) rem -= x if (rem <= 0): break return rem while(low <= high): mid = (low + high) // 2 if(solve(mid) <= 0): ans = mid high = mid - 1 else: low = mid + 1 return low
06b465
be02cd
You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes. You are also given an integer cars representing the total number of cars waiting in the garage to be repaired. Return the minimum time taken to repair all the cars. Note: All the mechanics can repair the cars simultaneously.   Example 1: Input: ranks = [4,2,3,1], cars = 10 Output: 16 Explanation: - The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes. - The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes. - The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes. - The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​ Example 2: Input: ranks = [5,1,8], cars = 6 Output: 16 Explanation: - The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes. - The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes. - The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes. It can be proved that the cars cannot be repaired in less than 16 minutes.​​​​​   Constraints: 1 <= ranks.length <= 100000 1 <= ranks[i] <= 100 1 <= cars <= 1000000
class Solution(object): def repairCars(self, ranks, cars): """ :type ranks: List[int] :type cars: int :rtype: int """ l = 1 r = min(ranks)*cars*cars while l < r: time = (l+r) // 2 repair = 0 for rank in ranks: repair += int((time/rank)**(0.5)) if repair >= cars: r = time else: l = time+1 return r
8932f8
536245
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.   Example 1: Input: pairs = [[5,1],[4,5],[11,9],[9,4]] Output: [[11,9],[9,4],[4,5],[5,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3 Example 2: Input: pairs = [[1,3],[3,2],[2,1]] Output: [[1,3],[3,2],[2,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid. Example 3: Input: pairs = [[1,2],[1,3],[2,1]] Output: [[1,2],[2,1],[1,3]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 2 == 2 = start1 end1 = 1 == 1 = start2   Constraints: 1 <= pairs.length <= 100000 pairs[i].length == 2 0 <= starti, endi <= 10^9 starti != endi No two pairs are exactly the same. There exists a valid arrangement of pairs.
from collections import defaultdict class Solution(object): def validArrangement(self, pairs): """ :type pairs: List[List[int]] :rtype: List[List[int]] """ deg = defaultdict(int) adj = defaultdict(list) for u, v in pairs: adj[u].append(v) deg[u] += 1 deg[v] -= 1 _, src = max((v, k) for k, v in deg.iteritems()) ans = [] def _f(u): while adj[u]: v = adj[u].pop() _f(v) ans.append(u) _f(src) n = len(ans) return [[ans[n-i-1], ans[n-i-2]] for i in xrange(n-1)]
361c3a
536245
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.   Example 1: Input: pairs = [[5,1],[4,5],[11,9],[9,4]] Output: [[11,9],[9,4],[4,5],[5,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3 Example 2: Input: pairs = [[1,3],[3,2],[2,1]] Output: [[1,3],[3,2],[2,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid. Example 3: Input: pairs = [[1,2],[1,3],[2,1]] Output: [[1,2],[2,1],[1,3]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 2 == 2 = start1 end1 = 1 == 1 = start2   Constraints: 1 <= pairs.length <= 100000 pairs[i].length == 2 0 <= starti, endi <= 10^9 starti != endi No two pairs are exactly the same. There exists a valid arrangement of pairs.
class Solution: def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]: d = defaultdict(list) ins = defaultdict(int) # visited = set() for s, e in pairs: # visited.add(s) # visited.add(e) ins[s] += 1 ins[e] -= 1 d[s].append(e) queue = deque() def dfs(i): while d[i]: dfs(d[i].pop()) queue.appendleft(i) pins = [] for k, v in ins.items(): if v == 1: pins.append(k) if not pins: # dfs(list(visited)[0]) dfs(pairs[0][0]) else: dfs(pins[0]) res = [] for i in range(1, len(queue)): res.append([queue[i - 1], queue[i]]) return res
64bb31
cf1e94
Given a binary tree root and a linked list with head as the first node.  Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards.   Example 1: Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Explanation: Nodes in blue form a subpath in the binary Tree. Example 2: Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Example 3: Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: false Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.   Constraints: The number of nodes in the tree will be in the range [1, 2500]. The number of nodes in the list will be in the range [1, 100]. 1 <= Node.val <= 100 for each node in the linked list and binary tree.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubPath(self, head: ListNode, root: TreeNode, started=False) -> bool: if head is None: return True if root is None: return False if head.val != root.val: if started: return False return self.isSubPath(head, root.left, False) or self.isSubPath(head, root.right, False) if started: return self.isSubPath(head.next, root.left, True) or self.isSubPath(head.next, root.right, True) return self.isSubPath(head.next, root.left, True) or self.isSubPath(head.next, root.right, True) or self.isSubPath(head, root.left, False) or self.isSubPath(head, root.right, False)
7d731c
cf1e94
Given a binary tree root and a linked list with head as the first node.  Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards.   Example 1: Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Explanation: Nodes in blue form a subpath in the binary Tree. Example 2: Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Example 3: Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: false Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.   Constraints: The number of nodes in the tree will be in the range [1, 2500]. The number of nodes in the list will be in the range [1, 100]. 1 <= Node.val <= 100 for each node in the linked list and binary tree.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # 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 isSubPath(self, head, root): """ :type head: ListNode :type root: TreeNode :rtype: bool """ a = [] t = head while t is not None: a.append(t.val) t =t.next def work(h, now): if h is None: return False tmp = now + [h.val] if len(tmp) >= len(a): F = True for i in range(len(a)): if tmp[len(tmp) - i - 1] != a[len(a) - i - 1]: F = False break if F: return True if work(h.left, tmp): return True if work(h.right, tmp): return True return False return work(root, [])
dd01b1
c50b0d
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day). For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies: Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000] Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000] Every day (86400-second chunks): [10,10000] Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: TweetCounts() Initializes the TweetCounts object. void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds). List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq. freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.   Example: Input ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] [[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] Output [null,null,null,null,[2],[2,1],null,[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0 tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60 tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10 tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120 tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets   Constraints: 0 <= time, startTime, endTime <= 10^9 0 <= endTime - startTime <= 10000 There will be at most 10000 calls in total to recordTweet and getTweetCountsPerFrequency.
class TweetCounts(object): def __init__(self): self.a = collections.defaultdict(list) def recordTweet(self, name, time): self.a[name].append(time) """ :type tweetName: str :type time: int :rtype: None """ def getTweetCountsPerFrequency(self, freq, name, startTime, endTime): """ :type freq: str :type tweetName: str :type startTime: int :type endTime: int :rtype: List[int] """ row = self.a[name] row.sort() i = bisect.bisect_left(row, startTime) i -= 2 if i <0: i = 0 if freq == 'minute': fv = 60 elif freq == 'hour': fv = 60 * 60 else: fv = 24 * 60 * 60 Q, _ = divmod(endTime - startTime, fv) Q += 1 ans = [0] * Q for i in xrange(i, len(row)): t = row[i] if t > endTime: break if t >= startTime: d = t - startTime q, r = divmod(d, fv) ans[q] += 1 return ans # Your TweetCounts object will be instantiated and called as such: # obj = TweetCounts() # obj.recordTweet(tweetName,time) # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
ff1660
c50b0d
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day). For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies: Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000] Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000] Every day (86400-second chunks): [10,10000] Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: TweetCounts() Initializes the TweetCounts object. void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds). List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq. freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.   Example: Input ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] [[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] Output [null,null,null,null,[2],[2,1],null,[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0 tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60 tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10 tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120 tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets   Constraints: 0 <= time, startTime, endTime <= 10^9 0 <= endTime - startTime <= 10000 There will be at most 10000 calls in total to recordTweet and getTweetCountsPerFrequency.
class TweetCounts: def __init__(self): self.timestampdict = {} self.lengthoftimedict = {"minute":60, "hour":3600,"day":86400} def recordTweet(self, tweetName: str, time: int) -> None: self.timestampdict[tweetName] = self.timestampdict.get(tweetName,[])+[time] def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: final = [0 for n in range(1+((endTime-startTime)//self.lengthoftimedict[freq]))] for time in self.timestampdict[tweetName]: if time>=startTime and time <= endTime: final[(time-startTime)//self.lengthoftimedict[freq]]+=1 return final # Your TweetCounts object will be instantiated and called as such: # obj = TweetCounts() # obj.recordTweet(tweetName,time) # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
85dfe8
f3fb53
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words.   Example 1: Input: words = ["alex","loves","leetcode"] Output: "alexlovesleetcode" Explanation: All permutations of "alex","loves","leetcode" would also be accepted. Example 2: Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"] Output: "gctaagttcatgcatc"   Constraints: 1 <= words.length <= 12 1 <= words[i].length <= 20 words[i] consists of lowercase English letters. All the strings of words are unique.
class Solution(object): def shortestSuperstring(self, A): """ :type A: List[str] :rtype: str """ def overlap(w1, w2): n1, n2 = len(w1), len(w2) ans = 0 s = '' for i in range(1, min(n1, n2) + 1): if w1[-i:] == w2[:i]: if ans < i: ans = i s = w1 + w2[i:] for i in range(1, min(n1, n2) + 1): if w2[-i:] == w1[:i]: if ans < i: ans = i s = w2 + w1[i:] return (ans, s) if ans > 0 else (ans, w1 + w2) A = set(A) while len(A) != 1: l, s = float('-inf'), None x, y = None, None # print(A) for a, b in itertools.combinations(A, 2): # print(a, b) l_temp, s_temp = overlap(a, b) if l_temp > l: l = l_temp s = s_temp x, y = a, b # print(a, b, s) A.remove(x) A.remove(y) A.add(s) # print(s) return A.pop()
23e46c
f3fb53
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words.   Example 1: Input: words = ["alex","loves","leetcode"] Output: "alexlovesleetcode" Explanation: All permutations of "alex","loves","leetcode" would also be accepted. Example 2: Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"] Output: "gctaagttcatgcatc"   Constraints: 1 <= words.length <= 12 1 <= words[i].length <= 20 words[i] consists of lowercase English letters. All the strings of words are unique.
from functools import lru_cache class Solution: def shortestSuperstring(self, A): """ :type A: List[str] :rtype: str """ A.sort(key=len) B = [] for s in A: if not any(s in s1 for s1 in B): B.append(s) @lru_cache(None) def overlap(s1, s2): return max((i for i in range(1, len(s2)) if s2[:i] == s1[-i:]), default=0) @lru_cache(None) def get(to_use, first): if to_use == 1 << first: return A[first] best = ''.join(A) for l1 in range(len(A)): if (to_use & (1 << l1)) and l1 != first: r = get(to_use ^ (1 << first), l1) r = A[first][:len(A[first]) - overlap(A[first], A[l1])] + r if len(r) < len(best): best = r return best return min((get((1 << len(A)) - 1, i) for i in range(len(A))), key=len)
aadd9e
b7b99c
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.   Example 1: Input: nums = [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. Example 2: Input: nums = [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.   Constraints: 1 <= nums.length <= 100000 nums[i] is either 0 or 1.
class Solution(object): def findMaxLength(self, nums): if not nums: return 0 d = {0: -1} counter = 0 ans = 0 for i, num in enumerate(nums): if num == 0: counter -= 1; else: counter += 1 if counter in d: ans = max(ans, i - d[counter]) d[counter] = min(d.get(counter, i), i) return ans def brute_force(nums): n = len(nums) ans = 0 for i in xrange(n): for j in xrange(i + 1, n): sl = nums[i: j + 1] if sl.count(0) == sl.count(1): ans = max(ans, j - i + 1) return ans S = Solution() assert(S.findMaxLength([1, 0, 1, 1, 1, 1, 0, 0, 0, 1]) == 8) assert(S.findMaxLength([0,1]) == 2) assert(S.findMaxLength([0,1,0]) == 2) assert(S.findMaxLength([0,1,0,1]) == 4) assert(brute_force([1, 0, 1, 1, 1, 1, 0, 0, 0, 1]) == 8) assert(S.findMaxLength([1, 0, 1, 1, 1, 1, 0, 0, 0, 1]) == 8) assert(brute_force([0,1,0,1]) == 4) import random for i in xrange(100): nums = [random.choice([0, 1]) for i in xrange(10)] assert(S.findMaxLength(nums) == brute_force(nums))
69d2b1
1f9d75
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.   Example 1: Input: nums = [4,6,15,35] Output: 4 Example 2: Input: nums = [20,50,9,63] Output: 2 Example 3: Input: nums = [2,3,6,7,4,12,21,39] Output: 8   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] <= 100000 All the values of nums are unique.
class UF(object): def __init__(self, nodes): self.idx = {v:i for i,v in enumerate(nodes)} self.parent = range(len(nodes)) self.rank = [0] * len(nodes) self.size = [1] * len(nodes) def union(self, node1, node2): i1, i2 = self._find(self.idx[node1]), self._find(self.idx[node2]) if i1 == i2: return if self.rank[i1] < self.rank[i2]: i1, i2 = i2, i1 # self.rank[i1] >= self.rank[i2] self.parent[i2] = i1 self.size[i1] += self.size[i2] if self.rank[i1] == self.rank[i2]: self.rank[i1] += 1 def groupsize(self, node): return self.size[self.idx[node]] def _find(self, i): path = [] while self.parent[i] != i: path.append(i) i = self.parent[i] for j in path: self.parent[j] = i return i class Solution(object): def largestComponentSize(self, A): """ :type A: List[int] :rtype: int """ m = max(A) primes = [2] def is_prime(x): for p in primes: if p * p > x: return True if x % p == 0: return False for x in xrange(3, m+1, 2): if is_prime(x): primes.append(x) if x * x > m: break def prime_factors(x): r = [] for p in primes: if p * p > x: break if x % p == 0: r.append(p) while x % p == 0: x //= p if x > 1: r.append(x) return r d = {} uf = UF(A) for v in A: for p in prime_factors(v): d.setdefault(p, []).append(v) for vv in d.itervalues(): for i in xrange(len(vv)-1): uf.union(vv[i], vv[i+1]) return max(uf.groupsize(node) for node in A)
825503
1f9d75
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.   Example 1: Input: nums = [4,6,15,35] Output: 4 Example 2: Input: nums = [20,50,9,63] Output: 2 Example 3: Input: nums = [2,3,6,7,4,12,21,39] Output: 8   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i] <= 100000 All the values of nums are unique.
class Solution: def largestComponentSize(self, A): """ :type A: List[int] :rtype: int """ A.sort() mx = max(A) DSU = [i for i in range(mx + 1)] #b = set(A) b = [False] * (mx + 1) for a in A: b[a] = True def find(x): if DSU[x] != x: DSU[x] = find(DSU[x]) return DSU[x] def union(x, y): DSU[find(x)] = find(y) l = [] cc = [False] * (mx + 1) for x in range(2, mx): if cc[x]: continue l.clear() n = x while n <= mx: cc[n] = True if b[n]: #if n in b: l.append(n) n += x if len(l) > 1: t = find(l[0]) for j in range(1, len(l)): DSU[find(l[j])] = t c = collections.defaultdict(int) for a in A: c[find(a)] += 1 return max(c.values())
93c2b1
97b836
You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of arr at index i to x. You may repeat this procedure as many times as needed. Return true if it is possible to construct the target array from arr, otherwise, return false.   Example 1: Input: target = [9,3,5] Output: true Explanation: Start with arr = [1, 1, 1] [1, 1, 1], sum = 3 choose index 1 [1, 3, 1], sum = 5 choose index 2 [1, 3, 5], sum = 9 choose index 0 [9, 3, 5] Done Example 2: Input: target = [1,1,1,2] Output: false Explanation: Impossible to create target array from [1,1,1,1]. Example 3: Input: target = [8,5] Output: true   Constraints: n == target.length 1 <= n <= 5 * 10000 1 <= target[i] <= 10^9
class Solution(object): def isPossible(self, A): N = len(A) S = sum(A) A = [-x for x in A] heapq.heapify(A) while S != N: x = -heapq.heappop(A) rem = S - x y = S - 2 * rem if y <= 0: return False heapq.heappush(A, -y) S = rem + y return True
ccc31f
97b836
You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of arr at index i to x. You may repeat this procedure as many times as needed. Return true if it is possible to construct the target array from arr, otherwise, return false.   Example 1: Input: target = [9,3,5] Output: true Explanation: Start with arr = [1, 1, 1] [1, 1, 1], sum = 3 choose index 1 [1, 3, 1], sum = 5 choose index 2 [1, 3, 5], sum = 9 choose index 0 [9, 3, 5] Done Example 2: Input: target = [1,1,1,2] Output: false Explanation: Impossible to create target array from [1,1,1,1]. Example 3: Input: target = [8,5] Output: true   Constraints: n == target.length 1 <= n <= 5 * 10000 1 <= target[i] <= 10^9
class Solution: def isPossible(self, target: List[int]) -> bool: a = [-i for i in target] heapq.heapify(a) s = sum(a) n = len(a) while True: ai = heapq.heappop(a) if ai == -1: return True if s > ai - n + 1 or 2 * ai - s >= 0: return False heapq.heappush(a, 2 * ai - s) s = ai
377bda
48225f
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward.   Example 1: Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created. Example 2: Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created. Example 3: Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".   Constraints: 1 <= words.length <= 100000 words[i].length == 2 words[i] consists of lowercase English letters.
from collections import defaultdict class Solution: def longestPalindrome(self, words: List[str]) -> int: d = defaultdict(int) for w in words: d[w] += 1 ret = 0 odd = False for w in list(d): r = w[::-1] if w == r: x = d[w] // 2 else: x = min(d[w], d[r]) d[w] -= x d[r] -= x ret += len(w) * x * 2 if w == r and d[w] and not odd: odd = True ret += 2 return ret
c6fd2d
48225f
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward.   Example 1: Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created. Example 2: Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created. Example 3: Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".   Constraints: 1 <= words.length <= 100000 words[i].length == 2 words[i] consists of lowercase English letters.
class Solution(object): def longestPalindrome(self, w): """ :type words: List[str] :rtype: int """ ans = 0 mid = 0 ok = 0 sz = [0]*26 now = defaultdict(int) for v in w: if v[0] == v[1]: sz[ord(v[0])-97] += 1 continue rev = str(v[1]+v[0]) if now[rev] > 0: now[rev] -= 1 ans += 4 else: now[v] += 1 for v in sz: if v & 1: if not ok: ok = 1 ans += 2 * v else: ans += 2 * (v - 1) else: ans += 2 * v return ans
caeaa2
d1e4e7
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].   Example 1: Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. Example 2: Input: left = "1", right = "2" Output: 1   Constraints: 1 <= left.length, right.length <= 18 left and right consist of only digits. left and right cannot have leading zeros. left and right represent integers in the range [1, 10^18 - 1]. left is less than or equal to right.
from math import sqrt class Solution: def superpalindromesInRange(self, L, R): """ :type L: str :type R: str :rtype: int """ l = int(L) r = int(R) l_below = int(sqrt(l) + 0.9) r_upper = int(sqrt(r)) l_s = str(l_below) l_p = min(10 ** (len(l_s) // 2), int(l_s[:(len(l_s) + 1) // 2])) r_s = str(r_upper) r_p = max(int(r_s[:(len(r_s) + 1) // 2]), 10 ** (len(r_s) // 2)) count = 0 print(l_p, r_p) for i in range(l_p, r_p + 1): i_s = str(i) i2 = int(i_s + i_s[-2::-1]) #print('try', i2) v = i2 * i2 if l <= v <= r: #print('check',v,'=',i2,'**2') v_s = str(v) if v_s == v_s[::-1]: count += 1 i3 = int(i_s + i_s[::-1]) #print('try', i3) v = i3 * i3 if l <= v <= r: v_s = str(v) #print('check',v,'=',i3,'**2') if v_s == v_s[::-1]: count += 1 return count
3f897a
d1e4e7
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].   Example 1: Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. Example 2: Input: left = "1", right = "2" Output: 1   Constraints: 1 <= left.length, right.length <= 18 left and right consist of only digits. left and right cannot have leading zeros. left and right represent integers in the range [1, 10^18 - 1]. left is less than or equal to right.
from itertools import count class Solution(object): def superpalindromesInRange(self, L, R): """ :type L: str :type R: str :rtype: int """ def isqrt(n): a, b = 0, n+1 # a**2 <= n < b**2 while a + 1 < b: c = (a + b) // 2 if c**2 <= n: a = c else: b = c return a def g(n): r, t = 0, 1 while n: r += n%3 * t t *= 10 n //= 3 return r def check(n): s = str(n) return s == s[::-1] and sum(int(c)**2 for c in s) < 10 def f(n): # n >= 0 n = isqrt(n) # count palindromes <= n with digit sum < 10 # aside from n = 3, there is only 0, 1, 2 r = 1 if n >= 3 else 0 for i in count(): j = g(i) if j > n: break if check(j): r += 1 return r return f(int(R)) - f(int(L)-1)
b29074
ca31bf
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5 Output: 4 Explanation: The following are all possible routes, each uses 5 units of fuel: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3 Example 2: Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6 Output: 5 Explanation: The following are all possible routes: 1 -> 0, used fuel = 1 1 -> 2 -> 0, used fuel = 5 1 -> 2 -> 1 -> 0, used fuel = 5 1 -> 0 -> 1 -> 0, used fuel = 3 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5 Example 3: Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3 Output: 0 Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.   Constraints: 2 <= locations.length <= 100 1 <= locations[i] <= 10^9 All integers in locations are distinct. 0 <= start, finish < locations.length 1 <= fuel <= 200
sys.setrecursionlimit(100000) class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: n = len(locations) @lru_cache(None) def dfs(pos, rest): # print(pos, rest) ans = 0 for i, loc in enumerate(locations): if pos != i: cost = abs(locations[pos] - loc) if cost <= rest: ans += dfs(i, rest - cost) if pos == finish: ans += 1 return ans % 1000000007 return dfs(start, fuel)
f0ddc7
ca31bf
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5 Output: 4 Explanation: The following are all possible routes, each uses 5 units of fuel: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3 Example 2: Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6 Output: 5 Explanation: The following are all possible routes: 1 -> 0, used fuel = 1 1 -> 2 -> 0, used fuel = 5 1 -> 2 -> 1 -> 0, used fuel = 5 1 -> 0 -> 1 -> 0, used fuel = 3 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5 Example 3: Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3 Output: 0 Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.   Constraints: 2 <= locations.length <= 100 1 <= locations[i] <= 10^9 All integers in locations are distinct. 0 <= start, finish < locations.length 1 <= fuel <= 200
class Solution(object): def countRoutes(self, locations, start, finish, fuel): """ :type locations: List[int] :type start: int :type finish: int :type fuel: int :rtype: int """ dp = {} n = len(locations) mod = 1000000007 def dfs(c, s): if c==0 and s==finish: return 1 k = (c, s) if k in dp: return dp[k] if s==finish: r=1 else: r=0 i = 0 while i<n: if i!=s: d = locations[i]-locations[s] if d<0: d=-d if c>=d: r += dfs(c-d, i) r %= mod i+=1 dp[k] = r return r return dfs(fuel, start)
b33d15
17b5e4
You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start. Each minute, a node becomes infected if: The node is currently uninfected. The node is adjacent to an infected node. Return the number of minutes needed for the entire tree to be infected.   Example 1: Input: root = [1,5,3,null,4,10,6,9,2], start = 3 Output: 4 Explanation: The following nodes are infected during: - Minute 0: Node 3 - Minute 1: Nodes 1, 10 and 6 - Minute 2: Node 5 - Minute 3: Node 4 - Minute 4: Nodes 9 and 2 It takes 4 minutes for the whole tree to be infected so we return 4. Example 2: Input: root = [1], start = 1 Output: 0 Explanation: At minute 0, the only node in the tree is infected so we return 0.   Constraints: The number of nodes in the tree is in the range [1, 100000]. 1 <= Node.val <= 100000 Each node has a unique value. A node with a value of start exists in the tree.
from collections import defaultdict # 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 amountOfTime(self, root: Optional[TreeNode], start: int) -> int: if not root: return 0 tree = defaultdict(list) stack = [root] while stack: node = stack.pop() if node.left is not None: tree[node.val].append(node.left.val) tree[node.left.val].append(node.val) stack.append(node.left) if node.right is not None: tree[node.val].append(node.right.val) tree[node.right.val].append(node.val) stack.append(node.right) visited = {start} queue = [start] depth = [0] for node, d in zip(queue, depth): for child in tree[node]: if child not in visited: visited.add(child) queue.append(child) depth.append(d + 1) return depth[-1]
59e5b1
17b5e4
You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start. Each minute, a node becomes infected if: The node is currently uninfected. The node is adjacent to an infected node. Return the number of minutes needed for the entire tree to be infected.   Example 1: Input: root = [1,5,3,null,4,10,6,9,2], start = 3 Output: 4 Explanation: The following nodes are infected during: - Minute 0: Node 3 - Minute 1: Nodes 1, 10 and 6 - Minute 2: Node 5 - Minute 3: Node 4 - Minute 4: Nodes 9 and 2 It takes 4 minutes for the whole tree to be infected so we return 4. Example 2: Input: root = [1], start = 1 Output: 0 Explanation: At minute 0, the only node in the tree is infected so we return 0.   Constraints: The number of nodes in the tree is in the range [1, 100000]. 1 <= Node.val <= 100000 Each node has a unique value. A node with a value of start exists in the tree.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def amountOfTime(self, root, start): """ :type root: Optional[TreeNode] :type start: int :rtype: int """ g, v = {}, set() def b(n): g[n.val] = [] if n.left: b(n.left) g[n.left.val].append(n.val) g[n.val].append(n.left.val) if n.right: b(n.right) g[n.right.val].append(n.val) g[n.val].append(n.right.val) def d(n): if n in v: return 0 v.add(n) r = 1 for c in g[n]: r = max(r, 1 + d(c)) return r b(root) return d(start) - 1
dc8b73
208790
You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square. 2 representing the ending square. There is exactly one ending square. 0 representing empty squares we can walk over. -1 representing obstacles that we cannot walk over. Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.   Example 1: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) Example 3: Input: grid = [[0,1],[2,0]] Output: 0 Explanation: There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 1 <= m * n <= 20 -1 <= grid[i][j] <= 2 There is exactly one starting cell and one ending cell.
class Solution: def uniquePathsIII(self, grid): """ :type grid: List[List[int]] :rtype: int """ def dfs(step, x, y): nonlocal ways if (x, y) == end: if step == nempty: ways += 1 return for k in range(4): nx, ny = x + dx[k], y + dy[k] if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == 0: grid[nx][ny] = 3 dfs(step + 1, nx, ny) grid[nx][ny] = 0 dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] ways = 0 n, m = len(grid), len(grid[0]) nempty = 1 for i in range(n): for j in range(m): if grid[i][j] == 1: start = (i, j) elif grid[i][j] == 0: nempty +=1 elif grid[i][j] == 2: end = (i, j) grid[i][j] = 0 dfs(0, *start) return ways
4c4223
208790
You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square. 2 representing the ending square. There is exactly one ending square. 0 representing empty squares we can walk over. -1 representing obstacles that we cannot walk over. Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.   Example 1: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) Example 3: Input: grid = [[0,1],[2,0]] Output: 0 Explanation: There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 1 <= m * n <= 20 -1 <= grid[i][j] <= 2 There is exactly one starting cell and one ending cell.
class Solution(object): def uniquePathsIII(self, grid): """ :type grid: List[List[int]] :rtype: int """ n, m = len(grid), len(grid[0]) start = end = bad = good = s = 0 for i, row in enumerate(grid): for j, v in enumerate(row): x = m*i + j if v < 0: bad |= 1<<x else: good |= 1<<x; s += 1 if v == 1: start = x elif v == 2: end = x def neighbors(i, j): if i > 0: yield m*(i-1) + j if i < n-1: yield m*(i+1) + j if j > 0: yield m*i + j-1 if j < m-1: yield m*i + j+1 t = [[x for x in neighbors(i,j) if not bad & (1<<x)] for i in xrange(n) for j in xrange(m)] cache = {} def ways(path, l, x): k = (path,x) if k in cache: return cache[k] if l == 1: return 1 if x == start else 0 r = 0 path ^= (1<<x) for y in t[x]: if not (1<<y) & path: continue r += ways(path, l-1, y) cache[k] = r return r return ways(good, s, end)
52ae1f
2eb494
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct.   Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5   Constraints: 1 <= hour <= 12 0 <= minutes <= 59
class Solution(object): def angleClock(self, hour, minutes): hour %= 12 total = hour * 60 + minutes # total out of 12 * 60 ang1 = total / 720.0 ang2 = minutes / 60.0 m = abs(ang1 - ang2) m = min(m, 1-m) return m * 360
169250
2eb494
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct.   Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5   Constraints: 1 <= hour <= 12 0 <= minutes <= 59
class Solution: def angleClock(self, hour: int, minutes: int) -> float: hour %= 12 h_angle = hour * 30.0 + minutes / 60 * 30 m_angle = minutes * 6.0 ans = abs(h_angle - m_angle) return min(ans, 360 - ans)
1c2277
ca14a1
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree. The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively. Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children.   Example 1: Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees shown. The first has a non-leaf node sum 36, and the second has non-leaf node sum 32. Example 2: Input: arr = [4,11] Output: 44   Constraints: 2 <= arr.length <= 40 1 <= arr[i] <= 15 It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 2^31).
class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: n = len(arr) mx = [[-float('inf') for i in range(n+1)] for j in range(n+1)] DP = [[0 for i in range(n+1)] for j in range(n+1)] for i in range(n): for j in range(i, n): mx[i][j+1] = max(mx[i][j], arr[j]) for ln in range(2, n+1): for i in range(n-ln+1): j = i + ln DP[i][j] = float('inf') for k in range(i+1, j): DP[i][j] = min(DP[i][j], DP[i][k] + DP[k][j] + mx[i][k]*mx[k][j]) #print(i, j, k, DP[i][j]) #print("final:", ln, i, j, DP[i][j]) return DP[0][n]
4d7907
ca14a1
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree. The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively. Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children.   Example 1: Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees shown. The first has a non-leaf node sum 36, and the second has non-leaf node sum 32. Example 2: Input: arr = [4,11] Output: 44   Constraints: 2 <= arr.length <= 40 1 <= arr[i] <= 15 It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 2^31).
class Solution(object): def mctFromLeafValues(self, arr): """ :type arr: List[int] :rtype: int """ INF = 1e100 n = len(arr) f = [[INF] * n for _ in xrange(n)] d = [[0] * n for _ in xrange(n)] for i in xrange(n): f[i][i] = 0 d[i][i] = arr[i] for i in xrange(n): for j in xrange(i + 1, n): d[i][j] = max(d[i][j - 1], arr[j]) for i in xrange(n): for j in xrange(i - 1, -1, -1): for k in xrange(j, i): f[j][i] = min(f[j][i], f[j][k] + f[k + 1][i] + d[j][k] * d[k + 1][i]) return f[0][n - 1]
3cefb2
374097
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.   Example 1: Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]] Output: [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. Example 2: Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]] Output: [15,-1,5]   Constraints: 1 <= nums.length, queries.length <= 100000 queries[i].length == 2 0 <= nums[j], xi, mi <= 10^9
#!/opt/python3.9/bin/python3 from bisect import * from collections import * from functools import * from heapq import * from typing import * import sys INF = float('inf') T = lambda: defaultdict(T) class Solution: def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: N = len(nums) M = len(queries) trie = T() def bignum_dp(n): return bin(n)[2:].zfill(32) nums.sort() queries = sorted(enumerate(queries), key=lambda x: x[1][1]) result = [None] * len(queries) last = 0 for query_idx, (x, limit) in queries: while last < len(nums) and nums[last] <= limit: n = nums[last] reduce(dict.__getitem__, bignum_dp(n), trie)['#'] = n last += 1 guh = bignum_dp(x) r = 0 node = trie for c in guh: c = int(c) wanted = c ^ 1 if str(wanted) in node: node = node[str(wanted)] elif str(wanted ^ 1) in node: node = node[str(wanted ^ 1)] else: node = None break if node is None: result[query_idx] = -1 else: result[query_idx] = node['#'] ^ x return result
c55fb4
374097
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.   Example 1: Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]] Output: [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. Example 2: Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]] Output: [15,-1,5]   Constraints: 1 <= nums.length, queries.length <= 100000 queries[i].length == 2 0 <= nums[j], xi, mi <= 10^9
from collections import defaultdict class Solution(object): def maximizeXor(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: List[int] """ nums.sort() T = lambda: defaultdict(T) trie = T() sorted_queries = [[q[1], q[0], i] for i, q in enumerate(queries)] sorted_queries.sort() # [m, x, i] answer = [] def put(p, i, bnum): p = p[(bnum >> i) & 1] if i == 0: p["#"] = bnum else: put(p, i - 1, bnum) def que(p, i, x): if i == -1: return p["#"] opt = 1 - ((x >> i) & 1) if opt in p: p = p[opt] else: p = p[1 - opt] return que(p, i - 1, x) num_p = 0 for m, x, i in sorted_queries: while num_p < len(nums) and nums[num_p] <= m: put(trie, 30, nums[num_p]) num_p += 1 if len(trie) != 0: partner = que(trie, 30, x) answer.append((i, partner ^ x)) else: answer.append((i, -1)) return [item[1] for item in sorted(answer)]
2d3111
f49a3b
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. Train tickets are sold in three different ways: a 1-day pass is sold for costs[0] dollars, a 7-day pass is sold for costs[1] dollars, and a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days.   Example 1: Input: days = [1,4,6,7,8,20], costs = [2,7,15] Output: 11 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. Example 2: Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] Output: 17 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel.   Constraints: 1 <= days.length <= 365 1 <= days[i] <= 365 days is in strictly increasing order. costs.length == 3 1 <= costs[i] <= 1000
class Solution(object): def mincostTickets(self, days, costs): """ :type days: List[int] :type costs: List[int] :rtype: int """ valid = [1, 7, 30] n = len(days) dp = [float('inf')] * n for i, day in enumerate(days): for v, p in zip(valid, costs): idx = bisect.bisect_right(days, day - v, hi=i) - 1 dp[i] = min(dp[i], p + (0 if idx < 0 else dp[idx])) return dp[-1]
4ff731
f49a3b
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. Train tickets are sold in three different ways: a 1-day pass is sold for costs[0] dollars, a 7-day pass is sold for costs[1] dollars, and a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days.   Example 1: Input: days = [1,4,6,7,8,20], costs = [2,7,15] Output: 11 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. Example 2: Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] Output: 17 Explanation: For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel.   Constraints: 1 <= days.length <= 365 1 <= days[i] <= 365 days is in strictly increasing order. costs.length == 3 1 <= costs[i] <= 1000
from functools import lru_cache class Solution: def mincostTickets(self, days: 'List[int]', costs: 'List[int]') -> 'int': @lru_cache(None) def dp(i): if i >= len(days): return 0 current = days[i] seven = i while seven < len(days) and days[seven] < current+7: seven += 1 thirty = seven while thirty < len(days) and days[thirty] < current+30: thirty += 1 x = min([dp(i+1) + costs[0], dp(seven) + costs[1], dp(thirty) + costs[2]]) return x return dp(0)
dec53d
f88dce
Given an integer n, find a sequence that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For every integer i between 2 and n, the distance between the two occurrences of i is exactly i. The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|. Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.   Example 1: Input: n = 3 Output: [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. Example 2: Input: n = 5 Output: [5,3,1,4,3,5,2,4,2]   Constraints: 1 <= n <= 20
class Solution: def constructDistancedSequence(self, n: int) -> List[int]: a = [0] * (n * 2 - 1) c = [True] * (n + 1) c[1] = 1 def work(k): if k == n * 2 - 1: return True if a[k] > 0: return work(k + 1) for i in range(n, 0, -1): if c[i]: if i == 1: a[k] = 1 c[i] = False if work(k + 1): return True c[i] = True a[k] = 0 elif i + k < 2 * n - 1 and a[i + k] == 0: a[k] = i a[i + k] = i c[i] = False if work(k + 1): return True c[i] = True a[k] = 0 a[i + k] = 0 return False work(0) return a
4ab493
f88dce
Given an integer n, find a sequence that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For every integer i between 2 and n, the distance between the two occurrences of i is exactly i. The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|. Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.   Example 1: Input: n = 3 Output: [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. Example 2: Input: n = 5 Output: [5,3,1,4,3,5,2,4,2]   Constraints: 1 <= n <= 20
class Solution(object): def rec(self, a, v, i): # print((a, v, i)) if i == len(a): return a if a[i] != 0: while a[i] != 0: i += 1 if i == len(a): return a return self.rec(a, v, i) for j in range(len(v)-1, 0, -1): if not v[j]: if j == 1 or i + j < len(a) and a[i + j] == 0: v[j] = True a[i] = j if j != 1: a[i + j] = j rc = self.rec(a, v, i + 1) if rc != None: return rc v[j] = False a[i] = 0 if j != 1: a[i + j] = 0 return None def constructDistancedSequence(self, n): v = [False for i in range(n+1)] a = [0 for i in range(2*n-1)] for i in range(n, 0, -1): v[i] = True a[0] = i if i != 1: a[i] = i rc = self.rec(a, v, 1) if rc != None: return rc v[i] = False a[0] = 0 a[i] = 0 return []
5df500
2702cf
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments. A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment. Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal. Note: The same index will not be removed more than once.   Example 1: Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1] Output: [14,7,2,2,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1]. Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5]. Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [14,7,2,2,0]. Example 2: Input: nums = [3,2,11,1], removeQueries = [3,2,1,0] Output: [16,5,3,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11]. Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2]. Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3]. Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [16,5,3,0].   Constraints: n == nums.length == removeQueries.length 1 <= n <= 100000 1 <= nums[i] <= 10^9 0 <= removeQueries[i] < n All the values of removeQueries are unique.
from sortedcontainers import SortedDict class Solution(object): def maximumSegmentSum(self, nums, removeQueries): """ :type nums: List[int] :type removeQueries: List[int] :rtype: List[int] """ r, p, s, t = [0] * len(nums), [0] * len(nums), 0, SortedDict({0: len(nums) - 1}) for i in range(len(nums)): s, p[i] = s + nums[i], s + nums[i] u, i = SortedDict({s: 1}), 0 for q in removeQueries: l, v = t.keys()[t.bisect_left(q + .1) - 1], t[t.keys()[t.bisect_left(q + .1) - 1]] t.pop(l) if u[p[v] - (p[l - 1] if l > 0 else 0)] == 1: u.pop(p[v] - (p[l - 1] if l > 0 else 0)) else: u[p[v] - (p[l - 1] if l > 0 else 0)] = u[p[v] - (p[l - 1] if l > 0 else 0)] - 1 if q > l: u[p[q - 1] - (p[l - 1] if l > 0 else 0)], t[l] = (u[p[q - 1] - (p[l - 1] if l > 0 else 0)] if p[q - 1] - (p[l - 1] if l > 0 else 0) in u else 0) + 1, q - 1 if q < v: u[p[v] - p[q]], t[q + 1] = (u[p[v] - p[q]] if p[v] - p[q] in u else 0) + 1, v r[i], i = u.keys()[-1] if u else 0, i + 1 return r
96355d
2702cf
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments. A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment. Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal. Note: The same index will not be removed more than once.   Example 1: Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1] Output: [14,7,2,2,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1]. Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5]. Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [14,7,2,2,0]. Example 2: Input: nums = [3,2,11,1], removeQueries = [3,2,1,0] Output: [16,5,3,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11]. Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2]. Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3]. Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [16,5,3,0].   Constraints: n == nums.length == removeQueries.length 1 <= n <= 100000 1 <= nums[i] <= 10^9 0 <= removeQueries[i] < n All the values of removeQueries are unique.
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: ans = [] have = {} ma = 0 for merge in removeQueries[::-1]: ans.append(ma) v = nums[merge] if merge - 1 in have and merge + 1 in have: count1, l, _ = have.pop(merge - 1) count2, _, r = have.pop(merge + 1) have[l] = [count1 + count2 + v, l, r] have[r] = [count1 + count2 + v, l, r] ma = max(ma, v + count1 + count2) elif merge - 1 in have: count, l, r = have.pop(merge - 1) have[l] = [v + count, l, merge] have[merge] = [v + count, l, merge] ma = max(ma, v + count) elif merge + 1 in have: count, l, r = have.pop(merge + 1) have[merge] = [v + count, merge, r] have[r] = [v + count, merge, r] ma = max(ma, v + count) else: have[merge] = [v, merge, merge] ma = max(ma, v) return ans[::-1]
f6fd18
300f9e
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following: Choose an integer x > 1, and remove the leftmost x stones from the row. Add the sum of the removed stones' values to the player's score. Place a new stone, whose value is equal to that sum, on the left side of the row. The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.   Example 1: Input: stones = [-1,2,-3,4,-5] Output: 5 Explanation: - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = [2,-5]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = [-3]. The difference between their scores is 2 - (-3) = 5. Example 2: Input: stones = [7,-6,5,10,5,-2,-6] Output: 13 Explanation: - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = [13]. The difference between their scores is 13 - 0 = 13. Example 3: Input: stones = [-10,-12] Output: -22 Explanation: - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = [-22]. The difference between their scores is (-22) - 0 = -22.   Constraints: n == stones.length 2 <= n <= 100000 -10000 <= stones[i] <= 10000
class Solution: def stoneGameVIII(self, stones: List[int]) -> int: pre_sum = [sum(stones[:2])] for t in stones[2:] : pre_sum.append(t + pre_sum[-1]) @functools.lru_cache(None) def solve(pt=0, move='a') : if pt == len(pre_sum) - 1 : return pre_sum[-1] if move == 'a' else -pre_sum[-1] if move == 'a' : return max(solve(pt+1, 'a'), pre_sum[pt]+solve(pt+1, 'b')) else : return min(solve(pt+1, 'b'), -pre_sum[pt]+solve(pt+1, 'a')) return solve()
6fa114
300f9e
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following: Choose an integer x > 1, and remove the leftmost x stones from the row. Add the sum of the removed stones' values to the player's score. Place a new stone, whose value is equal to that sum, on the left side of the row. The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.   Example 1: Input: stones = [-1,2,-3,4,-5] Output: 5 Explanation: - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = [2,-5]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = [-3]. The difference between their scores is 2 - (-3) = 5. Example 2: Input: stones = [7,-6,5,10,5,-2,-6] Output: 13 Explanation: - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = [13]. The difference between their scores is 13 - 0 = 13. Example 3: Input: stones = [-10,-12] Output: -22 Explanation: - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = [-22]. The difference between their scores is (-22) - 0 = -22.   Constraints: n == stones.length 2 <= n <= 100000 -10000 <= stones[i] <= 10000
class Solution(object): def stoneGameVIII(self, stones): """ :type stones: List[int] :rtype: int """ a = stones[::-1] n = len(a) # i stones left: a[:i-1] + [sum(a[i-1:])] # f(i) = max sum(a[j-1:]) - f(j) over 1 <= j < i s = a[:] for i in xrange(n-2, -1, -1): s[i] += s[i+1] m = s[0] - 0 for i in xrange(1, n-1): m = max(m, s[i] - m) return m
58e8bd
65663c
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: m = 1, n = 1 Output: 3 Explanation: The three possible colorings are shown in the image above. Example 2: Input: m = 1, n = 2 Output: 6 Explanation: The six possible colorings are shown in the image above. Example 3: Input: m = 5, n = 5 Output: 580986   Constraints: 1 <= m <= 5 1 <= n <= 1000
class Solution: def colorTheGrid(self, R, C): MOD = 10 ** 9 + 7 def nodup(row): for i in range(len(row) - 1): if row[i] == row[i+1]: return False return True states = [c for c in itertools.product(range(3), repeat=R) if nodup(c)] adj = [[] for _ in states] for i1, s1 in enumerate(states): for i2, s2 in enumerate(states): if all(s1[i] != s2[i] for i in range(R)): adj[i1].append(i2) dp = [1] * len(states) for _ in range(C-1): ndp = [0] * len(states) for i1, row in enumerate(adj): for i2 in row: ndp[i2] += dp[i1] ndp[i2] %= MOD dp = ndp return sum(dp) % MOD
88511a
65663c
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: m = 1, n = 1 Output: 3 Explanation: The three possible colorings are shown in the image above. Example 2: Input: m = 1, n = 2 Output: 6 Explanation: The six possible colorings are shown in the image above. Example 3: Input: m = 5, n = 5 Output: 580986   Constraints: 1 <= m <= 5 1 <= n <= 1000
class Solution(object): def colorTheGrid(self, m, n): """ :type m: int :type n: int :rtype: int """ mod = 1000000007 dp = {} cans = set() def build(s, c): if c==m: cans.add(s) return mk = -1 if c>0: mk = (s%3) for i in range(3): if i==mk: continue build(s*3+i, c+1) build(0, 0) def conflict(s1, s2): for i in range(m): if (s1%3)==(s2%3): return True s1/=3; s2/=3 return False # print cans def dfs(s, i): if i==0: return 1 k = (s, i) if k in dp: return dp[k] r = 0 for c in cans: if conflict(c, s): continue r += dfs(c, i-1) r %=mod dp[k]=r return r rc = 0 for s in cans: rc += dfs(s, n-1) rc %=mod return rc
dcbf3c
abe88b
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.   Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.   Constraints: 1 <= nums.length <= 100000 nums[i] is either 0 or 1. 0 <= k <= nums.length
class Solution(object): def longestOnes(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ n = len(A) i = 0 d = collections.deque() last = 0 total = 0 ret = 0 while i < n: if A[i] == 0: d.append(last + 1) total += d[-1] last = 0 if len(d) > K: total -= d.popleft() ret = max(ret, total) i += 1 else: j = i while j < n and A[j] == 1: j += 1 last = j - i i = j ret = max(ret, total + last) return ret
1bb8f6
abe88b
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.   Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.   Constraints: 1 <= nums.length <= 100000 nums[i] is either 0 or 1. 0 <= k <= nums.length
class Solution: def longestOnes(self, A: List[int], K: int) -> int: dq = collections.deque() n = len(A) dq += [0] ans = 0 for x in A: if x: dq[-1] += 1 else: dq += [0] if len(dq) > K + 1: dq.popleft() ans = max(ans, sum(dq) + K) return min(ans, n)
6a8c27
9a9295
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where both A and B are balanced strings, or It can be written as [C], where C is a balanced string. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.   Example 1: Input: s = "][][" Output: 1 Explanation: You can make the string balanced by swapping index 0 with index 3. The resulting string is "[[]]". Example 2: Input: s = "]]][[[" Output: 2 Explanation: You can do the following to make the string balanced: - Swap index 0 with index 4. s = "[]][][". - Swap index 1 with index 5. s = "[[][]]". The resulting string is "[[][]]". Example 3: Input: s = "[]" Output: 0 Explanation: The string is already balanced.   Constraints: n == s.length 2 <= n <= 1000000 n is even. s[i] is either '[' or ']'. The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
class Solution: def minSwaps(self, s: str) -> int: n = len(s) res = 0 curr = 0 for i,c in enumerate(s): if c=="]": curr +=1 else: curr -=1 res = max(res,curr) return (res+1)//2
f7e7bd
9a9295
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where both A and B are balanced strings, or It can be written as [C], where C is a balanced string. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.   Example 1: Input: s = "][][" Output: 1 Explanation: You can make the string balanced by swapping index 0 with index 3. The resulting string is "[[]]". Example 2: Input: s = "]]][[[" Output: 2 Explanation: You can do the following to make the string balanced: - Swap index 0 with index 4. s = "[]][][". - Swap index 1 with index 5. s = "[[][]]". The resulting string is "[[][]]". Example 3: Input: s = "[]" Output: 0 Explanation: The string is already balanced.   Constraints: n == s.length 2 <= n <= 1000000 n is even. s[i] is either '[' or ']'. The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
class Solution(object): def minSwaps(self, s): """ :type s: str :rtype: int """ a = [1 if ch == '[' else -1 for ch in s] n = len(a) j = n h = r = 0 for i in xrange(n): if a[i] < 0 and h == 0: j -= 1 while a[j] < 0: j -= 1 a[i], a[j] = a[j], a[i] r += 1 h += a[i] return r
cf9b91
a40480
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.   Example 1: Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Example 2: Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved. Example 3: Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]]   Constraints: board.length == 2 board[i].length == 3 0 <= board[i][j] <= 5 Each value board[i][j] is unique.
class Solution: def encode(self, a): ret = '' for i in range(2): for j in range(3): ret += '{}'.format(a[i][j]) return ret def decode(self, val): a = [[None, None, None], [None, None, None]] t = 0 for i in range(2): for j in range(3): a[i][j] = int(val[t]) t += 1 return a def copy(self, val): a = [[None, None, None], [None, None, None]] for i in range(2): for j in range(3): a[i][j] = val[i][j] return a def slidingPuzzle(self, board): """ :type board: List[List[int]] :rtype: int """ start = self.encode(board) dist = {} dist[start] = 0 import collections q = collections.deque() q.append(start) while '123450' not in dist: if len(q) == 0: return -1 idx = q.popleft() cur = self.decode(idx) for i in range(2): for j in range(3): if cur[i][j] == 0: x, y = i, j # print(cur, cur) if x > 0: tmp = self.copy(cur) tmp[x][y], tmp[x - 1][y] = tmp[x - 1][y], tmp[x][y] # print(cur, '1', tmp) tmp = self.encode(tmp) if tmp not in dist: dist[tmp] = dist[idx] + 1 q.append(tmp) if x < 1: tmp = self.copy(cur) tmp[x][y], tmp[x + 1][y] = tmp[x + 1][y], tmp[x][y] # print(cur, '2', tmp) tmp = self.encode(tmp) if tmp not in dist: dist[tmp] = dist[idx] + 1 q.append(tmp) if y > 0: tmp = self.copy(cur) tmp[x][y], tmp[x][y - 1] = tmp[x][y - 1], tmp[x][y] # print(cur, '3', tmp) tmp = self.encode(tmp) if tmp not in dist: dist[tmp] = dist[idx] + 1 q.append(tmp) if y < 2: tmp = self.copy(cur) tmp[x][y], tmp[x][y + 1] = tmp[x][y + 1], tmp[x][y] # print(cur, '4', tmp) tmp = self.encode(tmp) if tmp not in dist: dist[tmp] = dist[idx] + 1 q.append(tmp) return dist['123450']
c861d3
a40480
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.   Example 1: Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Example 2: Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved. Example 3: Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]]   Constraints: board.length == 2 board[i].length == 3 0 <= board[i][j] <= 5 Each value board[i][j] is unique.
class Solution(object): def slidingPuzzle(self, board): """ :type board: List[List[int]] :rtype: int """ start = tuple(i for j in board for i in j) end = (1,2,3,4,5,0) if start == end: return 0 visited = set() visited.add(start) toDo = [start] result = 1 while toDo: newTo = [] for td in toDo: id0 = td.index(0) if id0 == 0: temp = (td[3],td[1],td[2],td[0],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[1],td[0],td[2],td[3],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) elif id0 == 1: temp = (td[0],td[4],td[2],td[3],td[1],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[1],td[0],td[2],td[3],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[2],td[1],td[3],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) elif id0 == 2: temp = (td[0],td[1],td[5],td[3],td[4],td[2]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[2],td[1],td[3],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) elif id0 == 3: temp = (td[3],td[1],td[2],td[0],td[4],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[1],td[2],td[4],td[3],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) elif id0 == 4: temp = (td[0],td[4],td[2],td[3],td[1],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[1],td[2],td[4],td[3],td[5]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[1],td[2],td[3],td[5],td[4]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) else: temp = (td[0],td[1],td[5],td[3],td[4],td[2]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) temp = (td[0],td[1],td[2],td[3],td[5],td[4]) if temp not in visited: if temp == end: return result visited.add(temp) newTo.append(temp) toDo = newTo result += 1 return -1
94dd6d
b53244
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.   Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. Example 3: Input: matrix = [[1,1,0],[1,0,1]] Output: 2 Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.   Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 100000 matrix[i][j] is either 0 or 1.
class Solution(object): def largestSubmatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ a = matrix n, m = len(a), len(a[0]) c = [0]*m r = 0 for i in xrange(n): c = [c[j]+1 if a[i][j]==1 else 0 for j in xrange(m)] d = sorted(c, reverse=True) h = d[0] for j in xrange(m): h = min(h, d[j]) if h == 0: break r = max(r, h*(j+1)) return r
122dad
b53244
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.   Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. Example 3: Input: matrix = [[1,1,0],[1,0,1]] Output: 2 Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.   Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 100000 matrix[i][j] is either 0 or 1.
class Solution: def largestSubmatrix(self, matrix: List[List[int]]) -> int: R, C = len(matrix), len(matrix[0]) reach = [[0]*C for _ in range(R)] for c in range(C): run = 0 for r in range(R): if matrix[r][c] == 1: run += 1 else: run = 0 reach[r][c] = run res = 0 for row in reach: row.sort(reverse=True) #for row in reach: for i in range(len(row)): res = max(res, (i+1)*row[i]) return res
e0dc5c
0e2a5b
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.   Example 1: Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves. Example 2: Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). Example 3: Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).   Constraints: 1 <= n <= 100000
class Solution(object): def winnerSquareGame(self, n): dp = [False, True, False] for x in xrange(3, n+1): dp.append(False) for y in xrange(1, n*n): a = x - y * y if a < 0: break if not dp[a]: dp[x] = True break return dp[n]
1b0c2f
0e2a5b
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.   Example 1: Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves. Example 2: Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). Example 3: Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).   Constraints: 1 <= n <= 100000
class Solution: def winnerSquareGame(self, n: int) -> bool: f = [False] * (n + 1) f[0] = False f[1] = True for i in range(2, n + 1): j = 1 while j * j <= i: if not f[i - j * j]: f[i] = True break j += 1 return f[n]
f55b78
524113
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.   Example 1: Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^8
class Solution: def maximumXOR(self, a: List[int]) -> int: z = 0 for i in a: z |= i return z
39ffdf
524113
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.   Example 1: Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR.   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^8
class Solution(object): def maximumXOR(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 for i in range(32): val = (1<<i) cnt0, cnt1 = 0, 0 for x in nums: if x<val: continue if x&val: cnt1+=1 else: cnt0+=1 if cnt1>0: res+=val return res
18dfbc
c4d739
Given an m x n binary matrix mat, return the number of submatrices that have all ones.   Example 1: Input: mat = [[1,0,1],[1,1,0],[1,1,0]] Output: 13 Explanation: There are 6 rectangles of side 1x1. There are 2 rectangles of side 1x2. There are 3 rectangles of side 2x1. There is 1 rectangle of side 2x2. There is 1 rectangle of side 3x1. Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13. Example 2: Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]] Output: 24 Explanation: There are 8 rectangles of side 1x1. There are 5 rectangles of side 1x2. There are 2 rectangles of side 1x3. There are 4 rectangles of side 2x1. There are 2 rectangles of side 2x2. There are 2 rectangles of side 3x1. There is 1 rectangle of side 3x2. Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.   Constraints: 1 <= m, n <= 150 mat[i][j] is either 0 or 1.
class Solution(object): def numSubmat(self, mat): """ :type mat: List[List[int]] :rtype: int """ a = mat n, m = len(a), len(a[0]) f = [[0]*(m+1) for _ in xrange(n)] for i in xrange(n): for j in xrange(m-1, -1, -1): if a[i][j]: f[i][j] = f[i][j+1] + 1 r = 0 for i in xrange(n): for j in xrange(m): t = f[i][j] for k in xrange(i, n): t = min(t, f[k][j]) if t == 0: break r += t return r
da8f18
c4d739
Given an m x n binary matrix mat, return the number of submatrices that have all ones.   Example 1: Input: mat = [[1,0,1],[1,1,0],[1,1,0]] Output: 13 Explanation: There are 6 rectangles of side 1x1. There are 2 rectangles of side 1x2. There are 3 rectangles of side 2x1. There is 1 rectangle of side 2x2. There is 1 rectangle of side 3x1. Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13. Example 2: Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]] Output: 24 Explanation: There are 8 rectangles of side 1x1. There are 5 rectangles of side 1x2. There are 2 rectangles of side 1x3. There are 4 rectangles of side 2x1. There are 2 rectangles of side 2x2. There are 2 rectangles of side 3x1. There is 1 rectangle of side 3x2. Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.   Constraints: 1 <= m, n <= 150 mat[i][j] is either 0 or 1.
class Solution: def numSubmat(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) prefix = [[0] * (n + 1) for i in range(m + 1)] for i in range(1, m+1): for j in range(1, n+1): prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] + mat[i-1][j-1] ans = 0 for i in range(m): for j in range(n): for k in range(m - i): for l in range(n - j): if prefix[i+k+1][j+l+1] - prefix[i][j+l+1] - prefix[i+k+1][j] + prefix[i][j] == (k + 1) * (l + 1): ans += 1 else: break return ans
c3ee39
6b4a25
You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. Return the maximum points you can get.   Example 1: Input: boxes = [1,3,2,2,2,3,4,3,1] Output: 23 Explanation: [1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) ----> [1, 3, 3, 3, 1] (1*1=1 points) ----> [1, 1] (3*3=9 points) ----> [] (2*2=4 points) Example 2: Input: boxes = [1,1,1] Output: 9 Example 3: Input: boxes = [1] Output: 1   Constraints: 1 <= boxes.length <= 100 1 <= boxes[i] <= 100
class Solution(object): def removeBoxes(self, A): sqmemo = {} def sq(x): #best way to have a_i sum to x maximizing a_i ** 2 if x < 2: return x if x == 2: return 4 if x in sqmemo: return sqmemo[x] ans = x*x for y in xrange(1, x): ans = max(ans, y*y + sq(x-y) ) sqmemo[x] = ans return ans from itertools import groupby, combinations N = len(A) memo = {(i,i): 1 for i in xrange(N)} for i in xrange(N): memo[i+1,i] = 0 if i < N-1: memo[i,i+1] = 2 if A[i] != A[i+1] else 4 def dp(i, j): if i>j: return 0 if (i,j) in memo: return memo[i,j] #value of A[i:j+1] """ ans = max(dp(i,m) + dp(m+1,j) for m in xrange(i, j)) buf = [] sumup = count = 0 if A[i] == A[j]: #develop answer involving removing all non A[i]'s for m in xrange(i, j+1): if A[i] == A[m]: count += 1 if buf: sumup += dp(buf[0], buf[-1]) buf =[] else: buf.append(m) if buf: sumup += dp(buf[0], buf[-1]) ans = max(ans, sumup + sq(count)) """ """ k = i while k+1 <= j and A[k+1] == A[i]: k += 1 ans = (k-i+1)**2 + dp(k+1, j) """ #What is last m so that i-m get popped together? """ ans = 0 count = 1 buf = [] sumup = 0 for m in xrange(i+1, j+1): if A[m] == A[i]: count += 1 if buf: sumup += dp(buf[0], buf[-1]) buf = [] ans = max(ans, sq(count) + sumup + dp(m+1, j)) else: buf.append(m) ans = max(ans, sq(count) + sumup + dp(buf[0], buf[-1]) + dp(m+1, j)) """ def outranges(grps, i, j): prev = i for gr in grps: g0, g1 = gr[0], gr[-1] yield prev, g0 - 1 prev = g1 + 1 yield prev, j good = [] bad = [] for k,v in groupby(range(i, j+1), key=lambda x: A[x] == A[i]): if k: good.append(list(v)) else: bad.append(list(v)) #Let's choose a subset of good groups G = len(good) ans = 0 for size in xrange(1, G+1): for cand in combinations(good, size): candsum = 0 for l, r in outranges(cand, i, j): candsum += dp(l, r) ans = max(ans, sum( g[-1] - g[0] + 1 for g in cand )**2 + candsum ) """ good = good[::-1] bad = bad[::-1] ans = -1 count = sumup = 0 while good and bad: goodn = good.pop() badn = bad.pop() g0,g1 = goodn[0], goodn[-1] b0,b1 = badn[0], badn[-1] for i in xrange(1, g1-g0+2): count += 1 ans = max(ans, sq(count) + sumup + dp(g0 + i, j)) #count += g1 - g0 + 1 sumup += dp(b0, b1) ans = max(ans, sq(count) + sumup + dp(b1 + 1, j)) if good: goodn = good.pop() #badn = bad.pop() g0,g1 = goodn[0], goodn[-1] #b0,b1 = badn[0], badn[-1] for i in xrange(1, g1-g0+2): count += 1 ans = max(ans, sq(count) + sumup + dp(g0 + i, j)) """ #assert(not good and not bad) """ count = k-i+1 bad = [] buf = [] sumup = 0 for m in xrange(k+1, j+1): if A[i] == A[m]: count += 1 if buf: bad.append([buf[0], buf[-1]]) sumup += dp(buf[0], buf[-1]) buf = [] else: buf.append(m) ans = max(ans, count**2 + sumup + dp(m+1, j) ) """ memo[i,j] = ans return ans for z in xrange(N): for i in xrange(N-z): _ = dp(i, i+z) return dp(0, len(A)-1)
754252
72fd44
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid. We can rotate digits of a number by 180 degrees to form new digits. When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 respectively. When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid. Note that after rotating a number, we can ignore leading zeros. For example, after rotating 8000, we have 0008 which is considered as just 8. Given an integer n, return the number of confusing numbers in the inclusive range [1, n]. Example 1: Input: n = 20 Output: 6 Explanation: The confusing numbers are [6,9,10,16,18,19]. 6 converts to 9. 9 converts to 6. 10 converts to 01 which is just 1. 16 converts to 91. 18 converts to 81. 19 converts to 61. Example 2: Input: n = 100 Output: 19 Explanation: The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]. Constraints: 1 <= n <= 10^9
class Solution: def countReversableForLength(self, length: int) -> int: return 4 * 5**(length - 1); def foobar(self, i: int, c: str) -> int: res = 1 if i > 0 else 0 if c == '7': return res + 2 return res + 1 def skidiki(self, i: int, c: str) -> int: if c == '0': return 0 res = 1 if i > 0 else 0 if c == '1': return res if c == '6': return res + 1 if c == '8': return res + 2 if c == '9': return res + 3 def check(self, s: int) -> bool: for c in str(s): if c in '23457': return False return True def countReversable(self, N: int) -> int: s = str(N) ans = 0 for i in range(1, len(s)): ans += self.countReversableForLength(i) for i, c in enumerate(s): if c in '23457': ans += self.foobar(i, c) * 5**(len(s) - i - 1) return ans else: ans += self.skidiki(i, c) * 5**(len(s) - i - 1) return ans + 1 def inverse(self, c: str) -> str: if c == '0': return '0' if c == '1': return '1' if c == '6': return '9' if c == '8': return '8' if c == '9': return '6' def reverse(self, x: int) -> str: s = str(x) for c in s: if c not in "01689": return None s = s[::-1] return ''.join([self.inverse(c) for c in s]) def confusingNumberII(self, N: int) -> int: ans = self.countReversable(N) if N >= 1: ans -= 1 if N >= 8: ans -= 1 i = 1 while True: s = self.reverse(i) if not s: i += 1 continue x = int(str(i) + s) if x <= N: ans -= 1 else: break i += 1 i = 1 while True: s = self.reverse(i) if not s: i += 1 continue x = int(str(i) + '0' + self.reverse(i)) y = int(str(i) + '1' + self.reverse(i)) z = int(str(i) + '8' + self.reverse(i)) if x <= N: ans -= 1 if y <= N: ans -= 1 if z <= N: ans -= 1 if x > N and y > N and x > N: break i += 1 return ans
115c5e
72fd44
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid. We can rotate digits of a number by 180 degrees to form new digits. When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 respectively. When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid. Note that after rotating a number, we can ignore leading zeros. For example, after rotating 8000, we have 0008 which is considered as just 8. Given an integer n, return the number of confusing numbers in the inclusive range [1, n]. Example 1: Input: n = 20 Output: 6 Explanation: The confusing numbers are [6,9,10,16,18,19]. 6 converts to 9. 9 converts to 6. 10 converts to 01 which is just 1. 16 converts to 91. 18 converts to 81. 19 converts to 61. Example 2: Input: n = 100 Output: 19 Explanation: The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]. Constraints: 1 <= n <= 10^9
c = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6} digit = [0, 1, 6, 8, 9] index = 1 pre = [0] * 9 def check(num): res = 0 tmp = num while num: num, mod = divmod(num, 10) res = res * 10 + c[mod] return res != tmp def dfs(total_idx, idx, num): if idx == total_idx: if check(num): pre[index] += 1; return for v in digit: if idx == 0 and v == 0: continue dfs(total_idx, idx + 1, num * 10 + v) while index <= 8: dfs(index, 0, 0) pre[index] += pre[index-1] index += 1 class Solution(object): def confusingNumberII(self, N): if N == 10**9: return 1950627 n = len(str(N)) self.ans = pre[n-1] def newdfs(total_idx, idx, num): if idx == total_idx: if num <= N and check(num): self.ans += 1; return for v in digit: if idx == 0 and v == 0: continue newdfs(total_idx, idx + 1, num * 10 + v) newdfs(n, 0, 0) return self.ans
58fcc9
3ba861
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.   Example 1: Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 Output: 2 Explanation: The maximum side length of square with sum less than 4 is 2 as shown. Example 2: Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1 Output: 0   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 300 0 <= mat[i][j] <= 10000 0 <= threshold <= 100000
class Solution(object): def maxSideLength(self, mat, threshold): """ :type mat: List[List[int]] :type threshold: int :rtype: int """ n, m = len(mat), len(mat[0]) s = [[0]*(m+1) for _ in xrange(n+1)] for i, row in enumerate(mat): for j, v in enumerate(row): s[i+1][j+1] = mat[i][j]+s[i+1][j]+s[i][j+1]-s[i][j] a, b = 0, min(n, m)+1 while a+1<b: c=(a+b)>>1 t = min(s[i+c][j+c]+s[i][j]-s[i][j+c]-s[i+c][j] for i in xrange(1+n-c) for j in xrange(1+m-c)) if t <= threshold: a=c else: b=c return a
83dbb6
3ba861
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.   Example 1: Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 Output: 2 Explanation: The maximum side length of square with sum less than 4 is 2 as shown. Example 2: Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1 Output: 0   Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 300 0 <= mat[i][j] <= 10000 0 <= threshold <= 100000
class Solution: def maxSideLength(self, matrix: List[List[int]], threshold: int) -> int: n = len(matrix) m = len(matrix[0]) mat = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, m + 1): mat[i][j] = matrix[i - 1][j - 1] if i > 0: mat[i][j] += mat[i - 1][j] if j > 0: mat[i][j] += mat[i][j - 1] if i > 0 and j > 0: mat[i][j] -= mat[i - 1][j - 1] def check(i, j, l): if i + l - 1 > n: return False if j + l - 1 > m: return False return mat[i + l - 1][j + l - 1] - mat[i - 1][j + l - 1] - mat[i + l - 1][j - 1] + mat[i - 1][j - 1] <= threshold dp = [[0] * (m + 1) for _ in range(n + 1)] res = 0 for i in range(1, n + 1): for j in range(1, m + 1): if matrix[i - 1][j - 1] > threshold: dp[i][j] = 0 continue l = max(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1], 3) - 1 while check(i, j, l): l += 1 dp[i][j] = l - 1 res = max(res, dp[i][j]) return res
0ee19d
f3a517
You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [3,5,6,7], target = 9 Output: 4 Explanation: There are 4 subsequences that satisfy the condition. [3] -> Min value + max value <= target (3 + 3 <= 9) [3,5] -> (3 + 5 <= 9) [3,5,6] -> (3 + 6 <= 9) [3,6] -> (3 + 6 <= 9) Example 2: Input: nums = [3,3,6,8], target = 10 Output: 6 Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). [3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6] Example 3: Input: nums = [2,3,3,4,6,7], target = 12 Output: 61 Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]). Number of valid subsequences (63 - 2 = 61).   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 1000000 1 <= target <= 1000000
class Solution: def numSubseq(self, nums: List[int], target: int) -> int: nums.sort() l=0 r=0 mod=10**9+7 n=len(nums) while r<n and nums[l]+nums[r]<=target: r+=1 ans=0 if r==l: return 0 ans+=2**(r-l-1)%mod l+=1 r-=1 if r<l: return 1 while l<n and 2*nums[l]<=target: while nums[r]+nums[l]>target: r-=1 ans+=2**(r-l) ans%=mod l+=1 return ans%mod
d97488
f3a517
You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [3,5,6,7], target = 9 Output: 4 Explanation: There are 4 subsequences that satisfy the condition. [3] -> Min value + max value <= target (3 + 3 <= 9) [3,5] -> (3 + 5 <= 9) [3,5,6] -> (3 + 6 <= 9) [3,6] -> (3 + 6 <= 9) Example 2: Input: nums = [3,3,6,8], target = 10 Output: 6 Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). [3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6] Example 3: Input: nums = [2,3,3,4,6,7], target = 12 Output: 61 Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]). Number of valid subsequences (63 - 2 = 61).   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 1000000 1 <= target <= 1000000
class Solution(object): def numSubseq(self, A, K): MOD = 10 ** 9 + 7 N = len(A) pow2 = [1] for x in xrange(1, N + 1): pow2.append(pow2[-1] * 2 % MOD) A.sort() ans = 0 j = N - 1 for i in range(N): while j and A[i] + A[j] > K: j -= 1 if i <= j and A[i] + A[j] <= K: ans += pow2[j - i] ans %= MOD return ans
0c3f97
749a6a
You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]: If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2. If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3. Return the maximum points you can earn for the exam.   Example 1: Input: questions = [[3,2],[4,3],[4,4],[2,5]] Output: 5 Explanation: The maximum points can be earned by solving questions 0 and 3. - Solve question 0: Earn 3 points, will be unable to solve the next 2 questions - Unable to solve questions 1 and 2 - Solve question 3: Earn 2 points Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points. Example 2: Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: 7 Explanation: The maximum points can be earned by solving questions 1 and 4. - Skip question 0 - Solve question 1: Earn 2 points, will be unable to solve the next 2 questions - Unable to solve questions 2 and 3 - Solve question 4: Earn 5 points Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.   Constraints: 1 <= questions.length <= 100000 questions[i].length == 2 1 <= pointsi, brainpoweri <= 100000
class Solution: def mostPoints(self, questions: List[List[int]]) -> int: @functools.lru_cache(None) def solve(t=0) : if t >= len(questions) : return 0 points, brainpower = questions[t] return max(points+solve(t+brainpower+1), solve(t+1)) return solve()
8a9948
749a6a
You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]: If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2. If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3. Return the maximum points you can earn for the exam.   Example 1: Input: questions = [[3,2],[4,3],[4,4],[2,5]] Output: 5 Explanation: The maximum points can be earned by solving questions 0 and 3. - Solve question 0: Earn 3 points, will be unable to solve the next 2 questions - Unable to solve questions 1 and 2 - Solve question 3: Earn 2 points Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points. Example 2: Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: 7 Explanation: The maximum points can be earned by solving questions 1 and 4. - Skip question 0 - Solve question 1: Earn 2 points, will be unable to solve the next 2 questions - Unable to solve questions 2 and 3 - Solve question 4: Earn 5 points Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.   Constraints: 1 <= questions.length <= 100000 questions[i].length == 2 1 <= pointsi, brainpoweri <= 100000
class Solution(object): def mostPoints(self, questions): """ :type questions: List[List[int]] :rtype: int """ a = questions n = len(a) r = [0] * (n+1) for i in xrange(n-1, -1, -1): r[i] = a[i][0] if i + a[i][1] + 1 < n: r[i] += r[i + a[i][1] + 1] r[i] = max(r[i], r[i+1]) return r[0]
7ed6c0
7bb56d
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even. Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 10^9 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.   Example 1: Input: n = 1 Output: 5 Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8". Example 2: Input: n = 4 Output: 400 Example 3: Input: n = 50 Output: 564908303   Constraints: 1 <= n <= 10^15
class Solution: def countGoodNumbers(self, n: int) -> int: od = n >> 1 ev = n - od ans = pow(5, ev, 1000000007) * pow(4, od, 1000000007) % 1000000007 return ans
78587e
7bb56d
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even. Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 10^9 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.   Example 1: Input: n = 1 Output: 5 Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8". Example 2: Input: n = 4 Output: 400 Example 3: Input: n = 50 Output: 564908303   Constraints: 1 <= n <= 10^15
class Solution(object): def countGoodNumbers(self, n): """ :type n: int :rtype: int """ mod = 10**9 + 7 return (pow(5, (n+1)//2, mod) * pow(4, n//2, mod)) % mod
db26af
385901
Design a number container system that can do the following: Insert or Replace a number at the given index in the system. Return the smallest index for the given number in the system. Implement the NumberContainers class: NumberContainers() Initializes the number container system. void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it. int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.   Example 1: Input ["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"] [[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]] Output [null, -1, null, null, null, null, 1, null, 2] Explanation NumberContainers nc = new NumberContainers(); nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1. nc.change(2, 10); // Your container at index 2 will be filled with number 10. nc.change(1, 10); // Your container at index 1 will be filled with number 10. nc.change(3, 10); // Your container at index 3 will be filled with number 10. nc.change(5, 10); // Your container at index 5 will be filled with number 10. nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1. nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.   Constraints: 1 <= index, number <= 10^9 At most 100000 calls will be made in total to change and find.
from sortedcontainers import SortedList class NumberContainers(object): def __init__(self): self.fow = {} self.rev = defaultdict(SortedList) def change(self, index, number): """ :type index: int :type number: int :rtype: None """ if index not in self.fow: self.fow[index] = number self.rev[number].add(index) else: old = self.fow[index] self.rev[old].remove(index) self.fow[index] = number self.rev[number].add(index) def find(self, number): """ :type number: int :rtype: int """ row = self.rev[number] if not row: return -1 return row[0] # Your NumberContainers object will be instantiated and called as such: # obj = NumberContainers() # obj.change(index,number) # param_2 = obj.find(number)
1671b5
385901
Design a number container system that can do the following: Insert or Replace a number at the given index in the system. Return the smallest index for the given number in the system. Implement the NumberContainers class: NumberContainers() Initializes the number container system. void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it. int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.   Example 1: Input ["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"] [[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]] Output [null, -1, null, null, null, null, 1, null, 2] Explanation NumberContainers nc = new NumberContainers(); nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1. nc.change(2, 10); // Your container at index 2 will be filled with number 10. nc.change(1, 10); // Your container at index 1 will be filled with number 10. nc.change(3, 10); // Your container at index 3 will be filled with number 10. nc.change(5, 10); // Your container at index 5 will be filled with number 10. nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1. nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.   Constraints: 1 <= index, number <= 10^9 At most 100000 calls will be made in total to change and find.
from heapq import heappop, heappush class NumberContainers: def __init__(self): self.seen = {} self.vals = {} def change(self, index: int, number: int) -> None: self.seen[index] = number if number not in self.vals: self.vals[number] = [] heappush(self.vals[number], index) def find(self, number: int) -> int: if number not in self.vals: return -1 while self.vals[number]: ind = self.vals[number][0] if self.seen[ind] == number: return ind heappop(self.vals[number]) return -1 # Your NumberContainers object will be instantiated and called as such: # obj = NumberContainers() # obj.change(index,number) # param_2 = obj.find(number)
6fafcf
bcabff
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and merge = "dv", then after choosing this operation, word1 = "bc" and merge = "dva". If word2 is non-empty, append the first character in word2 to merge and delete it from word2. For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a". Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: word1 = "cabaa", word2 = "bcaaa" Output: "cbcabaaaaa" Explanation: One way to get the lexicographically largest merge is: - Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" - Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" - Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" - Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" - Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" - Append the remaining 5 a's from word1 and word2 at the end of merge. Example 2: Input: word1 = "abcabc", word2 = "abdcaba" Output: "abdcabcabcaba"   Constraints: 1 <= word1.length, word2.length <= 3000 word1 and word2 consist only of lowercase English letters.
class Solution: def largestMerge(self, a: str, b: str) -> str: # subproblem of that other problem ret = "" while a or b: if a >= b: ret += a[0] a = a[1:] else: ret += b[0] b = b[1:] return ret
d84aa8
bcabff
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and merge = "dv", then after choosing this operation, word1 = "bc" and merge = "dva". If word2 is non-empty, append the first character in word2 to merge and delete it from word2. For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a". Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: word1 = "cabaa", word2 = "bcaaa" Output: "cbcabaaaaa" Explanation: One way to get the lexicographically largest merge is: - Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" - Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" - Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" - Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" - Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" - Append the remaining 5 a's from word1 and word2 at the end of merge. Example 2: Input: word1 = "abcabc", word2 = "abdcaba" Output: "abdcabcabcaba"   Constraints: 1 <= word1.length, word2.length <= 3000 word1 and word2 consist only of lowercase English letters.
class Solution(object): def largestMerge(self, word1, word2): """ :type word1: str :type word2: str :rtype: str """ res = '' while word1 and word2: if word1[0] > word2[0]: res += word1[0] word1 = word1[1:] elif word1[0] < word2[0]: res += word2[0] word2 = word2[1:] else: i = 0 while i < len(word1) and i < len(word2) and word1[i] == word2[i]: i += 1 if i == len(word2) or i < len(word1) and word1[i] > word2[i]: res += word1[0] word1 = word1[1:] else: res += word2[0] word2 = word2[1:] return res + word1 + word2
81d949
8b22c1
You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k. Return the number of distinct great partitions. Since the answer may be too large, return it modulo 10^9 + 7. Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.   Example 1: Input: nums = [1,2,3,4], k = 4 Output: 6 Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]). Example 2: Input: nums = [3,3,3], k = 4 Output: 0 Explanation: There are no great partitions for this array. Example 3: Input: nums = [6,6], k = 2 Output: 2 Explanation: We can either put nums[0] in the first partition or in the second partition. The great partitions will be ([6], [6]) and ([6], [6]).   Constraints: 1 <= nums.length, k <= 1000 1 <= nums[i] <= 10^9
class Solution(object): def countPartitions(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def i(): c, s, t = 0, 0, 0 for i in nums: c, s, t = c if i < k else c + 1, s + i if i < k else s, t + i if c or min(3 * k, t - k) < k: return c < 2 and s < k or not c d = [[True] + [False] * min(3 * k, t - k) for _ in range(len(nums) + 1)] for i in range(1, len(nums) + 1): for j in range(1, min(3 * k, t - k) + 1): d[i][j] = j - nums[i - 1] >= 0 and d[i - 1][j - nums[i - 1]] or d[i - 1][j] for i in range(k, min(3 * k, t - k) + 1): if d[len(nums)][i]: return False return True if i(): return 0 d, a = [[1] + [0] * k for _ in range(len(nums) + 1)], 0 for i in range(1, len(nums) + 1): for j in range(1, k + 1): d[i][j] = ((d[i - 1][j - nums[i - 1]] if j - nums[i - 1] >= 0 else 0) + d[i - 1][j]) % 1000000007 for j in range(max(0, k - nums[i - 1] + 1), k + 1): d[i][k] = (d[i][k] + d[i - 1][j]) % 1000000007 for i in range(k): a = (a + d[len(nums)][i]) % 1000000007 return (d[len(nums)][k] - a + 1000000007) % 1000000007
8968cc
8b22c1
You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k. Return the number of distinct great partitions. Since the answer may be too large, return it modulo 10^9 + 7. Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.   Example 1: Input: nums = [1,2,3,4], k = 4 Output: 6 Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]). Example 2: Input: nums = [3,3,3], k = 4 Output: 0 Explanation: There are no great partitions for this array. Example 3: Input: nums = [6,6], k = 2 Output: 2 Explanation: We can either put nums[0] in the first partition or in the second partition. The great partitions will be ([6], [6]) and ([6], [6]).   Constraints: 1 <= nums.length, k <= 1000 1 <= nums[i] <= 10^9
class Solution: def countPartitions(self, A: List[int], k: int) -> int: mod = 10**9+7 total = sum(A) dp = [1] + [0] * (k - 1) for a in A: for i in range(k-1-a,-1,-1): dp[i + a] += dp[i] n = len(A) res = pow(2, n, mod) for i in range(k): if total - i < k: res -= dp[i] else: res -= dp[i] * 2 return res % mod
77dba7
5cf709
Given an integer array nums of length n, return true if there is a triplet (i, j, k) which satisfies the following conditions: 0 < i, i + 1 < j, j + 1 < k < n - 1 The sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) is equal. A subarray (l, r) represents a slice of the original array starting from the element indexed l to the element indexed r. Example 1: Input: nums = [1,2,1,2,1,2,1] Output: true Explanation: i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 Example 2: Input: nums = [1,2,1,2,1,2,1,2] Output: false Constraints: n == nums.length 1 <= n <= 2000 -1000000 <= nums[i] <= 1000000
class Solution(object): def splitArray(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) if n < 7: return False s = [0] * (n + 1) for i in range(n): s[i + 1] = s[i] + nums[i] j = n o = set() while j > 3: if j + 2 < n: o.add((s[n] - s[j + 2], nums[j + 1])) if n - j >= 3: i = 2 while i <= j - 2: t = s[i - 1] if t == s[j - 1] - s[i]: x = s[n] - s[j] if ((t, x - t * 2)) in o: return True i += 1 j -= 1 return False
d46ecc
d34325
A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 1, a = 2, b = 3 Output: 2 Example 2: Input: n = 4, a = 2, b = 3 Output: 6   Constraints: 1 <= n <= 10^9 2 <= a, b <= 4 * 10000
class Solution(object): def gcd(self, a, b): if 0 == b: return a return self.gcd(b, a % b) def nthMagicalNumber(self, n, a, b): """ :type N: int :type A: int :type B: int :rtype: int """ c = a * b / self.gcd(a, b) lo, hi = 1, 1 << 60 while lo < hi: mid = (lo + hi) / 2 t = mid / a + mid / b - mid / c if t < n: lo = mid + 1 else: hi = mid return lo % 1000000007
ee8591
d34325
A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 1, a = 2, b = 3 Output: 2 Example 2: Input: n = 4, a = 2, b = 3 Output: 6   Constraints: 1 <= n <= 10^9 2 <= a, b <= 4 * 10000
class Solution: def nthMagicalNumber(self, N, A, B): """ :type N: int :type A: int :type B: int :rtype: int """ MOD = 10 ** 9 + 7 if A > B: A, B = B, A if B % A == 0: return (A * N) % MOD def gcd(x, y): if x % y == 0: return y return gcd(y, x % y) C = A * B // gcd(A, B) def count(X): ans = 0 ans += X // A ans += X // B ans -= X // C return ans l, r = 1, N * min(A, B) while l < r: mid = (l + r) // 2 if count(mid) < N: l = mid + 1 else: r = mid return l % MOD
eac7e6
a9e907
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4. Return the maximum possible AND sum of nums given numSlots slots.   Example 1: Input: nums = [1,2,3,4,5,6], numSlots = 3 Output: 9 Explanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. This gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9. Example 2: Input: nums = [1,3,10,4,7,1], numSlots = 9 Output: 24 Explanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9. This gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24. Note that slots 2, 5, 6, and 8 are empty which is permitted.   Constraints: n == nums.length 1 <= numSlots <= 9 1 <= n <= 2 * numSlots 1 <= nums[i] <= 15
class Solution: def maximumANDSum(self, nums: List[int], numSlots: int) -> int: import scipy.optimize nums += [0]*(numSlots*2-len(nums)) arr = [[-(i&(j//2+1)) for j in range(numSlots*2)] for i in nums] #print(arr) #print(nums) row, col = scipy.optimize.linear_sum_assignment(arr) #print(row, col) return -sum(arr[i][j] for i, j in zip(row, col)) """x = [0]*16 for i in nums: x[i] += 1 ans = 0 rem = numSlots for i in range(1, 16): if x[i] > 1: while x[i] >= 2: ans += i*2 x[i] -= 2 rem -= 1 @cache def f(slots, b, cur): if b == 0: return 0 if slots == 0: return -10**18 x = [i for i in range(1, 16) if b&(1<<i)] res = -10**18 for i in range(len(x)): for j in range(i+1, len(x)): res = max(res, f(slots-1, b^(1<<x[i])^(1<<x[j]))+(x[i]&x[j])*2) res = max(res, f(slots-1, b^(1<<x[i]))+x[i]) return res return ans+f(rem, sum(x[i]*(1<<i) for i in range(16)))"""
0809bf
a9e907
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4. Return the maximum possible AND sum of nums given numSlots slots.   Example 1: Input: nums = [1,2,3,4,5,6], numSlots = 3 Output: 9 Explanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. This gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9. Example 2: Input: nums = [1,3,10,4,7,1], numSlots = 9 Output: 24 Explanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9. This gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24. Note that slots 2, 5, 6, and 8 are empty which is permitted.   Constraints: n == nums.length 1 <= numSlots <= 9 1 <= n <= 2 * numSlots 1 <= nums[i] <= 15
from collections import Counter from itertools import combinations class Solution(object): def maximumANDSum(self, nums, numSlots): """ :type nums: List[int] :type numSlots: int :rtype: int """ slots = range(1, numSlots+1) * 2 nums += [0]*(len(slots)-len(nums)) cost = [[-(x&y) for y in slots] for x in nums] return -hungarian(cost)[0] def hungarian(orig_cost): n = len(orig_cost) assert all(len(row) == n for row in orig_cost) cost = map(list, orig_cost) for x in xrange(n): min_cost = min(cost[x]) for y in xrange(n): cost[x][y] -= min_cost for y in xrange(n): min_cost = min(cost[x][y] for x in xrange(n)) for x in xrange(n): cost[x][y] -= min_cost match_x = [-1]*n match_y = [-1]*n label_x = [0]*n label_y = [0]*n minx_slack_y = [0]*n min_slack_y = [0]*n seen_x = [False]*n prev_y = [0]*n def _augment(x): for i in xrange(n): seen_x[i] = False prev_y[i] = -1 seen_x[x] = True for y in xrange(n): min_slack_y[y] = cost[x][y] - label_x[x] - label_y[y] minx_slack_y[y] = x while True: min_slack = float('inf') min_x = -1 min_y = -1 for y in xrange(n): if prev_y[y] == -1 and min_slack_y[y] < min_slack: min_slack = min_slack_y[y] min_x = minx_slack_y[y] min_y = y if min_slack > 0: for x in xrange(n): if seen_x[x]: label_x[x] += min_slack for y in xrange(n): if prev_y[y] == -1: min_slack_y[y] -= min_slack else: label_y[y] -= min_slack prev_y[min_y] = min_x if match_y[min_y] == -1: y = min_y while True: x = prev_y[y] nxt = match_x[x] match_x[x] = y match_y[y] = x y = nxt if y == -1: break return x = match_y[min_y] seen_x[x] = True for y in xrange(n): if prev_y[y] == -1: slack = cost[x][y] - label_x[x] - label_y[y] if min_slack_y[y] > slack: min_slack_y[y] = slack minx_slack_y[y] = x # greedy initial match for x in xrange(n): for y in xrange(n): if match_x[x] == -1 and match_y[y] == -1 and cost[x][y] == label_x[x] + label_y[y]: match_x[x] = y match_y[y] = x # augment loop while True: for x in xrange(n): if match_x[x] == -1: _augment(x) break else: break # compute best cost best_cost = sum(orig_cost[x][match_x[x]] for x in xrange(n)) return best_cost, match_x
e34537
5376ba
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.   Example 1: Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1 Output: 6 Explanation: The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2). Example 2: Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1 Output: -1 Explanation: We need to eliminate at least two obstacles to find such a walk.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 40 1 <= k <= m * n grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0
from collections import deque class Solution(object): def shortestPath(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: int """ n, m = len(grid), len(grid[0]) s = [[[False]*(k+1) for j in xrange(m)] for i in xrange(n)] q = deque() def consider(x, y, z, d): if x<0 or x>=n or y<0 or y>=m: return z += grid[x][y] if z>k or s[x][y][z]: return s[x][y][z] = True q.append((x, y, z, d)) consider(0, 0, 0, 0) while q: x, y, z, d = q.popleft() consider(x+1, y, z, d+1) consider(x-1, y, z, d+1) consider(x, y+1, z, d+1) consider(x, y-1, z, d+1) if x==n-1 and y==m-1: return d return -1
234a93
5376ba
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.   Example 1: Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1 Output: 6 Explanation: The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2). Example 2: Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1 Output: -1 Explanation: We need to eliminate at least two obstacles to find such a walk.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 40 1 <= k <= m * n grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0
class Solution: def shortestPath(self, grid: List[List[int]], k: int) -> int: bfs = collections.deque() bfs.append((0, 0, 0, 0)) seen = set() seen.add((0,0,0)) n = len(grid) m = len(grid[0]) while bfs: x, y, has, step = bfs.popleft() if x == n - 1 and y == m - 1: return step for i, j in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): if 0 <= i < n and 0 <= j < m: if grid[i][j] == 1: if (i, j, has + 1) not in seen and has < k: bfs.append((i, j, has + 1, step + 1)) seen.add((i, j, has + 1)) else: if (i, j, has) not in seen: bfs.append((i, j, has, step + 1)) seen.add((i, j, has)) return -1
ef06fe
71dd17
There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1. You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. Return an array ans where ans[i] is the answer to the ith query.   Example 1: Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]] Output: [2,3,7] Explanation: The queries are processed as follows: - [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2. - [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3. - [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7. Example 2: Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]] Output: [6,14,7] Explanation: The queries are processed as follows: - [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6. - [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14. - [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.   Constraints: 2 <= parents.length <= 100000 0 <= parents[i] <= parents.length - 1 for every node i that is not the root. parents[root] == -1 1 <= queries.length <= 3 * 10000 0 <= nodei <= parents.length - 1 0 <= vali <= 2 * 100000
class Solution(object): def maxGeneticDifference(self, parents, queries): """ :type parents: List[int] :type queries: List[List[int]] :rtype: List[int] """ n = len(parents) children = [[] for _ in xrange(n)] for child, par in enumerate(parents): if par == -1: root = child else: children[par].append(child) m = n - 1 q = [[] for _ in xrange(n)] r = [-1] * len(queries) for idx, (node, val) in enumerate(queries): q[node].append((val, idx)) m = max(m, val) m = m.bit_length() sz = [0] * (1<<(m+1)) def _inc(val, d): curr = 1 for i in xrange(m-1, -1, -1): sz[curr] += d j = (val>>i) & 1 curr = (curr<<1)|j sz[curr] += d def _query(val): best = 0 curr = 1 for i in xrange(m-1, -1, -1): j = (val>>i) & 1 ch0 = (curr<<1)|j ch1 = ch0 ^ 1 if sz[ch1] > 0: curr = ch1 best |= 1<<i else: curr = ch0 return best def _dfs(node): _inc(node, 1) for val, idx in q[node]: r[idx] = _query(val) for child in children[node]: _dfs(child) _inc(node, -1) _dfs(root) return r
ed9b00
71dd17
There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1. You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. Return an array ans where ans[i] is the answer to the ith query.   Example 1: Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]] Output: [2,3,7] Explanation: The queries are processed as follows: - [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2. - [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3. - [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7. Example 2: Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]] Output: [6,14,7] Explanation: The queries are processed as follows: - [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6. - [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14. - [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.   Constraints: 2 <= parents.length <= 100000 0 <= parents[i] <= parents.length - 1 for every node i that is not the root. parents[root] == -1 1 <= queries.length <= 3 * 10000 0 <= nodei <= parents.length - 1 0 <= vali <= 2 * 100000
class Solution: def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]: n = len(parents) G = [[] for _ in range(n)] for i, p in enumerate(parents): if p == -1: root = i else: G[p].append(i) m = len(queries) ans = [-1] * m for i in range(m): queries[i].append(i) dic = defaultdict(list) for node, val, i in queries: dic[node].append((val, i)) T = lambda: defaultdict(T) trie = T() def dfs(i): nonlocal trie cur = trie for k in range(17, -1, -1): b = i >> k & 1 if '#' not in cur: cur['#'] = [0, 0] cur['#'][b] += 1 cur = cur[b] for val, idx in dic[i]: tmp = 0 cur = trie for k in range(17, -1, -1): b = val >> k & 1 if cur['#'][1 - b]: tmp |= 1 << k cur = cur[1 - b] else: cur = cur[b] ans[idx] = tmp for j in G[i]: dfs(j) cur = trie for k in range(17, -1, -1): b = i >> k & 1 cur['#'][b] -= 1 cur = cur[b] dfs(root) return ans
b5ea65
093bad
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.   Example 1: Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] Output: 3 Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. Example 2: Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] Output: 0 Explanation: There are exactly three trios: 1) [1,4,3] with degree 0. 2) [2,5,6] with degree 2. 3) [5,6,7] with degree 2.   Constraints: 2 <= n <= 400 edges[i].length == 2 1 <= edges.length <= n * (n-1) / 2 1 <= ui, vi <= n ui != vi There are no repeated edges.
class Solution(object): def minTrioDegree(self, n, edges): graph = defaultdict(set) for u,v in edges: graph[u].add(v) graph[v].add(u) ans = INF = float('inf') for u in graph: for v, w in edges: if v in graph[u] and w in graph[u]: deg = len(graph[u]) + len(graph[v]) + len(graph[w]) deg -= 6 if deg < ans: ans = deg return ans if ans < INF else -1
be11f0
093bad
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.   Example 1: Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] Output: 3 Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. Example 2: Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] Output: 0 Explanation: There are exactly three trios: 1) [1,4,3] with degree 0. 2) [2,5,6] with degree 2. 3) [5,6,7] with degree 2.   Constraints: 2 <= n <= 400 edges[i].length == 2 1 <= edges.length <= n * (n-1) / 2 1 <= ui, vi <= n ui != vi There are no repeated edges.
class Solution: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: deg = [0] * (n+1) adj = [[] for i in range(n+1)] for u,v in edges: deg[u] += 1 deg[v] += 1 adj[u].append(v) adj[v].append(u) adj = [set(s) for s in adj] worst = (n+1)**3 r = worst for u,v in edges: for w in adj[u] & adj[v]: r = min(r, deg[u] + deg[v] + deg[w] - 6) if r >= worst: return -1 else: return r
d85090
d46a7a
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string.   Example 1: Input: word1 = "sea", word2 = "eat" Output: 2 Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". Example 2: Input: word1 = "leetcode", word2 = "etco" Output: 4   Constraints: 1 <= word1.length, word2.length <= 500 word1 and word2 consist of only lowercase English letters.
class Solution(object): def minDistance(self, A, B): memo = {} def dp(i, j): #min steps to make A[i:] and B[j:] the same if i == len(A) or j == len(B): return len(A) - i + len(B) - j if (i,j ) not in memo: if A[i] == B[j]: ans= dp(i+1,j+1) else: ans= 1 + min(dp(i+1, j), dp(i, j+1)) memo[i,j]= ans return memo[i,j] return dp(0, 0)
228c91
d46a7a
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string.   Example 1: Input: word1 = "sea", word2 = "eat" Output: 2 Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". Example 2: Input: word1 = "leetcode", word2 = "etco" Output: 4   Constraints: 1 <= word1.length, word2.length <= 500 word1 and word2 consist of only lowercase English letters.
class Solution: def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ def LCS_(u, v): LCS = [[0 for i in range(len(v)+1)] for j in range(len(u)+1)] for c in range(len(v)-1,-1,-1): for r in range(len(u)-1,-1,-1): if u[r] == v[c]: LCS[r][c] = 1 + LCS[r+1][c+1] else: LCS[r][c] = max(LCS[r][c+1], LCS[r+1][c]) return(LCS[0][0]) l1,l2 = len(word1),len(word2) return(l1+l2-2*LCS_(word1,word2))
add9f7
6b3687
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 <= 100000 root is a perfect binary tree.
# 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]: stuff = defaultdict(list) def dfs(node, d): if node: stuff[d].append(node) dfs(node.left, d+1) dfs(node.right, d+1) dfs(root, 0) for k in stuff: if k & 1: row = stuff[k] vals = [n.val for n in row] vals = vals[::-1] for i, n in enumerate(row): n.val = vals[i] return root
db8c0d
6b3687
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 <= 100000 root is a perfect binary tree.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def reverseOddLevels(self, root): """ :type root: Optional[TreeNode] :rtype: Optional[TreeNode] """ q = [root] f = False while q: if f: i, j = 0, len(q)-1 while i < j: q[i].val, q[j].val = q[j].val, q[i].val i += 1 j -= 1 q = [ch for u in q for ch in (u.left, u.right) if ch is not None] f = not f return root
bc6fc0
6fb1aa
Given an integer array nums, return the number of AND triples. An AND triple is a triple of indices (i, j, k) such that: 0 <= i < nums.length 0 <= j < nums.length 0 <= k < nums.length nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.   Example 1: Input: nums = [2,1,3] Output: 12 Explanation: We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 Example 2: Input: nums = [0,0,0] Output: 27   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < 216
class Solution(object): def countTriplets(self, A): """ :type A: List[int] :rtype: int """ bits = len(bin(max(A))) - 2 bound = 1 << bits collect = [0] * bound for i in A: collect[i] += 1 for j in range(bits): mask = 1 << j for i in range(bound): if i & mask == 0: collect[i] += collect[i ^ mask] return sum((-1 if bin(i).count('1') % 2 else 1) * (collect[i] ** 3) for i in range(bound))
d5caea
6fb1aa
Given an integer array nums, return the number of AND triples. An AND triple is a triple of indices (i, j, k) such that: 0 <= i < nums.length 0 <= j < nums.length 0 <= k < nums.length nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.   Example 1: Input: nums = [2,1,3] Output: 12 Explanation: We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 Example 2: Input: nums = [0,0,0] Output: 27   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < 216
class Solution: def countTriplets(self, A: 'List[int]') -> 'int': d = collections.defaultdict(int) l = len(A) for i in range(l): for j in range(l): d[A[i] & A[j]] += 1 #print(d) out = 0 for i in range(l): for k, v in d.items(): if A[i] & k == 0: out += v return out