sol_id
stringlengths 6
6
| problem_id
stringlengths 6
6
| problem_text
stringlengths 322
4.55k
| solution_text
stringlengths 137
5.74k
|
---|---|---|---|
f30d52 | b2c57e | You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "ababbb"
Output: 9
Explanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Example 2:
Input: s = "zaaaxbbby"
Output: 9
Explanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Constraints:
2 <= s.length <= 100000
s consists of lowercase English letters.
| class Solution:
def maxProduct(self, S: str) -> int:
N = len(S)
def manachers(S):
A = '@#' + '#'.join(S) + '#$'
Z = [0] * len(A)
center = right = 0
for i in range(1, len(A) - 1):
if i < right:
Z[i] = min(right - i, Z[2 * center - i])
while A[i + Z[i] + 1] == A[i - Z[i] - 1]:
Z[i] += 1
if i + Z[i] > right:
center, right = i, i + Z[i]
return Z
A = manachers(S)
B = A[2::2]
B.pop()
def make(B):
furthest = 0
ans = [0] * len(B)
for i, length in enumerate(B):
j = (length >> 1) + i
ans[j] = max(ans[j], length)
for j in range(len(ans) - 2, -1, -1):
ans[j] = max(ans[j], ans[j+1] - 2)
# print("PRE", ans)
for i in range(1, len(ans)):
ans[i] = max(ans[i], ans[i-1])
return ans
# print("B", B)
left = make(B)
right = make(B[::-1])[::-1]
# print(left)
# print(right)
# eve dhkbdhntnhdbkhd 45
# "ggbswiymmlevedhkbdhntnhdbkhdevelmmyiwsbgg"
ans = 0
for i in range(len(left) - 1):
ans = max(ans, left[i] * right[i + 1])
return ans |
1a6bce | b2c57e | You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "ababbb"
Output: 9
Explanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Example 2:
Input: s = "zaaaxbbby"
Output: 9
Explanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Constraints:
2 <= s.length <= 100000
s consists of lowercase English letters.
| class Solution(object):
def maxProduct(self, s):
"""
:type s: str
:rtype: int
"""
T = '$#' + '#'.join(s) + '#@'
l = len(T)
P = [0] * l
R, C = 0, 0
# print(T,P)
for i in range(1,l-1):
if i < R:
P[i] = min(P[2 * C - i], R - i)
while T[i+(P[i]+1)] == T[i-(P[i]+1)]:
P[i] += 1
if P[i] + i > R:
R = P[i] + i
C = i
arr = []
for i in range(len(T)):
if T[i].isalpha():
arr.append(P[i])
presum = [1 for _ in range(len(s))]
for i in range(len(s)):
presum[i+(arr[i]-1)//2] = max(presum[i+(arr[i]-1)//2],arr[i])
# print(presum)
for i in range(len(s)-2,-1,-1):
presum[i] = max(presum[i],presum[i+1]-2)
# print(presum)
for i in range(len(presum)-1):
presum[i+1] = max(presum[i],presum[i+1])
post = [1 for _ in range(len(s))]
for i in range(len(s)-1,-1,-1):
post[i-(arr[i]-1)//2] = max(post[i-(arr[i]-1)//2],arr[i])
# print(post)
for i in range(1,len(s)):
post[i] = max(post[i],post[i-1]-2)
# print(post)
post = post[1:]+[0]
# print(post)
for i in range(len(s)-1,0,-1):
post[i-1] = max(post[i-1],post[i])
# print(presum,post)
res = 0
for i in range(len(presum)):
res = max(res,presum[i]*post[i])
return res
|
66e1e8 | 85fe8a | You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.
Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
Example 1:
Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
Example 2:
Input: img1 = [[1]], img2 = [[1]]
Output: 1
Example 3:
Input: img1 = [[0]], img2 = [[0]]
Output: 0
Constraints:
n == img1.length == img1[i].length
n == img2.length == img2[i].length
1 <= n <= 30
img1[i][j] is either 0 or 1.
img2[i][j] is either 0 or 1.
| class Solution:
def largestOverlap(self, A, B):
N = len(A)
import numpy as np
A, B = np.array(A), np.array(B)
ret = 0
for i in range(N):
for j in range(N):
if (N-i)*(N-j)<=ret:
continue
ret = max(ret, np.sum(A[i:,j:]&B[:N-i, :N-j]))
ret = max(ret, np.sum(B[i:,j:]&A[:N-i, :N-j]))
return int(ret) |
72b4b4 | 85fe8a | You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.
Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
Example 1:
Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
Example 2:
Input: img1 = [[1]], img2 = [[1]]
Output: 1
Example 3:
Input: img1 = [[0]], img2 = [[0]]
Output: 0
Constraints:
n == img1.length == img1[i].length
n == img2.length == img2[i].length
1 <= n <= 30
img1[i][j] is either 0 or 1.
img2[i][j] is either 0 or 1.
| class Solution(object):
def largestOverlap(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: int
"""
def countbits(a):
r = 0
while a > 0:
if (a & 1) > 0:
r += 1
a >>= 1
return r
def convert(a):
r = 0
for aa in a:
r <<= 1
if aa:
r += 1
return r
n = len(A)
for i in range(n):
A[i] = convert(A[i])
B[i] = convert(B[i])
best = 0
for bx in range(-n + 1, n):
for by in range(-n + 1, n):
cur = 0
for y in range(n):
if 0 <= y + by < n:
curB = B[y + by]
if bx < 0:
curB <<= -bx
elif bx > 0:
curB >>= bx
cur += countbits(curB & A[y])
best = max(best, cur)
return best |
488b3a | 796718 | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:
floor[i] = '0' denotes that the ith tile of the floor is colored black.
On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.
You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.
Return the minimum number of white tiles still visible.
Example 1:
Input: floor = "10110101", numCarpets = 2, carpetLen = 2
Output: 2
Explanation:
The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.
No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.
Example 2:
Input: floor = "11111", numCarpets = 2, carpetLen = 3
Output: 0
Explanation:
The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.
Note that the carpets are able to overlap one another.
Constraints:
1 <= carpetLen <= floor.length <= 1000
floor[i] is either '0' or '1'.
1 <= numCarpets <= 1000
| class Solution:
def minimumWhiteTiles(self, floor: str, xx: int, cc: int) -> int:
pre = [0]
N = len(floor)
for i in range(N):
if floor[i] == '1':
pre.append(pre[-1] + 1)
else:
pre.append(pre[-1])
@cache
def cal(i, j):
if i < 0:
return 0
if j == 0:
return pre[i + 1]
return min(cal(i - 1, j) + (1 if floor[i] == '1' else 0), cal(i - cc, j - 1))
return cal(N - 1, xx)
|
ff34cb | 796718 | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:
floor[i] = '0' denotes that the ith tile of the floor is colored black.
On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.
You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.
Return the minimum number of white tiles still visible.
Example 1:
Input: floor = "10110101", numCarpets = 2, carpetLen = 2
Output: 2
Explanation:
The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.
No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.
Example 2:
Input: floor = "11111", numCarpets = 2, carpetLen = 3
Output: 0
Explanation:
The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.
Note that the carpets are able to overlap one another.
Constraints:
1 <= carpetLen <= floor.length <= 1000
floor[i] is either '0' or '1'.
1 <= numCarpets <= 1000
| class Solution(object):
def minimumWhiteTiles(self, A, k, l):
A = [int(c) for c in A]
n = len(A)
memo = {}
def dp(i, k):
if (i, k) in memo:
return memo[i,k]
if i >= n: return 0
if k == 0:
res = sum(A[i] for i in xrange(i, n))
elif A[i] == 0:
res = dp(i + 1, k)
else:
res = min(1 + dp(i+1, k), dp(i+l, k-1))
memo[i, k] = res
return res
res = dp(0, k)
return res |
7d5866 | e53ecc | You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.
Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7. Note that you should maximize the product before taking the modulo.
Example 1:
Input: nums = [0,4], k = 5
Output: 20
Explanation: Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
Example 2:
Input: nums = [6,3,3,2], k = 2
Output: 216
Explanation: Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
Constraints:
1 <= nums.length, k <= 100000
0 <= nums[i] <= 1000000
| class Solution(object):
def maximumProduct(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
q, r = [], 1
for n in nums:
heappush(q, n)
while k > 0:
heappush(q, heappop(q) + 1)
k -= 1
for n in q:
r = r * n % 1000000007
return r |
83eefe | e53ecc | You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.
Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7. Note that you should maximize the product before taking the modulo.
Example 1:
Input: nums = [0,4], k = 5
Output: 20
Explanation: Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
Example 2:
Input: nums = [6,3,3,2], k = 2
Output: 216
Explanation: Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
Constraints:
1 <= nums.length, k <= 100000
0 <= nums[i] <= 1000000
| from sortedcontainers import SortedList
class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
MOD = 10 ** 9 + 7
nums = SortedList(nums)
for i in range(k):
x = nums.pop(0)
nums.add(x + 1)
ans = 1
for x in nums:
ans *= x
ans %= MOD
return ans % MOD |
7aebb0 | f20ecf | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
Output: [true,true]
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
All the pairs [ai, bi] are unique.
The prerequisites graph has no cycles.
1 <= queries.length <= 10000
0 <= ui, vi <= n - 1
ui != vi
| class Solution(object):
def checkIfPrerequisite(self, n, prerequisites, queries):
"""
:type n: int
:type prerequisites: List[List[int]]
:type queries: List[List[int]]
:rtype: List[bool]
"""
graph = [[] for _ in xrange(n)]
for u, v in prerequisites:
# need u to do v
graph[u].append(v)
ans = []
for qs, qt in queries:
stack = [qs]
seen = {qs}
while stack:
node = stack.pop()
if node == qt:
ans.append(True)
break
for nei in graph[node]:
if nei not in seen:
stack.append(nei)
seen.add(nei)
else:
ans.append(False)
return ans
|
ce7a0a | f20ecf | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
Output: [true,true]
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
All the pairs [ai, bi] are unique.
The prerequisites graph has no cycles.
1 <= queries.length <= 10000
0 <= ui, vi <= n - 1
ui != vi
|
class Solution:
def checkIfPrerequisite(self, n, prerequisites, queries):
admat = []
for i in range(n):
admat.append([False]*n)
for u, v in prerequisites:
admat[u][v] = True
for k in range(n):
for i in range(n):
for j in range(n):
admat[i][j] = admat[i][j] or (admat[i][k] and admat[k][j])
return [admat[u][v] for u,v in queries] |
214b62 | 7b8284 | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:
Input: n = 1, edges = []
Output: [0]
Example 3:
Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints:
1 <= n <= 3 * 10000
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
The given input represents a valid tree.
| class Solution:
def sumOfDistancesInTree(self, N, edges):
dic1 = collections.defaultdict(list)
for e in edges:
dic1[e[0]].append(e[1])
dic1[e[1]].append(e[0])
exclude = {0}
ans1 = [[0, 0] for _ in range(N)]
ans2 = [0]*N
def sumDist(n, exclude):
cnt, ret = 0, 0
exclude.add(n)
for x in dic1[n]:
if x in exclude:
continue
res = sumDist(x, exclude)
cnt += res[0]
ret += (res[0]+res[1])
ans1[n][0] = cnt+1
ans1[n][1] = ret
return cnt+1, ret
sumDist(0, set())
def visit(n, pre, exclude):
if pre==-1:
ans2[n] = ans1[n][1]
else:
ans2[n] = ans2[pre]-2*ans1[n][0]+N
exclude.add(n)
for x in dic1[n]:
if x not in exclude:
visit(x, n, exclude)
visit(0, -1, set())
return ans2 |
88209e | 7b8284 | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:
Input: n = 1, edges = []
Output: [0]
Example 3:
Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints:
1 <= n <= 3 * 10000
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
The given input represents a valid tree.
| class Solution(object):
def sumOfDistancesInTree(self, N, edges):
"""
:type N: int
:type edges: List[List[int]]
:rtype: List[int]
"""
memo = {}
e = collections.defaultdict(list)
for a, b in edges:
e[a].append(b)
e[b].append(a)
def find(a, b):
if (a, b) in memo:
return memo[(a, b)]
count = 0
lensum = 0
for c in e[b]:
if c == a: continue
cc, cls = find(b, c)
count += cc
lensum += cls
count += 1
lensum += count
r = (count, lensum)
memo[(a, b)] = r
return r
r = []
for i in range(N):
lensum = 0
for c in e[i]:
cc, cls = find(i, c)
lensum += cls
r.append(lensum)
return r
|
115a89 | 154c1f | There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.
Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:
Assuming that on a day, you visit room i,
if you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;
if you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.
Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nextVisit = [0,0]
Output: 2
Explanation:
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit[0] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
Example 2:
Input: nextVisit = [0,0,2]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,0,0,1,2,...].
Day 6 is the first day where you have been in all the rooms.
Example 3:
Input: nextVisit = [0,1,2,0]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,1,2,2,3,...].
Day 6 is the first day where you have been in all the rooms.
Constraints:
n == nextVisit.length
2 <= n <= 100000
0 <= nextVisit[i] <= i
| class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
mod = 10 ** 9 + 7
n = len(nextVisit)
dp = [0] * n
dp[1] = 2
for i in range(2, n):
j = nextVisit[i - 1]
dp[i] = dp[i - 1] + 1 + dp[i - 1] - dp[j] + 1
dp[i] %= mod
return dp[-1]
|
4c0ec9 | 154c1f | There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.
Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:
Assuming that on a day, you visit room i,
if you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;
if you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.
Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nextVisit = [0,0]
Output: 2
Explanation:
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit[0] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
Example 2:
Input: nextVisit = [0,0,2]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,0,0,1,2,...].
Day 6 is the first day where you have been in all the rooms.
Example 3:
Input: nextVisit = [0,1,2,0]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,1,2,2,3,...].
Day 6 is the first day where you have been in all the rooms.
Constraints:
n == nextVisit.length
2 <= n <= 100000
0 <= nextVisit[i] <= i
| class Solution(object):
def firstDayBeenInAllRooms(self, nextVisit):
"""
:type nextVisit: List[int]
:rtype: int
"""
mod = 10**9 + 7
a = nextVisit
n = len(a)
f = [0] * (n+1)
for i in xrange(n):
f[i+1] = (2 + 2*f[i] - f[a[i]]) % mod
return f[n-1] |
008576 | 5057a8 | Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
"directory_path/file_name.txt"
Example 1:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Example 2:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Constraints:
1 <= paths.length <= 2 * 10000
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 100000
paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
You may assume no files or directories share the same name in the same directory.
You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
Follow up:
Imagine you are given a real file system, how will you search files? DFS or BFS?
If the file content is very large (GB level), how will you modify your solution?
If you can only read the file by 1kb each time, how will you modify your solution?
What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
How to make sure the duplicated files you find are not false positive?
| import re
FILE_RE = re.compile(r'(.*)\((.*)\)')
class Solution(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
data = {}
for p in paths:
files = p.split()
directory = files.pop(0)
for file in files:
filename, content = FILE_RE.match(file).groups()
filepath = '%s/%s' % (directory, filename)
data.setdefault(content, []).append(filepath)
return [v for v in data.itervalues() if len(v) > 1] |
016ab3 | 5057a8 | Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
"directory_path/file_name.txt"
Example 1:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Example 2:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Constraints:
1 <= paths.length <= 2 * 10000
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 100000
paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
You may assume no files or directories share the same name in the same directory.
You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
Follow up:
Imagine you are given a real file system, how will you search files? DFS or BFS?
If the file content is very large (GB level), how will you modify your solution?
If you can only read the file by 1kb each time, how will you modify your solution?
What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
How to make sure the duplicated files you find are not false positive?
| class Solution:
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for path in paths:
directory, files = path.split(' ', 1)
for file in files.split():
filename, h = file.split('(')
d[h].append(directory+'/'+filename)
return [t for t in d.values() if len(t)>1] |
4e65b8 | 6b7b97 | In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect all the gold in that cell.
From your position, you can walk one step to the left, right, up, or down.
You can't visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
There are at most 25 cells containing gold.
| class Solution(object):
def getMaximumGold(self, A):
R, C = len(A), len(A[0])
self.ans = 0
def neighbors(r, c):
for nr, nc in ((r-1,c),(r,c-1), (r+1, c), (r, c+1)):
if 0 <=nr<R and 0<=nc<C:
yield nr, nc
def search(r, c):
for nr, nc in neighbors(r, c):
if A[nr][nc]:
v = A[nr][nc]
A[nr][nc] = 0
self.bns += v
if self.bns > self.ans:
self.ans = self.bns
search(nr, nc)
A[nr][nc] = v
self.bns -= v
for r in xrange(R):
for c in xrange(C):
if A[r][c]:
self.bns = v = A[r][c]
if self.bns > self.ans: self.ans = self.bns
A[r][c] = 0
search(r, c)
A[r][c] = v
return self.ans
|
98dd50 | 6b7b97 | In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect all the gold in that cell.
From your position, you can walk one step to the left, right, up, or down.
You can't visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
There are at most 25 cells containing gold.
| class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
maxx = 0
R, C = len(grid), len(grid[0])
def dfs(r, c, visited, count):
nonlocal maxx
count += grid[r][c]
maxx = max(maxx, count)
visited.add((r, c))
for nr, nc in [[r+1, c], [r, c+1], [r-1, c], [r, c-1]]:
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != 0 and (nr, nc) not in visited:
dfs(nr, nc, visited, count)
visited.remove((r, c))
count -= grid[r][c]
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 0:
dfs(r, c, set(), 0)
return maxx |
a51c35 | 33d0d5 | Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it does from right to left.
For example, 101 and 12321 are palindromes.
The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8].
Example 1:
Input: n = 6
Output: 7
Example 2:
Input: n = 8
Output: 11
Example 3:
Input: n = 13
Output: 101
Constraints:
1 <= n <= 10^8
| class Solution(object):
def ndigs(self, N):
d = 0
while N > 0:
d += 1
N /= 10
return d
def is_prime(self, v):
if v == 1:
return False
i = 2
while i*i <= v:
if v%i == 0:
return False
i += 1
return True
def get_pals(self, ndigs, n):
if ndigs % 2 == 0:
nd = ndigs/2
if ndigs > len(str(n)):
start = 10**(nd-1)
else:
start = int(str(n)[:nd])
for i in xrange(start, 10**nd):
si = str(i)
v = int(si + si[::-1])
if v < n:
continue
if self.is_prime(v):
return v
else:
nd = ndigs/2 + 1
if ndigs > len(str(n)):
start = 10**(nd-1)
else:
start = int(str(n)[:nd])
for i in xrange(start, 10**nd):
si = str(i)
v = int(si[:-1] + si[::-1])
if v < n:
continue
if self.is_prime(v):
return v
return None
def primePalindrome(self, N):
"""
:type N: int
:rtype: int
"""
nd = self.ndigs(N)
while True:
ret = self.get_pals(nd, N)
if ret is not None:
return ret
nd += 1
|
c4c004 | 33d0d5 | Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it does from right to left.
For example, 101 and 12321 are palindromes.
The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8].
Example 1:
Input: n = 6
Output: 7
Example 2:
Input: n = 8
Output: 11
Example 3:
Input: n = 13
Output: 101
Constraints:
1 <= n <= 10^8
| class Solution:
PRIMES = []
MAXPRIME = 65535
def gen_primes():
a = [True] * (Solution.MAXPRIME + 1)
a[0] = a[1] = False
for i in range(2, int(Solution.MAXPRIME ** 0.5)+1):
for j in range(i * i, Solution.MAXPRIME + 1, i):
a[j] = False
Solution.PRIMES = [i for i in range(2, Solution.MAXPRIME + 1) if a[i]]
def primePalindrome(self, N):
"""
:type N: int
:rtype: int
"""
if not Solution.PRIMES:
Solution.gen_primes()
primes = Solution.PRIMES
def isPrime(n):
for p in primes:
if p * p > n: break
if n % p == 0: return False
return True
if N <= 11:
for p in primes:
if p >= N: return p
elif N <= 101:
return 101
def get_p(n):
sn = str(n)
s = sn + sn[-2::-1]
return int(s)
sN = str(N)
if len(sN) % 2:
st = int(sN[:(len(sN)+1)//2])
if get_p(st) < N: st += 1
else:
st = 10 ** (len(sN)//2)
while True:
n = get_p(st)
if isPrime(n): return n
st += 1
|
33a2bf | dc49ef | You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.
Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.
Return the minimum number of magic beans that you have to remove.
Example 1:
Input: beans = [4,1,6,5]
Output: 4
Explanation:
- We remove 1 bean from the bag with only 1 bean.
This results in the remaining bags: [4,0,6,5]
- Then we remove 2 beans from the bag with 6 beans.
This results in the remaining bags: [4,0,4,5]
- Then we remove 1 bean from the bag with 5 beans.
This results in the remaining bags: [4,0,4,4]
We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.
There are no other solutions that remove 4 beans or fewer.
Example 2:
Input: beans = [2,10,3,2]
Output: 7
Explanation:
- We remove 2 beans from one of the bags with 2 beans.
This results in the remaining bags: [0,10,3,2]
- Then we remove 2 beans from the other bag with 2 beans.
This results in the remaining bags: [0,10,3,0]
- Then we remove 3 beans from the bag with 3 beans.
This results in the remaining bags: [0,10,0,0]
We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.
There are no other solutions that removes 7 beans or fewer.
Constraints:
1 <= beans.length <= 100000
1 <= beans[i] <= 100000
| class Solution:
def minimumRemoval(self, a: List[int]) -> int:
a.sort()
s = sum(a)
t = 0
z = s
for i in range(len(a)):
z = min(z, t + s - (len(a) - i) * a[i])
s -= a[i]
t += a[i]
return z |
32f370 | dc49ef | You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.
Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.
Return the minimum number of magic beans that you have to remove.
Example 1:
Input: beans = [4,1,6,5]
Output: 4
Explanation:
- We remove 1 bean from the bag with only 1 bean.
This results in the remaining bags: [4,0,6,5]
- Then we remove 2 beans from the bag with 6 beans.
This results in the remaining bags: [4,0,4,5]
- Then we remove 1 bean from the bag with 5 beans.
This results in the remaining bags: [4,0,4,4]
We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.
There are no other solutions that remove 4 beans or fewer.
Example 2:
Input: beans = [2,10,3,2]
Output: 7
Explanation:
- We remove 2 beans from one of the bags with 2 beans.
This results in the remaining bags: [0,10,3,2]
- Then we remove 2 beans from the other bag with 2 beans.
This results in the remaining bags: [0,10,3,0]
- Then we remove 3 beans from the bag with 3 beans.
This results in the remaining bags: [0,10,0,0]
We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.
There are no other solutions that removes 7 beans or fewer.
Constraints:
1 <= beans.length <= 100000
1 <= beans[i] <= 100000
| class Solution(object):
def minimumRemoval(self, beans):
"""
:type beans: List[int]
:rtype: int
"""
a = sorted(beans)
r = s = sum(a)
n = len(a)
for i, v in enumerate(a):
r = min(r, s - v*(n-i))
return r |
0f97d3 | 9297a0 | Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists.
Example 1:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
Example 2:
Input: root = [1]
Output: 0
Constraints:
The number of nodes in the tree is in the range [1, 10000].
1 <= Node.val <= 100
| # 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 sumEvenGrandparent(self, root):
self.ans = 0
def dfs(node, pval = -1, ppval = -1):
if node:
if ppval % 2 == 0:
self.ans += node.val
dfs(node.left, node.val, pval)
dfs(node.right, node.val, pval)
dfs(root)
return self.ans |
6d57f8 | 9297a0 | Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists.
Example 1:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
Example 2:
Input: root = [1]
Output: 0
Constraints:
The number of nodes in the tree is in the range [1, 10000].
1 <= Node.val <= 100
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(node, parent, grandparent, values):
if not node:
return
if grandparent and not grandparent.val % 2:
values.append(node.val)
dfs(node.left, node, parent, values)
dfs(node.right, node, parent, values)
values = []
dfs(root, None, None, values)
return sum(values)
|
c9ac31 | 48088e | Given the root of a binary tree, return the length of the longest consecutive path in the tree.
A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.
For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.
On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
Example 1:
Input: root = [1,2,3]
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].
Example 2:
Input: root = [2,1,3]
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
Constraints:
The number of nodes in the tree is in the range [1, 3 * 10000].
-3 * 10000 <= Node.val <= 3 * 10000
| # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def solve(x):
if x is None: return (0,0,0)
lfinc, lfdec, lfans = (0,0,0) if x.left is None else solve(x.left)
rtinc, rtdec, rtans = (0,0,0) if x.right is None else solve(x.right)
inc = 1 + max(0 if x.left is None or x.left.val != x.val+1 else lfinc, 0 if x.right is None or x.right.val != x.val+1 else rtinc)
dec = 1 + max(0 if x.left is None or x.left.val != x.val-1 else lfdec, 0 if x.right is None or x.right.val != x.val-1 else rtdec)
ans = max(inc+dec-1, max(lfans,rtans))
return (inc,dec,ans)
class Solution(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
_, __, ans = solve(root)
return ans |
991812 | a9f843 | You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k.
The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.
Return the maximum tastiness of a candy basket.
Example 1:
Input: price = [13,5,1,8,21,2], k = 3
Output: 8
Explanation: Choose the candies with the prices [13,5,21].
The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8.
It can be proven that 8 is the maximum tastiness that can be achieved.
Example 2:
Input: price = [1,3,1], k = 2
Output: 2
Explanation: Choose the candies with the prices [1,3].
The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2.
It can be proven that 2 is the maximum tastiness that can be achieved.
Example 3:
Input: price = [7,7,7,7], k = 2
Output: 0
Explanation: Choosing any two distinct candies from the candies we have will result in a tastiness of 0.
Constraints:
2 <= k <= price.length <= 100000
1 <= price[i] <= 10^9
| class Solution(object):
def maximumTastiness(self, price, k):
"""
:type price: List[int]
:type k: int
:rtype: int
"""
def i(d, k):
l, k = price[0], k - 1
for i in range(1, len(price)):
l, k = price[i] if price[i] >= l + d else l, k - 1 if price[i] >= l + d else k
return k <= 0
price.sort()
l, r = 0, 1000000007
while l < r:
l, r = (l + r + 1) / 2 if i((l + r + 1) / 2, k) else l, r if i((l + r + 1) / 2, k) else (l + r + 1) / 2 - 1
return l |
9f4de1 | a9f843 | You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k.
The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.
Return the maximum tastiness of a candy basket.
Example 1:
Input: price = [13,5,1,8,21,2], k = 3
Output: 8
Explanation: Choose the candies with the prices [13,5,21].
The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8.
It can be proven that 8 is the maximum tastiness that can be achieved.
Example 2:
Input: price = [1,3,1], k = 2
Output: 2
Explanation: Choose the candies with the prices [1,3].
The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2.
It can be proven that 2 is the maximum tastiness that can be achieved.
Example 3:
Input: price = [7,7,7,7], k = 2
Output: 0
Explanation: Choosing any two distinct candies from the candies we have will result in a tastiness of 0.
Constraints:
2 <= k <= price.length <= 100000
1 <= price[i] <= 10^9
| class Solution:
def maximumTastiness(self, A, k):
n = len(A)
A.sort()
l, r = 0, A[-1] - A[0]
while l < r:
m = (l + r + 1) // 2
c = 0
cur = -inf
for a in A:
if a >= cur + m:
c += 1
cur = a
if c >= k:
l = m
else:
r = m - 1
return l
|
87dd11 | 678517 | There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Example 1:
Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6
Output: 20190301
Explanation:
The first event occurs at timestamp = 20190101, and after 0 and 1 become friends, we have the following friendship groups [0,1], [2], [3], [4], [5].
The second event occurs at timestamp = 20190104, and after 3 and 4 become friends, we have the following friendship groups [0,1], [2], [3,4], [5].
The third event occurs at timestamp = 20190107, and after 2 and 3 become friends, we have the following friendship groups [0,1], [2,3,4], [5].
The fourth event occurs at timestamp = 20190211, and after 1 and 5 become friends, we have the following friendship groups [0,1,5], [2,3,4].
The fifth event occurs at timestamp = 20190224, and as 2 and 4 are already friends, nothing happens.
The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends, we all become friends.
Example 2:
Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
Output: 3
Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends.
Constraints:
2 <= n <= 100
1 <= logs.length <= 10000
logs[i].length == 3
0 <= timestampi <= 10^9
0 <= xi, yi <= n - 1
xi != yi
All the values timestampi are unique.
All the pairs (xi, yi) occur at most one time in the input.
| class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
# Solution
class Solution:
def earliestAcq(self, logs: List[List[int]], N: int) -> int:
uf = DisjointSetUnion(N)
logs.sort()
for t, a, b in logs:
uf.union(a, b)
if uf.num_sets == 1:
return t
return -1 |
44134f | 678517 | There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Example 1:
Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6
Output: 20190301
Explanation:
The first event occurs at timestamp = 20190101, and after 0 and 1 become friends, we have the following friendship groups [0,1], [2], [3], [4], [5].
The second event occurs at timestamp = 20190104, and after 3 and 4 become friends, we have the following friendship groups [0,1], [2], [3,4], [5].
The third event occurs at timestamp = 20190107, and after 2 and 3 become friends, we have the following friendship groups [0,1], [2,3,4], [5].
The fourth event occurs at timestamp = 20190211, and after 1 and 5 become friends, we have the following friendship groups [0,1,5], [2,3,4].
The fifth event occurs at timestamp = 20190224, and as 2 and 4 are already friends, nothing happens.
The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends, we all become friends.
Example 2:
Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
Output: 3
Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends.
Constraints:
2 <= n <= 100
1 <= logs.length <= 10000
logs[i].length == 3
0 <= timestampi <= 10^9
0 <= xi, yi <= n - 1
xi != yi
All the values timestampi are unique.
All the pairs (xi, yi) occur at most one time in the input.
| class Solution(object):
def earliestAcq(self, logs, N):
"""
:type logs: List[List[int]]
:type N: int
:rtype: int
"""
uf = {}
for x in xrange(N):
uf[x] = x
self.groups = N
def merge(x, y):
x,y = find(x),find(y)
if x != y:
self.groups -= 1
uf[find(x)] = find(y)
def find(x):
if uf[x] != x:
uf[x] = find(uf[x])
return uf[x]
for t,x,y in sorted(logs):
merge(x,y)
if self.groups == 1:
return t
return -1
|
f6116d | 521b64 | There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.
Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
Example 2:
Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
Constraints:
1 <= n <= 100
0 <= minProfit <= 100
1 <= group.length <= 100
1 <= group[i] <= 100
profit.length == group.length
0 <= profit[i] <= 100
| class Solution(object):
def profitableSchemes(self, G, P, group, profit):
"""
:type G: int
:type P: int
:type group: List[int]
:type profit: List[int]
:rtype: int
"""
# f(g, p) = number of schemes generate exactly p profit using exactly g gang members
# update to consider crime i:
# f(g, p) := f(g - group[i], p - profit[i])
M = 10**9 + 7
w = [[0 for _ in xrange(P+1)] for _ in xrange(G+1)]
w[0][0] = 1
for i in xrange(len(group)):
for g in xrange(G - group[i], -1, -1):
ng = g + group[i]
for p in xrange(P, -1, -1):
if not w[g][p]: continue
np = min(P, p + profit[i])
w[ng][np] = (w[ng][np] + w[g][p]) % M
return sum(w[g][P] for g in xrange(G+1)) % M |
efdc81 | 521b64 | There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.
Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
Example 2:
Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
Constraints:
1 <= n <= 100
0 <= minProfit <= 100
1 <= group.length <= 100
1 <= group[i] <= 100
profit.length == group.length
0 <= profit[i] <= 100
| class Solution:
def profitableSchemes(self, G, P, group, profit):
"""
:type G: int
:type P: int
:type group: List[int]
:type profit: List[int]
:rtype: int
"""
f = [dict() for _ in range(G + 1)]
f[G][0] = 1
for i in range(len(group)):
for weight in range(group[i], G + 1):
for total in f[weight]:
newWeight = weight - group[i]
newProfit = min(total + profit[i], P)
if newProfit in f[newWeight]:
f[newWeight][newProfit] = (f[newWeight][newProfit] + f[weight][total]) % (10 ** 9 + 7)
else:
f[newWeight][newProfit] = f[weight][total] % (10 ** 9 + 7)
result = 0
for i in range(G + 1):
if P in f[i]:
result = (result + f[i][P]) % (10 ** 9 + 7)
return result |
3b0a90 | 7c19a9 | You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].
You play a game with the following rules:
You start eating candies on day 0.
You cannot eat any candy of type i unless you have eaten all candies of type i - 1.
You must eat at least one candy per day until you have eaten all the candies.
Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.
Return the constructed array answer.
Example 1:
Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
Output: [true,false,true]
Explanation:
1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
2- You can eat at most 4 candies each day.
If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.
Example 2:
Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
Output: [false,true,true,false,false]
Constraints:
1 <= candiesCount.length <= 100000
1 <= candiesCount[i] <= 100000
1 <= queries.length <= 100000
queries[i].length == 3
0 <= favoriteTypei < candiesCount.length
0 <= favoriteDayi <= 10^9
1 <= dailyCapi <= 10^9
| class Solution(object):
def canEat(self, candiesCount, queries):
"""
:type candiesCount: List[int]
:type queries: List[List[int]]
:rtype: List[bool]
"""
s = [0]
for c in candiesCount:
s.append(s[-1] + c)
def answer(t, d, cap):
max_before = d * cap
min_before = d
min_eaten = s[t] - (cap-1)
max_eaten = s[t+1] - 1
return max_before >= min_eaten and min_before <= max_eaten
return [answer(t, d, c) for t, d, c in queries] |
1ccacf | 7c19a9 | You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].
You play a game with the following rules:
You start eating candies on day 0.
You cannot eat any candy of type i unless you have eaten all candies of type i - 1.
You must eat at least one candy per day until you have eaten all the candies.
Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.
Return the constructed array answer.
Example 1:
Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
Output: [true,false,true]
Explanation:
1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
2- You can eat at most 4 candies each day.
If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.
Example 2:
Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
Output: [false,true,true,false,false]
Constraints:
1 <= candiesCount.length <= 100000
1 <= candiesCount[i] <= 100000
1 <= queries.length <= 100000
queries[i].length == 3
0 <= favoriteTypei < candiesCount.length
0 <= favoriteDayi <= 10^9
1 <= dailyCapi <= 10^9
|
class Solution:
def canEat(self, cc: List[int], queries: List[List[int]]) -> List[bool]:
a = [0]
for i in range(0, len(cc)):
a.append(a[-1] + cc[i])
print(a)
res = []
for q in queries:
if (q[1] + 1) * q[2] <= a[q[0]] or q[1] + 1 > a[q[0] + 1]:
res.append(False)
else:
res.append(True)
return res |
1919e8 | 4a6f20 | You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.
You can perform the following operation at most maxOperations times:
Take any bag of balls and divide it into two new bags with a positive number of balls.
For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.
Return the minimum possible penalty after performing the operations.
Example 1:
Input: nums = [9], maxOperations = 2
Output: 3
Explanation:
- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
Example 2:
Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
Explanation:
- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.
Constraints:
1 <= nums.length <= 100000
1 <= maxOperations, nums[i] <= 10^9
| class Solution(object):
def minimumSize(self, A, maxOperations):
def make(bound):
if bound == 0: return False
ops = 0
for x in A:
q, r = divmod(x, bound)
if r == 0:
ops += q - 1
else:
ops += q
return ops <= maxOperations
# print([make(b) for b in range(1, 5)])
lo, hi = 0, max(A)
while lo < hi:
mi = lo + hi >> 1
if not make(mi):
lo = mi + 1
else:
hi = mi
return lo |
4b88d6 | 4a6f20 | You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.
You can perform the following operation at most maxOperations times:
Take any bag of balls and divide it into two new bags with a positive number of balls.
For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.
Return the minimum possible penalty after performing the operations.
Example 1:
Input: nums = [9], maxOperations = 2
Output: 3
Explanation:
- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
Example 2:
Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
Explanation:
- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.
Constraints:
1 <= nums.length <= 100000
1 <= maxOperations, nums[i] <= 10^9
| class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
lo = 1
hi = max(nums)
while lo <= hi:
mid = (lo + hi) // 2
tot = 0
for num in nums:
tot += (num - 1) // mid
if tot <= maxOperations:
hi = mid - 1
else:
lo = mid + 1
return lo |
149de2 | ab7244 | There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.
Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7.
Example 1:
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6
Example 2:
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
Constraints:
1 <= m, n <= 50
0 <= maxMove <= 50
0 <= startRow < m
0 <= startColumn < n
| class Solution(object):
def findPaths(self, R, C, N, sr, sc):
#RxC grid , make N moves
#start at sr, sc
def neighbors(r, c):
for cr, cc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1)):
yield cr, cc
def legal(r, c):
return 0 <= r < R and 0 <= c < C
MOD = 10**9 +7
dp = [[0] * C for _ in xrange(R)]
dp[sr][sc] = 1
ans = 0
for move in xrange(N):
new = [[0] * C for _ in xrange(R)]
for r, row in enumerate(dp):
for c, val in enumerate(row):
for nr, nc in neighbors(r, c):
if legal(nr, nc):
new[nr][nc] += val
if new[nr][nc] >= MOD:
new[nr][nc] %= MOD
else:
ans += val
if ans >= MOD:
ans %= MOD
dp = new
return ans |
87a150 | c7780b | Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
Constraints:
1 <= arr.length <= 100000
-10000 <= arr[i] <= 10000
| class Solution:
def maximumSum(self, arr: List[int]) -> int:
mwc = []
ms = []
r = max(arr)
if r < 0:
return r
for n in arr:
if not mwc:
mwc.append(n)
ms.append(0)
else:
ms.append(max(ms[-1] + n, mwc[-1]))
mwc.append(max(n, n + mwc[-1]))
r = max([r, ms[-1], mwc[-1]])
return r |
f60324 | c7780b | Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
Constraints:
1 <= arr.length <= 100000
-10000 <= arr[i] <= 10000
| class Solution(object):
def maximumSum(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
b = s = 0
pre = []
for i in arr:
s += i
pre.append(s - b)
b = min(b, s)
b = s = 0
suf = []
for i in reversed(arr):
s += i
suf.append(s - b)
b = min(b, s)
suf.reverse()
r = max(pre)
for i in xrange(1, len(arr) - 1):
r = max(r, pre[i-1] + suf[i+1])
return r |
1e90f8 | e27ac5 | There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.
Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.
A subpath of a path is a contiguous sequence of cities within that path.
Example 1:
Input: n = 5, paths = [[0,1,2,3,4],
[2,3,4],
[4,0,1,2,3]]
Output: 2
Explanation: The longest common subpath is [2,3].
Example 2:
Input: n = 3, paths = [[0],[1],[2]]
Output: 0
Explanation: There is no common subpath shared by the three paths.
Example 3:
Input: n = 5, paths = [[0,1,2,3,4],
[4,3,2,1,0]]
Output: 1
Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
Constraints:
1 <= n <= 100000
m == paths.length
2 <= m <= 100000
sum(paths[i].length) <= 100000
0 <= paths[i][j] < n
The same city is not listed multiple times consecutively in paths[i].
| class Rabin_Karp:
def single_rolling_hash_nums(self, arr, k, p = 113, MOD = 10**9+7):
"""Compute the rolling-hash on len-k subarrays of original integer array arr
Inputs:
arr: the input array of integers
k: substring length
p: the prime number for power, default as 113
MOD: the prime number for mod, default at 10**9 + 7
Returns:
an array of integers, each value at res[i] is the rolling hash value of the k-sized
subarray arr[i:i+k]
"""
if len(arr) < k:
return []
exp = 1
for i in range(k-1): # one place for easy-to-make mistakes: here exp only goes to p^(k-1), not p^k!
exp = (exp * p) % MOD
h = 0
for i in range(k):
h = (h * p + arr[i]) % MOD
res = [h]
for i in range(k, len(arr)):
h = (((h - arr[i-k] * exp) % MOD) * p + arr[i]) % MOD # in python, % always return non-negative numbers
res.append(h)
return res
def single_rolling_hash_str(self, s, k, p = 113, MOD = 10**9+7):
"""Compute the rolling-hash on len-k substrings of original string s, everything else the same as self.single_rolling_hash_nums()
"""
arr = [ord(c) for c in s]
return self.single_rolling_hash_nums(arr, k, p, MOD)
def rolling_hash_nums(self, arr, k, p = 113, MOD = 10**9+7, p2 = 101, MOD2 = 99991):
"""Compute the rolling-hash on len-k subarrays of original integer array arr, using two pairs of (mod, power)
The new rolling hash value is equal to hash1 * 100000 + hash2.
"""
hash1 = self.single_rolling_hash_nums(arr, k, p, MOD)
hash2 = self.single_rolling_hash_nums(arr, k, p2, MOD2)
return set((hash1[i], hash2[i]) for i in range(len(hash1)))
def rolling_hash_str(self, s, k, p = 113, MOD = 10**9+7, p2 = 101, MOD2 = 99991):
"""Compute the rolling-hash on len-k substrings of original string s, with two pairs of prime numbers, everything else the same as self.rolling_hash_nums()
"""
arr = [ord(c) for c in s]
return self.rolling_hash_nums(arr, k, p, MOD, p2, MOD2)
class Solution:
def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int:
hasher = Rabin_Karp()
L = min([len(path) for path in paths])
def can(lenn):
cnt = collections.Counter()
for path in paths:
uniq = hasher.rolling_hash_nums(path, lenn)
for key in uniq:
cnt[key] += 1
maxx = max(cnt.values())
return maxx == len(paths)
low, high = 0, L
while low < high:
mid = (low + high + 1) // 2
if can(mid):
low = mid
else:
high = mid - 1
return low |
1a6c4d | e27ac5 | There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.
Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.
A subpath of a path is a contiguous sequence of cities within that path.
Example 1:
Input: n = 5, paths = [[0,1,2,3,4],
[2,3,4],
[4,0,1,2,3]]
Output: 2
Explanation: The longest common subpath is [2,3].
Example 2:
Input: n = 3, paths = [[0],[1],[2]]
Output: 0
Explanation: There is no common subpath shared by the three paths.
Example 3:
Input: n = 5, paths = [[0,1,2,3,4],
[4,3,2,1,0]]
Output: 1
Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
Constraints:
1 <= n <= 100000
m == paths.length
2 <= m <= 100000
sum(paths[i].length) <= 100000
0 <= paths[i][j] < n
The same city is not listed multiple times consecutively in paths[i].
| class Solution(object):
def longestCommonSubpath(self, n, paths):
"""
:type n: int
:type paths: List[List[int]]
:rtype: int
"""
p1, q1 = 1044353, 1020339751
p2, q2 = 1141739, 1020339781
def _test(k):
t1 = pow(p1, k, q1)
t2 = pow(p2, k, q2)
c = Counter()
for path in paths:
s = set()
h1 = h2 = 0
for i in xrange(len(path)):
h1 = (p1*h1 + path[i]) % q1
h2 = (p2*h2 + path[i]) % q2
if i >= k:
h1 = (h1 - path[i-k]*t1) % q1
h2 = (h2 - path[i-k]*t2) % q2
if i >= k-1:
s.add((h1, h2))
for x in s:
c[x] += 1
return c and max(c.itervalues()) == len(paths)
lo = 0
hi = min(len(path) for path in paths) + 1
while lo + 1 < hi:
mid = (lo + hi) // 2
if _test(mid):
lo = mid
else:
hi = mid
return lo |
29668f | a2e51d | You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.
Given an integer k, return the kth letter (1-indexed) in the decoded string.
Example 1:
Input: s = "leet2code3", k = 10
Output: "o"
Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Example 2:
Input: s = "ha22", k = 5
Output: "h"
Explanation: The decoded string is "hahahaha".
The 5th letter is "h".
Example 3:
Input: s = "a2345678999999999999999", k = 1
Output: "a"
Explanation: The decoded string is "a" repeated 8301530446056247680 times.
The 1st letter is "a".
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters and digits 2 through 9.
s starts with a letter.
1 <= k <= 10^9
It is guaranteed that k is less than or equal to the length of the decoded string.
The decoded string is guaranteed to have less than 263 letters.
| class Solution:
def decodeAtIndex(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
l = 0
i = 0
while l < K:
if '0' <= S[i] <= '9':
l *= int(S[i])
else:
l += 1
i += 1
i -= 1
while True:
if 'a' <= S[i] <= 'z':
if l == K:
return S[i]
else:
l -= 1
else:
l //= int(S[i])
K %= l
if K == 0: K = l
i -= 1
return None
|
9beb5c | a2e51d | You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.
Given an integer k, return the kth letter (1-indexed) in the decoded string.
Example 1:
Input: s = "leet2code3", k = 10
Output: "o"
Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Example 2:
Input: s = "ha22", k = 5
Output: "h"
Explanation: The decoded string is "hahahaha".
The 5th letter is "h".
Example 3:
Input: s = "a2345678999999999999999", k = 1
Output: "a"
Explanation: The decoded string is "a" repeated 8301530446056247680 times.
The 1st letter is "a".
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters and digits 2 through 9.
s starts with a letter.
1 <= k <= 10^9
It is guaranteed that k is less than or equal to the length of the decoded string.
The decoded string is guaranteed to have less than 263 letters.
| class Solution(object):
def search(self, S, K, n):
if K < n:
return K
if S[0] in '0123456789':
m = n * int(S[0])
t = self.search(S[1:], K, m)
return t % n
t = self.search(S[1:], K, n + 1)
if t == n:
if self.ans is None:
self.ans = S[0]
return 0
return t % (n + 1)
def decodeAtIndex(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
self.ans = None
self.search(S, K - 1, 0)
return self.ans
|
68cb76 | d93023 | You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.
Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.
Note that the batteries cannot be recharged.
Return the maximum number of minutes you can run all the n computers simultaneously.
Example 1:
Input: n = 2, batteries = [3,3,3]
Output: 4
Explanation:
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.
Example 2:
Input: n = 2, batteries = [1,1,1,1]
Output: 2
Explanation:
Initially, insert battery 0 into the first computer and battery 2 into the second computer.
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer.
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.
Constraints:
1 <= n <= batteries.length <= 100000
1 <= batteries[i] <= 10^9
| class Solution:
def maxRunTime(self, n: int, batteries: List[int]) -> int:
batteries = sorted(batteries, reverse=True)
sumt = sum(batteries)
for t in batteries :
if t > sumt // n :
n -= 1
sumt -= t
else :
return sumt // n
|
b7e2a0 | d93023 | You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.
Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.
Note that the batteries cannot be recharged.
Return the maximum number of minutes you can run all the n computers simultaneously.
Example 1:
Input: n = 2, batteries = [3,3,3]
Output: 4
Explanation:
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.
Example 2:
Input: n = 2, batteries = [1,1,1,1]
Output: 2
Explanation:
Initially, insert battery 0 into the first computer and battery 2 into the second computer.
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer.
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.
Constraints:
1 <= n <= batteries.length <= 100000
1 <= batteries[i] <= 10^9
| class Solution(object):
def maxRunTime(self, n, batteries):
"""
:type n: int
:type batteries: List[int]
:rtype: int
"""
a = batteries
lb = 0
ub = sum(a) // n + 1
def check(amt):
return sum(min(amt, v) for v in a) >= n * amt
while lb + 1 < ub:
x = (lb + ub) >> 1
if check(x):
lb = x
else:
ub = x
return lb |
a03b30 | 28e708 | You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
Return the length of the shortest sequence of rolls that cannot be taken from rolls.
A sequence of rolls of length len is the result of rolling a k sided dice len times.
Note that the sequence taken does not have to be consecutive as long as it is in order.
Example 1:
Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.
Example 2:
Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.
Example 3:
Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.
Constraints:
n == rolls.length
1 <= n <= 100000
1 <= rolls[i] <= k <= 100000
| class Solution(object):
def shortestSequence(self, A, K):
N = len(A)
if len(set(A)) < K:
return 1
if K == 1:
return N + 1
seen = set()
count = 1
for x in A:
seen.add(x)
if len(seen) == K:
count += 1
seen.clear()
return count |
813cd1 | 28e708 | You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
Return the length of the shortest sequence of rolls that cannot be taken from rolls.
A sequence of rolls of length len is the result of rolling a k sided dice len times.
Note that the sequence taken does not have to be consecutive as long as it is in order.
Example 1:
Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.
Example 2:
Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.
Example 3:
Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.
Constraints:
n == rolls.length
1 <= n <= 100000
1 <= rolls[i] <= k <= 100000
| class Solution:
def shortestSequence(self, rolls: List[int], k: int) -> int:
seen = [False] * k
out = 1
ct = 0
for v in rolls:
if not seen[v - 1]:
ct += 1
seen[v - 1] = True
if ct == k:
out += 1
ct = 0
seen = [False] * k
return out
|
44d406 | 41edd3 | You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.
You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.
Let penalty() be the maximum distance between adjacent gas stations after adding the k new stations.
Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: stations = [1,2,3,4,5,6,7,8,9,10], k = 9
Output: 0.50000
Example 2:
Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1
Output: 14.00000
Constraints:
10 <= stations.length <= 2000
0 <= stations[i] <= 10^8
stations is sorted in a strictly increasing order.
1 <= k <= 1000000
| class Solution:
def possible(self, a, k, thres):
n = len(a)
cnt = 0
import math
for i in range(n - 1):
gap = a[i + 1] - a[i]
need = math.ceil(gap / thres)
cnt += need - 1
if cnt > k:
return False
return True
def minmaxGasDist(self, stations, K):
"""
:type stations: List[int]
:type K: int
:rtype: float
"""
a = stations
n = len(a)
k = K
upper = max([a[i + 1] - a[i] for i in range(n - 1)])
lower = 0
while upper - lower > 1e-8:
mid = (upper + lower) / 2
# print(mid, self.possible(a, k, mid))
if self.possible(a, k, mid):
upper = mid
else:
lower = mid
return (upper + lower) / 2
|
77afc1 | 41edd3 | You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.
You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.
Let penalty() be the maximum distance between adjacent gas stations after adding the k new stations.
Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: stations = [1,2,3,4,5,6,7,8,9,10], k = 9
Output: 0.50000
Example 2:
Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1
Output: 14.00000
Constraints:
10 <= stations.length <= 2000
0 <= stations[i] <= 10^8
stations is sorted in a strictly increasing order.
1 <= k <= 1000000
| class Solution(object):
def minmaxGasDist(self, stations, K):
"""
:type stations: List[int]
:type K: int
:rtype: float
"""
dis = []
stations.sort()
for i in range(1, len(stations)):
dis.append(stations[i] - stations[i-1])
# print dis
left = 0.0
right = max(dis)
while right - left > 0.000001:
mid = (right + left) / 2
needed = 0
for d in dis:
needed += int(d / mid)
if needed > K:
break
# print left, right, mid, needed
if needed > K:
left = mid
else:
right = mid
return (right + left) / 2
|
220e7f | 6bef54 | You are given a string s representing a list of words. Each letter in the word has one or more options.
If there is one option, the letter is represented as is.
If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}" represents options ["a", "b", "c"].
For example, if s = "a{b,c}", the first character is always 'a', but the second character can be 'b' or 'c'. The original list is ["ab", "ac"].
Return all words that can be formed in this manner, sorted in lexicographical order.
Example 1:
Input: s = "{a,b}c{d,e}f"
Output: ["acdf","acef","bcdf","bcef"]
Example 2:
Input: s = "abcd"
Output: ["abcd"]
Constraints:
1 <= s.length <= 50
s consists of curly brackets '{}', commas ',', and lowercase English letters.
s is guaranteed to be a valid input.
There are no nested curly brackets.
All characters inside a pair of consecutive opening and ending curly brackets are different.
| class Solution(object):
def permute(self, s):
level = []
rec = []
for ss in s:
if ss == "{":
if rec:
level.append(''.join(rec).split(','))
rec = []
elif ss == "}":
rec = ''.join(rec).split(',')
level.append(rec)
rec = []
else:
rec.append(ss)
if rec: level.append(''.join(rec).split(','))
# print(level)
res = []
def dfs(idx, string):
if idx == len(level):
res.append(string); return
for ss in level[idx]:
dfs(idx+1, string+ss)
dfs(0, '')
res.sort()
return res |
4e3e6a | 6bef54 | You are given a string s representing a list of words. Each letter in the word has one or more options.
If there is one option, the letter is represented as is.
If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}" represents options ["a", "b", "c"].
For example, if s = "a{b,c}", the first character is always 'a', but the second character can be 'b' or 'c'. The original list is ["ab", "ac"].
Return all words that can be formed in this manner, sorted in lexicographical order.
Example 1:
Input: s = "{a,b}c{d,e}f"
Output: ["acdf","acef","bcdf","bcef"]
Example 2:
Input: s = "abcd"
Output: ["abcd"]
Constraints:
1 <= s.length <= 50
s consists of curly brackets '{}', commas ',', and lowercase English letters.
s is guaranteed to be a valid input.
There are no nested curly brackets.
All characters inside a pair of consecutive opening and ending curly brackets are different.
| class Solution:
def permute(self, S: str) -> List[str]:
words = S.split('{')
word = []
for s in words:
w = s.split('}')
word.extend(w)
self._cands = [w.split(',') for w in word]
self._res = []
self.DFS(0, "")
return sorted(self._res)
def DFS(self, depth, now):
if depth == len(self._cands):
self._res.append(now)
return
for ch in self._cands[depth]:
self.DFS(depth + 1, now + ch)
|
5dd223 | 222350 | Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000
text has only lowercase English letters.
| class Solution(object):
def distinctEchoSubstrings(self, S):
N = len(S)
A = map(ord, S)
MOD = 10 ** 9 + 7
P = 37
Pinv = pow(P, MOD-2, MOD)
pwr = 1
B = []
for x in A:
B.append(pwr * x % MOD)
pwr *= P; pwr %= MOD
Bsum = [0]
for ha in B:
Bsum.append( (Bsum[-1] +ha )% MOD)
ppwr = 1
ans = 0
for length in xrange(1, N // 2 + 1):
seen = set()
ppwr *= P; ppwr %= MOD
for i1 in xrange(N - 2 * length + 1):
left = (Bsum[i1 + length] - Bsum[i1])
left *= ppwr; left %= MOD
right = (Bsum[i1 + length + length] - Bsum[i1 + length])
right %= MOD
if left == right:
seen.add(left * pow(Pinv, i1, MOD) % MOD)
#print("!", i1, length)
#print("!!", length, len(seen))
ans += len(seen)
return ans |
523c5b | 222350 | Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000
text has only lowercase English letters.
| class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
results = set()
for i in range(len(text)):
for j in range(len(text)):
if (j+1-i) % 2:
continue
start = i
end = j+1
middle = (start + end) // 2
s1 = text[start:middle]
s2 = text[middle:end]
if s1 and s1 == s2:
results.add(s1)
return len(results) |
f2f4e2 | 97c97b | You are given an integer array nums and an integer goal.
You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
Return the minimum possible value of abs(sum - goal).
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Example 1:
Input: nums = [5,-7,3,5], goal = 6
Output: 0
Explanation: Choose the whole array as a subsequence, with a sum of 6.
This is equal to the goal, so the absolute difference is 0.
Example 2:
Input: nums = [7,-9,15,-2], goal = -5
Output: 1
Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.
The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
Example 3:
Input: nums = [1,2,3], goal = -7
Output: 7
Constraints:
1 <= nums.length <= 40
-10^7 <= nums[i] <= 10^7
-10^9 <= goal <= 10^9
| class Solution:
def minAbsDifference(self, a: List[int], targ: int) -> int:
n = len(a)
# nums is NOT very long
# meet in the middle?
# yes,
# 2^20 is not very large
# every subsequence of left half
# checks against pool of subsequence on right half
# finds the closest hit
# NOTE: don't forget empty subarrays
ln = n//2
# populate right half
right = [0]
for i in range(ln, n):
x = a[i]
right.extend([x+y for y in right])
right.sort()
# bisect find best matches
# bisect_left and bisect_left-1 will both do fine
left = [0]
for i in range(ln):
x = a[i]
left.extend([x+y for y in left])
ret = inf
for x in left:
idx = bisect_left(right, targ-x)
idx2 = idx-1
if idx < len(right):
y = right[idx]
chal = abs(targ - (x+y))
ret = min(ret, chal)
if idx2 >= 0:
y = right[idx2]
chal = abs(targ - (x+y))
ret = min(ret, chal)
return ret
|
ed231b | 97c97b | You are given an integer array nums and an integer goal.
You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
Return the minimum possible value of abs(sum - goal).
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Example 1:
Input: nums = [5,-7,3,5], goal = 6
Output: 0
Explanation: Choose the whole array as a subsequence, with a sum of 6.
This is equal to the goal, so the absolute difference is 0.
Example 2:
Input: nums = [7,-9,15,-2], goal = -5
Output: 1
Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.
The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
Example 3:
Input: nums = [1,2,3], goal = -7
Output: 7
Constraints:
1 <= nums.length <= 40
-10^7 <= nums[i] <= 10^7
-10^9 <= goal <= 10^9
| class Solution(object):
def minAbsDifference(self, A, target):
N = len(A)
N1 = N >> 1
def make(B):
seen = {0}
for x in B:
seen |= {x+y for y in seen}
return seen
left = sorted(make(A[:N1]))
right = sorted(make(A[N1:]))
ans = float('inf')
j = len(right) - 1
for i, x in enumerate(left):
while j >= 0 and x + right[j] > target:
j -= 1
if j >= 0:
cand = abs(x + right[j] - target)
if cand < ans: ans = cand
if j+1 < len(right):
cand = abs(x + right[j+1] - target)
if cand < ans: ans = cand
return ans |
089eac | fb1009 | Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree.
Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.
Example 1:
Input: root = [1,3,2], k = 1
Output: 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
Example 2:
Input: root = [1], k = 1
Output: 1
Explanation: The nearest leaf node is the root node itself.
Example 3:
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2
Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
1 <= Node.val <= 1000
All the values of the tree are unique.
There exist some node in the tree where Node.val == k.
| # 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 findClosestLeaf(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
self.result = None
self.dis = float("inf")
self.checkDistance(root, k)
return self.result
def checkDistance(self, node, k):
if node.val == k:
if node.left:
self.findLeaf(node.left, 0)
if node.right:
self.findLeaf(node.right, 0)
if node.left is None and node.right is None:
self.result = node.val
self.dis = 0
return 0
else:
result = -1
if node.left:
resultLeft = self.checkDistance(node.left, k)
if resultLeft != -1:
result = resultLeft + 1
if node.right:
self.findLeaf(node.right, result)
if result == -1 and node.right:
resultRight = self.checkDistance(node.right, k)
if resultRight != -1:
result = resultRight + 1
if node.left:
self.findLeaf(node.left, result)
return result
def findLeaf(self, node, dis):
dis += 1
if node.left:
self.findLeaf(node.left, dis)
if node.right:
self.findLeaf(node.right, dis)
if node.left is None and node.right is None:
if self.dis > dis:
self.dis = dis
self.result = node.val
|
34759e | fb1009 | Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree.
Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.
Example 1:
Input: root = [1,3,2], k = 1
Output: 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
Example 2:
Input: root = [1], k = 1
Output: 1
Explanation: The nearest leaf node is the root node itself.
Example 3:
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2
Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
1 <= Node.val <= 1000
All the values of the tree are unique.
There exist some node in the tree where Node.val == k.
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findClosestLeaf(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
self.nodes = [None] * 1001
self.edges = [[] for i in range(1001)]
self.dfs(root)
visited = [0] * 1001
level = [k]
while level:
tmp = []
for val in level:
if not(self.nodes[val].left or self.nodes[val].right):
return val
visited[val] = 1
for nb in self.edges[val]:
if visited[nb]: continue
tmp.append(nb)
level = tmp
def dfs(self, root):
if not root: return
self.nodes[root.val] = root
if root.left:
self.edges[root.val].append(root.left.val)
self.edges[root.left.val].append(root.val)
self.dfs(root.left)
if root.right:
self.edges[root.val].append(root.right.val)
self.edges[root.right.val].append(root.val)
self.dfs(root.right) |
4946bb | fa0c69 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.
To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.
Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.
An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.
Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.
Example 1:
Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
Output: [-1,0,0,1]
Explanation: In the above figure, each node's value is in parentheses.
- Node 0 has no coprime ancestors.
- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).
- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's
value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.
- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its
closest valid ancestor.
Example 2:
Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output: [-1,0,-1,0,0,0,-1]
Constraints:
nums.length == n
1 <= nums[i] <= 50
1 <= n <= 100000
edges.length == n - 1
edges[j].length == 2
0 <= uj, vj < n
uj != vj
| class Solution:
def getCoprimes(self, nums: List[int], e: List[List[int]]) -> List[int]:
n = len(nums)
edges = collections.defaultdict(list)
for x, y in e:
edges[x].append(y)
edges[y].append(x)
coprime = collections.defaultdict(list)
for i in range(1, 50 + 1):
for j in range(1, 50 + 1):
if math.gcd(i, j) == 1:
coprime[i].append(j)
pos = [-1] * 51
ans = [-1] * n
stk = []
def dfs(u, fa):
dep = -1
for p in coprime[nums[u]]:
dep = max(dep, pos[p])
ans[u] = (-1 if dep == -1 else stk[dep])
tmp = pos[nums[u]]
pos[nums[u]] = len(stk)
stk.append(u)
for v in edges[u]:
if v != fa:
dfs(v, u)
pos[nums[u]] = tmp
stk.pop()
dfs(0, -1)
return ans |
c2a6bc | fa0c69 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.
To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.
Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.
An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.
Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.
Example 1:
Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
Output: [-1,0,0,1]
Explanation: In the above figure, each node's value is in parentheses.
- Node 0 has no coprime ancestors.
- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).
- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's
value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.
- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its
closest valid ancestor.
Example 2:
Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output: [-1,0,-1,0,0,0,-1]
Constraints:
nums.length == n
1 <= nums[i] <= 50
1 <= n <= 100000
edges.length == n - 1
edges[j].length == 2
0 <= uj, vj < n
uj != vj
| class Solution(object):
def getCoprimes(self, A, edges):
n = len(edges) + 1
graph = [[] for _ in xrange(n)]
for u,v in edges:
graph[u].append(v)
graph[v].append(u)
from fractions import gcd
ans = [-1] * n
paths = [[] for p in range(51)]
timer = {}
def dfs(node, par=None, time=0):
timer[node] = time
v = A[node]
best = None
for i, row in enumerate(paths):
if i and gcd(v, i) == 1 and row:
last = row[-1]
if best is None or timer[last] > timer[best]:
best = last
if best is not None:
ans[node] = best
paths[v].append(node)
for nei in graph[node]:
if nei != par:
dfs(nei, node, time+1)
paths[v].pop()
dfs(0)
return ans |
a9d504 | b9ea57 | In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
Example 1:
Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Constraints:
2 <= tops.length <= 2 * 10000
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
| class Solution(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
n = len(A)
a = collections.Counter(A)
b = collections.Counter(B)
c = a + b
m = c.most_common(1)[0]
if m[1] < n:
return -1
cand = m[0]
ac, bc = 0, 0
for i in range(n):
if cand != A[i]:
if cand != B[i]:
return -1
ac += 1
elif cand != B[i]:
bc += 1
return min(ac, bc)
|
071fb2 | b9ea57 | In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
Example 1:
Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Constraints:
2 <= tops.length <= 2 * 10000
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
| class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
tar_a = [0]*7
tar_b = [0]*7
inf = float('inf')
tar_a[0] = tar_b[0] = inf
for a, b in zip(A, B):
# impossible solution
for i in range(1, 6+1):
if i != a and i != b:
tar_a[i] = tar_b[i] = inf
if a != b:
tar_a[b] += 1
tar_b[a] += 1
# print(tar_a, tar_b)
ret = min(tar_a+tar_b)
return -1 if ret == inf else ret
|
b0d81c | 7bba8f | Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 100000
-10000 <= nums[i] <= 10000
| from collections import deque
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
ans = A[0]
q = deque() # val, idx
for i in range(len(A)):
while q and q[0][1] < i-k:
q.popleft()
m = max(0, q[0][0]) if q else 0
m += A[i]
if ans < m:
ans = m
while q and q[-1][0] < m:
q.pop()
q.append((m, i))
return ans
|
a2a683 | 7bba8f | Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 100000
-10000 <= nums[i] <= 10000
| from collections import deque
class Solution(object):
def constrainedSubsetSum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
a = nums
r = max(a)
if r < 0: return r
n = len(a)
b = a[:]
# b[i] = best sum ending on nums[i]
# b[i] = nums[i] + max(0, b[i-k], b[i-k+1], ..., b[i-1])
s = deque() # (i asc, v desc)
for i in xrange(n):
if s: b[i] = max(b[i], a[i] + s[0][1])
if s and i - s[0][0] == k: s.popleft()
while s and s[-1][1] <= b[i]: s.pop()
s.append((i, b[i]))
return max(b) |
370e4d | 988362 | You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.
-x for x < 0.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:
Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.length
n == points[r].length
1 <= m, n <= 100000
1 <= m * n <= 100000
0 <= points[r][c] <= 100000
| class Solution(object):
def maxPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
a = points
n = len(a[0])
f = [0]*n
for row in a:
ff = [0] * n
t = float('-inf')
for i in xrange(n):
t = max(t, f[i] + i)
ff[i] = max(ff[i], t + row[i] - i)
t = float('-inf')
for i in xrange(n-1, -1, -1):
t = max(t, f[i] - i)
ff[i] = max(ff[i], t + row[i] + i)
f = ff
return max(f) |
e55f12 | 988362 | You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.
-x for x < 0.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:
Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.length
n == points[r].length
1 <= m, n <= 100000
1 <= m * n <= 100000
0 <= points[r][c] <= 100000
| class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
m, n = len(points), len(points[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
dp[i][j] = max(dp[i][j], points[i][j])
if i:
dp[i][j] = max(dp[i][j], dp[i - 1][j] + points[i][j])
if j:
dp[i][j] = max(dp[i][j], dp[i][j - 1] - 1)
for j in range(n - 1, -1, -1):
dp[i][j] = max(dp[i][j], points[i][j])
if i:
dp[i][j] = max(dp[i][j], dp[i - 1][j] + points[i][j])
if j < n - 1:
dp[i][j] = max(dp[i][j], dp[i][j + 1] - 1)
ans = max(dp[-1])
return ans |
e7037b | d05726 | You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.
Example 3:
Input: nums = [3,100,20]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes [4,7,20].
In the second move, change 20 to 7. nums becomes [4,7,7].
In the third move, change 4 to 3. nums becomes [7,7,7].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
Constraints:
1 <= nums.length <= 100000
-10^9 <= nums[i] <= 10^9
| class Solution(object):
def minDifference(self, A):
A.sort()
N = len(A)
if N <= 3: return 0
take = N - 3
return min(A[i+take - 1] - A[i] for i in range(N - take + 1)) |
f670a5 | d05726 | You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.
Example 3:
Input: nums = [3,100,20]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes [4,7,20].
In the second move, change 20 to 7. nums becomes [4,7,7].
In the third move, change 4 to 3. nums becomes [7,7,7].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
Constraints:
1 <= nums.length <= 100000
-10^9 <= nums[i] <= 10^9
| class Solution:
def minDifference(self, nums: List[int]) -> int:
if len(nums) <= 3:
return 0
n1 = list(sorted(nums))
return min(n1[-1] - n1[3], n1[-2] - n1[2], n1[-3] - n1[1], n1[-4] - n1[0]) |
6d3172 | 870a94 | You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:
status[i] is 1 if the ith box is open and 0 if the ith box is closed,
candies[i] is the number of candies in the ith box,
keys[i] is a list of the labels of the boxes you can open after opening the ith box.
containedBoxes[i] is a list of the boxes you found inside the ith box.
You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
Example 1:
Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.
Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:
Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.
The total number of candies will be 6.
Constraints:
n == status.length == candies.length == keys.length == containedBoxes.length
1 <= n <= 1000
status[i] is either 0 or 1.
1 <= candies[i] <= 1000
0 <= keys[i].length <= n
0 <= keys[i][j] < n
All values of keys[i] are unique.
0 <= containedBoxes[i].length <= n
0 <= containedBoxes[i][j] < n
All values of containedBoxes[i] are unique.
Each box is contained in one box at most.
0 <= initialBoxes.length <= n
0 <= initialBoxes[i] < n
| class Solution:
def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
n=len(status)
ans=0
cur=initialBoxes
cont=True
while cont:
cont=False
nxt=[]
for idx in cur:
if status[idx]:
ans+=candies[idx]
nxt.extend(containedBoxes[idx])
for nid in keys[idx]:
status[nid]=1
cont=True
else:
nxt.append(idx)
cur=nxt
return ans
|
2518e1 | 870a94 | You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:
status[i] is 1 if the ith box is open and 0 if the ith box is closed,
candies[i] is the number of candies in the ith box,
keys[i] is a list of the labels of the boxes you can open after opening the ith box.
containedBoxes[i] is a list of the boxes you found inside the ith box.
You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
Example 1:
Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.
Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:
Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.
The total number of candies will be 6.
Constraints:
n == status.length == candies.length == keys.length == containedBoxes.length
1 <= n <= 1000
status[i] is either 0 or 1.
1 <= candies[i] <= 1000
0 <= keys[i].length <= n
0 <= keys[i][j] < n
All values of keys[i] are unique.
0 <= containedBoxes[i].length <= n
0 <= containedBoxes[i][j] < n
All values of containedBoxes[i] are unique.
Each box is contained in one box at most.
0 <= initialBoxes.length <= n
0 <= initialBoxes[i] < n
| from collections import deque
class Solution(object):
def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes):
"""
:type status: List[int]
:type candies: List[int]
:type keys: List[List[int]]
:type containedBoxes: List[List[int]]
:type initialBoxes: List[int]
:rtype: int
"""
n = len(status)
removed = [0]*n
unlocked = status
usable = [0]*n
r = 0
q = deque()
for u in initialBoxes:
usable[u] = 1
if unlocked[u]: q.append(u)
# we can unlock a box
# we can also reach a box
# whichever happens second willl enqueue the box
while q:
u = q.popleft()
r += candies[u]
for v in keys[u]:
if unlocked[v]: continue
unlocked[v] = 1
if usable[v]: q.append(v)
for v in containedBoxes[u]:
if usable[v]: continue
usable[v] = 1
if unlocked[v]: q.append(v)
return r |
f7395f | 554795 | A maximum tree is a tree where every node has a value greater than any other value in its subtree.
You are given the root of a maximum binary tree and an integer val.
Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:
If a is empty, return null.
Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i].
The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).
The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).
Return root.
Note that we were not given a directly, only a root node root = Construct(a).
Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.
Return Construct(b).
Example 1:
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: a = [1,4,2,3], b = [1,4,2,3,5]
Example 2:
Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: a = [2,1,5,4], b = [2,1,5,4,3]
Example 3:
Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: a = [2,1,5,3], b = [2,1,5,3,4]
Constraints:
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 100
All the values of the tree are unique.
1 <= val <= 100
| # 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 insertIntoMaxTree(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
self.serial = []
self.deserial(root)
self.serial.append(TreeNode(val))
return self.construct(self.serial, 0, len(self.serial) - 1)
def construct(self, lst, left, right):
if left == right:
return lst[left]
if left > right:
return None
max_idx = left
for i in range(left, right + 1):
if lst[i].val > lst[max_idx].val:
max_idx = i
root = lst[max_idx]
root.left = self.construct(lst, left, max_idx - 1)
root.right = self.construct(lst, max_idx + 1, right)
return root
def deserial(self, root):
if root:
self.deserial(root.left)
self.serial.append(root)
self.deserial(root.right)
root.left = None
root.right = None |
dc30db | 554795 | A maximum tree is a tree where every node has a value greater than any other value in its subtree.
You are given the root of a maximum binary tree and an integer val.
Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:
If a is empty, return null.
Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i].
The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).
The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).
Return root.
Note that we were not given a directly, only a root node root = Construct(a).
Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.
Return Construct(b).
Example 1:
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: a = [1,4,2,3], b = [1,4,2,3,5]
Example 2:
Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: a = [2,1,5,4], b = [2,1,5,4,3]
Example 3:
Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: a = [2,1,5,3], b = [2,1,5,3,4]
Constraints:
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 100
All the values of the tree are unique.
1 <= val <= 100
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
if val > root.val:
node = TreeNode(val)
node.left = root
return node
root.right = self.insertIntoMaxTree(root.right, val)
return root |
70a241 | ecdf4e | There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
Example 1:
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Example 2:
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] is 1 or 0.
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
| class Solution(object):
def root_of(self, x):
if x == self.r[x]:
return x
self.r[x] = self.root_of(self.r[x])
return self.r[x]
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M:
return 0
n = len(M)
self. r = range(n)[:]
ans = n
for i in range(n):
for j in range(n):
if M[i][j]:
a = self.root_of(i)
b = self.root_of(j)
if a != b:
ans -= 1
self.r[b] = a
return ans
|
ba52db | b999cc | Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
An expression alternates chunks and symbols, with a space separating each chunk and symbol.
A chunk is either an expression in parentheses, a variable, or a non-negative integer.
A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
For example, expression = "1 + 2 * 3" has an answer of ["7"].
The format of the output is as follows:
For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
For example, we would never write a term like "b*a*c", only "a*b*c".
Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
For example, "a*a*b*c" has degree 4.
The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
Terms (including constant terms) with coefficient 0 are not included.
For example, an expression of "0" has an output of [].
Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].
Example 1:
Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]
Example 2:
Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]
Example 3:
Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]
Constraints:
1 <= expression.length <= 250
expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.
expression does not contain any leading or trailing spaces.
All the tokens in expression are separated by a single space.
0 <= evalvars.length <= 100
1 <= evalvars[i].length <= 20
evalvars[i] consists of lowercase English letters.
evalints.length == evalvars.length
-100 <= evalints[i] <= 100
| class term(object):
def __init__(self, coef):
self.coef = coef
self.var = []
def __neg__(self):
rt = term(-self.coef)
rt.var = self.var[:]
return rt
def compareTuple(self):
self.var.sort()
return (-len(self.var), "*".join(self.var))
def compareStr(self):
self.var.sort()
return "*".join(self.var)
def __str__(self):
if not self.var:
return str(self.coef)
return "".join([str(self.coef), "*", self.compareStr()])
class manyTerms(object):
def __init__(self, term):
self.terms = [term]
# def pt(self):
# for t in self.terms:
# print t
def result(self):
self.terms = [t for t in self.terms if t.coef != 0]
self.terms.sort(key = term.compareTuple)
return map(str, self.terms)
def add(self, other):
for j in range(len(other.terms)):
for i in range(len(self.terms)):
if self.terms[i].compareStr() == other.terms[j].compareStr():
self.terms[i].coef += other.terms[j].coef
other.terms[j].coef = 0
break
for j in range(len(other.terms)):
if other.terms[j].coef != 0:
self.terms.append(other.terms[j])
def minus(self, other):
for j in range(len(other.terms)):
for i in range(len(self.terms)):
if self.terms[i].compareStr() == other.terms[j].compareStr():
self.terms[i].coef -= other.terms[j].coef
other.terms[j].coef = 0
break
for j in range(len(other.terms)):
if other.terms[j].coef != 0:
self.terms.append(-other.terms[j])
def mul(self, other):
ans = manyTerms(term(0))
for j in range(len(other.terms)):
for i in range(len(self.terms)):
newTerm = term(self.terms[i].coef * other.terms[j].coef)
newTerm.var = self.terms[i].var + other.terms[j].var
ans.add(manyTerms(newTerm))
return ans
class Solution(object):
def basicCalculatorIV(self, expression, evalvars, evalints):
"""
:type expression: str
:type evalvars: List[str]
:type evalints: List[int]
:rtype: List[str]
"""
self.d = {}
for i in range(len(evalvars)):
self.d[evalvars[i]] = evalints[i]
return self.calcExp(expression).result()
def calcExp(self, s):
# first deal with ( and ) with stack
s = s.strip()
# iPlus = s.rfind("+")
# iMinus = s.rfind("-")
# iMul = s.rfind("*")
iPlus = iMinus = iMul = -1
level = 0
for i in reversed(range(len(s))):
if level == 0:
if s[i] == "+" and iPlus == -1:
iPlus = i
if s[i] == "-" and iMinus == -1:
iMinus = i
if s[i] == "*" and iMul == -1:
iMul = i
if s[i] == ")":
level += 1
if s[i] == "(":
level -= 1
if iPlus == -1 and iMinus == -1 and iMul == -1:
if s[0] == "(":
return self.calcExp(s[1:-1])
if s in self.d:
return manyTerms(term(self.d[s]))
if ord("a")<=ord(s[0])<=ord("z"):
tempTerm = term(1)
tempTerm.var.append(s)
return manyTerms(tempTerm)
else:
return manyTerms(term(int(s)))
if iPlus == -1 and iMinus == -1:
mx = iMul
else:
mx = max(iPlus, iMinus)
left = self.calcExp(s[:mx])
right = self.calcExp(s[mx+1:])
if mx == iPlus:
left.add(right)
return left
if mx == iMinus:
left.minus(right)
return left
if mx == iMul:
return left.mul(right)
|
6827d6 | f51b7b | You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 10000
num consists of only digits and does not contain leading zeros.
1 <= k <= 10^9
| class Solution(object):
def minInteger(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
# within next k, find the min
# move the closest such min to the front
# remove that many swaps from k
# repeat
# position of 0 -> 9
a = num
n = len(a)
pos = [[] for _ in xrange(10)]
for i in xrange(n-1, -1, -1):
pos[ord(a[i])-ord('0')].append(i)
bit = [0] * (n+1)
def inc(i):
i += 1
while i <= n:
bit[i] += 1
i += i&-i
def get(i):
r = 0
while i:
r += bit[i]
i &= i-1
return r
def find_best():
for d in xrange(10):
if not pos[d]: continue
i = pos[d][-1]
cost = i - get(i)
if cost <= k: return d, cost
return None, None
r = []
removed = [False]*n
while k:
d, cost = find_best()
if d is None: break
k -= cost
r.append(d)
i = pos[d].pop()
inc(i)
removed[i] = True
lhs = ''.join(str(d) for d in r)
rhs = ''.join(a[i] for i in xrange(n) if not removed[i])
return lhs + rhs |
ea360f | f51b7b | You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 10000
num consists of only digits and does not contain leading zeros.
1 <= k <= 10^9
| class Solution:
def minInteger(self, num: str, k: int) -> str:
if sorted(num) == num:
return num
n = len(num)
if k >= n * (n - 1) // 2:
return ''.join(sorted(num))
num = list(num)
i = 0
while k and i < n:
mini = min(num[i:i + k + 1])
ind = i + num[i:i + k + 1].index(mini)
if ind > i:
k -= ind - i
num[i:ind + 1] = [mini] + num[i:ind]
i += 1
return ''.join(num) |
d94f87 | 4f827b | Given a string s, return the maximum number of ocurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Constraints:
1 <= s.length <= 100000
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s consists of only lowercase English letters.
| class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
cnt=collections.defaultdict(int)
n=len(s)
st=ed=0
while st<n:
temp=set()
while len(temp)<=maxLetters and ed-st<=maxSize and ed<=n:
if ed-st>=minSize:
cnt[s[st:ed]]+=1
if ed<n:
temp.add(s[ed])
ed+=1
st+=1
ed=st
return max(cnt.values()) if cnt else 0
|
2bbdaf | 4f827b | Given a string s, return the maximum number of ocurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Constraints:
1 <= s.length <= 100000
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s consists of only lowercase English letters.
| from collections import Counter
class Solution(object):
def maxFreq(self, s, maxLetters, minSize, maxSize):
"""
:type s: str
:type maxLetters: int
:type minSize: int
:type maxSize: int
:rtype: int
"""
A, B, M = 1009, 1, 1000000007
k = minSize
for _ in xrange(k): B = (B*A)%M
f = [0]*256
t = 0
h = 0
r = Counter()
for i, c in enumerate(s):
c = ord(c)
if not f[c]: t += 1
f[c] += 1
h = (A*h+c)%M
if i >= k:
c = ord(s[i-k])
h = (h-B*c)%M
f[c] -= 1
if not f[c]: t -= 1
if i >= k-1 and t <= maxLetters: r[h] += 1
return max(r.itervalues()) if r else 0 |
275242 | e8e777 | You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
Replace the leaf node in trees[i] with trees[j].
Remove trees[j] from trees.
Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
Every node in the node's left subtree has a value strictly less than the node's value.
Every node in the node's right subtree has a value strictly greater than the node's value.
A leaf is a node that has no children.
Example 1:
Input: trees = [[2,1],[3,2,5],[5,4]]
Output: [3,2,5,1,null,4]
Explanation:
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
Delete trees[0], so trees = [[3,2,5,1],[5,4]].
In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
Delete trees[1], so trees = [[3,2,5,1,null,4]].
The resulting tree, shown above, is a valid BST, so return its root.
Example 2:
Input: trees = [[5,3,8],[3,2,6]]
Output: []
Explanation:
Pick i=0 and j=1 and merge trees[1] into trees[0].
Delete trees[1], so trees = [[5,3,8,2,6]].
The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
Example 3:
Input: trees = [[5,4],[3]]
Output: []
Explanation: It is impossible to perform any operations.
Constraints:
n == trees.length
1 <= n <= 5 * 10000
The number of nodes in each tree is in the range [1, 3].
Each node in the input may have children but no grandchildren.
No two roots of trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 10000.
| class Solution:
def canMerge(self, trees: List[TreeNode]) -> TreeNode:
random.shuffle(trees)
roots = {node.val: node for node in trees}
leaves = set()
for node in trees:
for nei in (node.left, node.right):
if nei:
leaves.add(nei.val)
choice = set(roots) - leaves
if choice:
for rv in choice: break
else:
return None
ans = roots[rv]
del roots[rv]
def dfs(node):
if not node:
return
if node.left is node.right and node.val in roots:
node = roots[node.val]
del roots[node.val]
dfs(node)
return node
node.left = dfs(node.left)
node.right = dfs(node.right)
return node
dfs(ans)
if roots: return
def valid(node, left_bound, right_bound):
if not node:
return True
if not (left_bound < node.val < right_bound):
return False
return (valid(node.left, left_bound, node.val) and
valid(node.right, node.val, right_bound))
if not valid(ans, float('-inf'), float('inf')): return
return ans
"""
A = []
def inorder(node, vals):
if node:
inorder(node.left,vals)
vals.append(node.val)
inorder(node.right,vals)
for root in trees:
vals = []
inorder(root, vals)
A.append(vals)
B = sorted(set(A))
for row in A:
"""
|
d5bcf2 | e8e777 | You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
Replace the leaf node in trees[i] with trees[j].
Remove trees[j] from trees.
Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
Every node in the node's left subtree has a value strictly less than the node's value.
Every node in the node's right subtree has a value strictly greater than the node's value.
A leaf is a node that has no children.
Example 1:
Input: trees = [[2,1],[3,2,5],[5,4]]
Output: [3,2,5,1,null,4]
Explanation:
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
Delete trees[0], so trees = [[3,2,5,1],[5,4]].
In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
Delete trees[1], so trees = [[3,2,5,1,null,4]].
The resulting tree, shown above, is a valid BST, so return its root.
Example 2:
Input: trees = [[5,3,8],[3,2,6]]
Output: []
Explanation:
Pick i=0 and j=1 and merge trees[1] into trees[0].
Delete trees[1], so trees = [[5,3,8,2,6]].
The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
Example 3:
Input: trees = [[5,4],[3]]
Output: []
Explanation: It is impossible to perform any operations.
Constraints:
n == trees.length
1 <= n <= 5 * 10000
The number of nodes in each tree is in the range [1, 3].
Each node in the input may have children but no grandchildren.
No two roots of trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 10000.
| # 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 canMerge(self, trees):
"""
:type trees: List[TreeNode]
:rtype: TreeNode
"""
vv = {}
pp = set()
for n in trees:
vv[n.val] = n
for n in trees:
nn = n.left
if nn and nn.val in vv:
n.left = vv[nn.val]
pp.add(nn.val)
nn = n.right
if nn and nn.val in vv:
n.right = vv[nn.val]
pp.add(nn.val)
def check(n):
if hasattr(n, "check"):
return n.check
minv, maxv = n.val, n.val
n.minv, n.maxv = minv, maxv
n.check = False
if n.left:
nn = n.left
if not check(n.left):
return False
if nn.maxv >= n.val:
return False
minv = min(minv, nn.minv)
maxv = max(maxv, nn.maxv)
if n.right:
nn = n.right
if not check(n.right):
return False
if nn.minv <= n.val:
return False
minv = min(minv, nn.minv)
maxv = max(maxv, nn.maxv)
# print "==", nn.val, nn.minv, nn.maxv
n.minv, n.maxv =minv, maxv
n.check = True
# print n.val, n.minv, n.maxv
return True
for n in trees:
if not check(n): return None
rc = 0
rn = None
for n in trees:
if n.val not in pp:
rc+=1
rn = n
if rc!=1: return None
return rn
|
04a237 | 79f1a4 | The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [2,1,3]
Output: 6
Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
Example 2:
Input: nums = [2]
Output: 0
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 100000
| class Solution:
def sumSubseqWidths(self, A):
"""
:type A: List[int]
:rtype: int
"""
MOD = 10**9 + 7
A.sort()
n = len(A)
pow2 = [1]
for _ in range(n+1):
pow2.append(pow2[-1] * 2 % MOD)
ans = 0
for i, a in enumerate(A):
ans -= a * (pow2[n-i-1] - 1) % MOD
ans += a * (pow2[i] - 1) % MOD
ans = (ans + MOD) % MOD
return ans
|
de35f3 | 79f1a4 | The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [2,1,3]
Output: 6
Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
Example 2:
Input: nums = [2]
Output: 0
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 100000
| class Solution(object):
def sumSubseqWidths(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
mod = 1000000000 + 7
ans = 0
base = 0
mul = 1
for i in reversed(range(1, len(A))):
base = (base*2 + A[i])%mod
ans = (ans+base-(A[i-1]*((mul*2)-1)))%mod
mul = (mul*2)%mod
return ans |
b891e8 | 0b4803 | You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
The greatest common divisor of any adjacent values in the sequence is equal to 1.
There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 10^9 + 7.
Two sequences are considered distinct if at least one element is different.
Example 1:
Input: n = 4
Output: 184
Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.
Example 2:
Input: n = 2
Output: 22
Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.
Constraints:
1 <= n <= 10000
| class Solution:
def distinctSequences(self, n: int) -> int:
@functools.lru_cache(None)
def solve(t=0, his=(17, 17)) :
if t == n :
return 1
to_ret = 0
for i in range(1, 7) :
if not math.gcd(i, his[1]) == 1 :
continue
if i == his[0] or i == his[1] :
continue
to_ret += solve(t+1, (his[1], i))
return to_ret % (10**9+7)
return solve() |
a5d2ca | 0b4803 | You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
The greatest common divisor of any adjacent values in the sequence is equal to 1.
There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 10^9 + 7.
Two sequences are considered distinct if at least one element is different.
Example 1:
Input: n = 4
Output: 184
Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.
Example 2:
Input: n = 2
Output: 22
Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.
Constraints:
1 <= n <= 10000
| class Solution(object):
def distinctSequences(self, n):
"""
:type n: int
:rtype: int
"""
# f[n][a][b] = sum_{i} f[n-1][i][a], a,b互质且a!=b且i!=b
# ..., i, a, b
MODB = 1000000000+7
are_prime = set() # and not equal
for x, y in {
(1,2), (1,3), (1,4), (1,5), (1,6),
(2,3), (2,5),
(3,4), (3,5),
(4,5),
(5,6)
}:
are_prime.add((x,y))
are_prime.add((y,x))
for x in range(7):
are_prime.add((0, x))
are_prime.add((x, 0))
f = [[[0]*7 for _ in range(7)] for _ in range(n+1)]
f[0][0][0] = 1
for k in range(1, n+1):
for a in range(0, 7):
for b in range(1, 7):
tmp = 0
if (a,b) in are_prime:
for i in range(0, 7):
if i != b:
tmp = (tmp+f[k-1][i][a]) % MODB
f[k][a][b] = tmp
res = 0
for a in range(0, 7):
for b in range(0, 7):
res = (res + f[n][a][b]) % MODB
return res
|
bed258 | bedfdb | You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.
Return a boolean array answer where answer[i] is the result of the ith query queries[i].
Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.
Example :
Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
Output: [true,false,false,true,true]
Explanation:
queries[0]: substring = "d", is palidrome.
queries[1]: substring = "bc", is not palidrome.
queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.
Example 2:
Input: s = "lyb", queries = [[0,1,0],[2,2,1]]
Output: [false,true]
Constraints:
1 <= s.length, queries.length <= 100000
0 <= lefti <= righti < s.length
0 <= ki <= s.length
s consists of lowercase English letters.
| class Solution:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
qdict = [{}]
curdict = {}
for c in s:
curdict[c] = curdict.get(c, 0) + 1
qdict.append({k:v for k, v in curdict.items()})
ret = []
for left, right, k in queries:
dff = 0
for c, n in qdict[right + 1].items():
if (n - qdict[left].get(c, 0)) % 2:
dff += 1
ret.append(dff >> 1 <= k)
return ret |
420bee | bedfdb | You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.
Return a boolean array answer where answer[i] is the result of the ith query queries[i].
Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.
Example :
Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
Output: [true,false,false,true,true]
Explanation:
queries[0]: substring = "d", is palidrome.
queries[1]: substring = "bc", is not palidrome.
queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.
Example 2:
Input: s = "lyb", queries = [[0,1,0],[2,2,1]]
Output: [false,true]
Constraints:
1 <= s.length, queries.length <= 100000
0 <= lefti <= righti < s.length
0 <= ki <= s.length
s consists of lowercase English letters.
| class Solution(object):
def canMakePaliQueries(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[bool]
"""
h = [0]
for c in s: h.append(h[-1] ^ (1 << (ord(c) - ord('a'))))
r = []
for left, right, k in queries:
v = h[right+1] ^ h[left]
m = 0
while v:
v ^= v & -v
m += 1
r.append((m + (right - left) % 2) // 2 <= k)
return r
|
72703c | 8e3aa7 | You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.
For chosen indices i0, i1, ..., ik - 1, your score is defined as:
The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.
It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).
Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.
Example 1:
Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
Output: 12
Explanation:
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
Example 2:
Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
Output: 30
Explanation:
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 100000
0 <= nums1[i], nums2[j] <= 100000
1 <= k <= n
| from sortedcontainers import SortedList
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
p = [[a, b] for (a, b) in zip(nums1, nums2)]
p.sort(key=lambda x: x[1], reverse=True)
stl = SortedList()
res = 0
cur = p[0][1]
curs = 0
for a, b in p:
cur = min(cur, b)
if len(stl) < k:
curs += a
else:
u = stl[-k]
if a > u:
curs += a - u
stl.add(a)
if len(stl) >= k:
res = max(res, cur * curs)
return res
|
b06347 | 8e3aa7 | You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.
For chosen indices i0, i1, ..., ik - 1, your score is defined as:
The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.
It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).
Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.
Example 1:
Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
Output: 12
Explanation:
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
Example 2:
Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
Output: 30
Explanation:
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 100000
0 <= nums1[i], nums2[j] <= 100000
1 <= k <= n
| class Solution(object):
def maxScore(self, A, B, k):
total = res = 0
h = []
for a,b in sorted(list(zip(A, B)), key=lambda ab: -ab[1]):
heappush(h, a)
total += a
if len(h) > k:
total -= heappop(h)
if len(h) == k:
res = max(res, total * b)
return res |
a001e6 | d61283 | You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.
To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].
In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.
Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.
Example 1:
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
Explanation: The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
Example 2:
Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
Output: 23
Example 3:
Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
Output: 1
Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
Constraints:
0 <= edges.length <= min(n * (n - 1) / 2, 10000)
edges[i].length == 3
0 <= ui < vi < n
There are no multiple edges in the graph.
0 <= cnti <= 10000
0 <= maxMoves <= 10^9
1 <= n <= 3000
| from heapq import heappush, heappop
class Solution:
def reachableNodes(self, edges, M, N):
"""
:type edges: List[List[int]]
:type M: int
:type N: int
:rtype: int
"""
es = [{} for _ in range(N)]
for i, j, n in edges:
es[i][j] = [n, 0]
es[j][i] = [n, 0]
ans = 0
pq = [(-M, 0)]
v = [False] * N
while pq:
r, i = heappop(pq)
r = -r
if v[i]: continue
v[i] = True
ans += 1
for j, x in es[i].items():
delta = min(r, x[0] - es[j][i][1])
ans += delta
x[1] = delta
if r > x[0] and not v[j]:
heappush(pq, (x[0]+1-r,j))
return ans
|
7246e2 | d61283 | You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.
To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].
In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.
Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.
Example 1:
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
Explanation: The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
Example 2:
Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
Output: 23
Example 3:
Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
Output: 1
Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
Constraints:
0 <= edges.length <= min(n * (n - 1) / 2, 10000)
edges[i].length == 3
0 <= ui < vi < n
There are no multiple edges in the graph.
0 <= cnti <= 10000
0 <= maxMoves <= 10^9
1 <= n <= 3000
| class Solution(object):
def reachableNodes(self, edges, M, N):
"""
:type edges: List[List[int]]
:type M: int
:type N: int
:rtype: int
"""
b=[(0,M)]
seen={0:M}
m=collections.defaultdict(dict)
rec={}
for s,e,c in edges:
m[s][e]=c
m[e][s]=c
rec[(s,e)]=0
rec[(e,s)]=0
i=0
while i<len(b):
cur,left=b[i]
for t in m[cur]:
step=left-m[cur][t]-1
if step>=0 and (t not in seen or seen[t]<step):
seen[t]=step
b.append((t,step))
rec[(cur,t)]=m[cur][t]
else:
rec[(cur,t)]=max(rec[(cur,t)],left)
i+=1
ans=len(seen)
for s,e,c in edges:
ans+=min(c,rec[(s,e)]+rec[(e,s)])
return ans
|
802427 | f2b7a3 | In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.
Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.
Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button.
At the stage of rotating the ring to spell the key character key[i]:
You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i].
If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.
Example 1:
Input: ring = "godding", key = "gd"
Output: 4
Explanation:
For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
Also, we need 1 more step for spelling.
So the final output is 4.
Example 2:
Input: ring = "godding", key = "godding"
Output: 13
Constraints:
1 <= ring.length, key.length <= 100
ring and key consist of only lower case English letters.
It is guaranteed that key could always be spelled by rotating ring.
| class Solution(object):
def findRotateSteps(self, ring, key):
def get(i):
return ring[i % len(ring)]
memo = {}
def dp(pos, k):
if (pos, k) in memo:
return memo[pos, k]
if k == len(key):
return 0
lo = hi = pos
himove = lomove = 0
while get(hi) != key[k]:
hi += 1
himove += 1
while get(lo) != key[k]:
lo -= 1
lomove += 1
lo %= len(ring)
hi %= len(ring)
ans = min(dp(lo, k+1) + lomove, dp(hi, k+1) + himove)
memo[pos, k] = ans
return ans
return dp(0, 0) + len(key) |
c803ed | 4e390e | Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.
Two formulas are concatenated together to produce another formula.
For example, "H2O2He3Mg4" is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
For example, "(H2O2)" and "(H2O2)3" are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
Example 1:
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Constraints:
1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid.
| from collections import defaultdict
class Solution(object):
def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
def getDict(formula):
cur = 0
answer = defaultdict(lambda : 0)
while cur < len(formula):
if formula[cur] == '(':
i = cur + 1
depth = 1
while depth > 0:
if formula[i] == '(':
depth += 1
elif formula[i] == ')':
depth -= 1
i += 1
numIndex = i
while i < len(formula) and formula[i].isdigit():
i += 1
nextIndex = i
times = 1 if numIndex == nextIndex else int(formula[numIndex:nextIndex])
subDict = getDict(formula[cur + 1: numIndex - 1])
for k, v in subDict.items():
answer[k] += v * times
cur = nextIndex
else:
i = cur + 1
while i < len(formula) and formula[i].islower():
i += 1
numIndex = i
while i < len(formula) and formula[i].isdigit():
i += 1
nextIndex = i
times = 1 if numIndex == nextIndex else int(formula[numIndex:nextIndex])
element = formula[cur:numIndex]
answer[element] += times
cur = nextIndex
return answer
d = getDict(formula)
items = sorted(d.items())
answer = []
for k, v in items:
answer.append(k)
if v > 1:
answer.append(str(v))
return ''.join(answer)
# print Solution().countOfAtoms("K4(ON(SO3)2)2") |
138046 | 4e390e | Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.
Two formulas are concatenated together to produce another formula.
For example, "H2O2He3Mg4" is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
For example, "(H2O2)" and "(H2O2)3" are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
Example 1:
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Constraints:
1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid.
| import re
class Solution:
def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
def add(a, b):
c = {}
keys = set(a.keys()) | set(b.keys())
for k in keys:
c[k] = a.get(k, 0) + b.get(k, 0)
return c
def mul(a, t):
return {k: t * v for k, v in a.items()}
def count(f):
if not f:
return dict()
p = f.find('(')
if p == -1:
fs = []
for s in re.split('([A-Z][a-z]?)', f):
if s:
fs.append(s)
ans = {}
for i, s in enumerate(fs):
if s[0] in '1234567890':
continue
c = 1
if i + 1 < len(fs) and fs[i + 1][0] in '1234567890':
c = int(fs[i + 1])
ans[s] = ans.get(s, 0) + c
return ans
c = 1
q = p + 1
while q < len(f) and c != 0:
if f[q] == '(':
c += 1
elif f[q] == ')':
c -= 1
q += 1
f1 = f[:p]
f2 = f[p + 1:q - 1]
t = 1
if q < len(f) and f[q] in '1234567890':
c = ''
while q < len(f) and f[q] in '1234567890':
c += f[q]
q += 1
t = int(c)
f3 = f[q:]
ans = mul(count(f2), t)
ans = add(count(f1), ans)
ans = add(count(f3), ans)
return ans
atoms = count(formula)
atoms = sorted(atoms.items())
ans = ''
for k, v in atoms:
ans += k
if v > 1:
ans += str(v)
return ans |
97d2d7 | 0c6582 | You are given an array nums of positive integers and a positive integer k.
A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.
Return the number of non-empty beautiful subsets of the array nums.
A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [2,4,6], k = 2
Output: 4
Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
Example 2:
Input: nums = [1], k = 1
Output: 1
Explanation: The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
Constraints:
1 <= nums.length <= 20
1 <= nums[i], k <= 1000
| class Solution(object):
def beautifulSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
s = set()
def f(i):
a = (1 if len(s) else 0) if i == len(nums) else 2 * f(i + 1) if nums[i] in s else f(i + 1)
if i != len(nums) and not nums[i] in s and not nums[i] - k in s and not nums[i] + k in s:
s.add(nums[i])
a += f(i + 1)
s.remove(nums[i])
return a
return f(0) |
b26bad | 0c6582 | You are given an array nums of positive integers and a positive integer k.
A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.
Return the number of non-empty beautiful subsets of the array nums.
A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [2,4,6], k = 2
Output: 4
Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
Example 2:
Input: nums = [1], k = 1
Output: 1
Explanation: The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
Constraints:
1 <= nums.length <= 20
1 <= nums[i], k <= 1000
| from itertools import combinations
class Solution:
def beautifulSubsets(self, nums: List[int], k: int) -> int:
answer = 0
n = len(nums)
nums.sort()
start = [[]]
for x in nums:
next_s = []
for y in start:
next_s.append(y)
if x-k not in y:
next_s.append(y+[x])
start = next_s
return len(start)-1
|
da40ce | 39a231 |
Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Example 1:
Input: arr = [9,12,3,7,15], target = 5
Output: 2
Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
Example 2:
Input: arr = [1000000,1000000,1000000], target = 1
Output: 999999
Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
Example 3:
Input: arr = [1,2,4,8,16], target = 0
Output: 0
Constraints:
1 <= arr.length <= 100000
1 <= arr[i] <= 1000000
0 <= target <= 10^7
| class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
if target in arr:
return 0
old_arr = arr
arr = [old_arr[0]]
for i in range(1,len(old_arr)):
if old_arr[i] != arr[-1]:
arr.append(old_arr[i])
best = abs(target - arr[0])
for i in range(len(arr)):
cur = arr[i]
best = min(best, abs(target - cur))
for j in range(i+1,len(arr)):
cur &= arr[j]
best = min(best, abs(target - cur))
if cur < target:
break
return best |
e2279c | 39a231 |
Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Example 1:
Input: arr = [9,12,3,7,15], target = 5
Output: 2
Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
Example 2:
Input: arr = [1000000,1000000,1000000], target = 1
Output: 999999
Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
Example 3:
Input: arr = [1,2,4,8,16], target = 0
Output: 0
Constraints:
1 <= arr.length <= 100000
1 <= arr[i] <= 1000000
0 <= target <= 10^7
| from itertools import groupby
class Solution(object):
def closestToTarget(self, arr, target):
"""
:type arr: List[int]
:type target: int
:rtype: int
"""
n = len(arr)
r = abs(arr[0] - target)
k = max(arr).bit_length()
p = [[n]*(n+1) for _ in xrange(k)]
for t in xrange(k):
x = 1 << t
for i in xrange(len(arr)-1, -1, -1):
p[t][i] = p[t][i+1] if x&arr[i] else i
for i in xrange(n):
x = arr[i]
r = min(r, abs(x-target))
for j in sorted(set(p[t][i] for t in xrange(k) if x&(1<<t))):
if j >= n: break
x &= arr[j]
r = min(r, abs(x-target))
if x < target: break
return r |
118d32 | d7aed8 | You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
You will do the following steps repeatedly until all cards are revealed:
Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
Note that the first entry in the answer is considered to be the top of the deck.
Example 1:
Input: deck = [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
Example 2:
Input: deck = [1,1000]
Output: [1,1000]
Constraints:
1 <= deck.length <= 1000
1 <= deck[i] <= 1000000
All the values of deck are unique.
| class Solution(object):
def deckRevealedIncreasing(self, deck):
"""
:type deck: List[int]
:rtype: List[int]
"""
a = range(len(deck))
b = []
p = 0
while a:
b.extend(a[p::2])
c = a[1-p::2]
p = (p+len(a))%2
a = c
r = deck[:]
for i, v in enumerate(sorted(deck)): r[b[i]] = v
return r |
e029d4 | d7aed8 | You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
You will do the following steps repeatedly until all cards are revealed:
Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
Note that the first entry in the answer is considered to be the top of the deck.
Example 1:
Input: deck = [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
Example 2:
Input: deck = [1,1000]
Output: [1,1000]
Constraints:
1 <= deck.length <= 1000
1 <= deck[i] <= 1000000
All the values of deck are unique.
| class Solution:
def deckRevealedIncreasing(self, a):
"""
:type deck: List[int]
:rtype: List[int]
"""
a = sorted(a)
n = len(a)
b = list(range(n))
i = 0
ans = []
for t in range(n):
ans += [b[i]]
i += 1
if i < len(b):
b += [b[i]]
i += 1
print(ans)
s = [0] * n
for i in range(n):
s[ans[i]] = a[i]
# s = [a[ans[b[i]]] for i in range(n)]
return s |
ffc339 | d47b95 | You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.
In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.
For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can:
place stamp at index 0 of s to obtain "abc??",
place stamp at index 1 of s to obtain "?abc?", or
place stamp at index 2 of s to obtain "??abc".
Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).
We want to convert s to target using at most 10 * target.length turns.
Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.
Example 1:
Input: stamp = "abc", target = "ababc"
Output: [0,2]
Explanation: Initially s = "?????".
- Place stamp at index 0 to get "abc??".
- Place stamp at index 2 to get "ababc".
[1,0,2] would also be accepted as an answer, as well as some other answers.
Example 2:
Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]
Explanation: Initially s = "???????".
- Place stamp at index 3 to get "???abca".
- Place stamp at index 0 to get "abcabca".
- Place stamp at index 1 to get "aabcaca".
Constraints:
1 <= stamp.length <= target.length <= 1000
stamp and target consist of lowercase English letters.
| class Solution(object):
def movesToStamp(self, stamp, target):
"""
:type stamp: str
:type target: str
:rtype: List[int]
"""
s = list(target)
r = []
c, m, n = 0, len(stamp), len(target)
def find():
i = j = k = 0
while i < n:
if s[i] == '?':
j += 1
elif s[i] == stamp[j]:
j += 1
k += 1
else:
i -= j
j = k = 0
i += 1
if j == m:
if k:
return i - m
else:
j -= 1
return None
while c < n:
i = find()
if i is None: return []
r.append(i)
for j in xrange(i, i+m):
if s[j] != '?':
s[j] = '?'
c += 1
return r[::-1] |
f1f515 | d47b95 | You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.
In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.
For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can:
place stamp at index 0 of s to obtain "abc??",
place stamp at index 1 of s to obtain "?abc?", or
place stamp at index 2 of s to obtain "??abc".
Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).
We want to convert s to target using at most 10 * target.length turns.
Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.
Example 1:
Input: stamp = "abc", target = "ababc"
Output: [0,2]
Explanation: Initially s = "?????".
- Place stamp at index 0 to get "abc??".
- Place stamp at index 2 to get "ababc".
[1,0,2] would also be accepted as an answer, as well as some other answers.
Example 2:
Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]
Explanation: Initially s = "???????".
- Place stamp at index 3 to get "???abca".
- Place stamp at index 0 to get "abcabca".
- Place stamp at index 1 to get "aabcaca".
Constraints:
1 <= stamp.length <= target.length <= 1000
stamp and target consist of lowercase English letters.
| class Solution:
def movesToStamp(self, stamp, target):
"""
:type stamp: str
:type target: str
:rtype: List[int]
"""
n = len(stamp)
tlen = len(target)
if stamp[0] != target[0]:
return []
if stamp[-1] != target[-1]:
return []
error = False
def draw(start, end):
nonlocal error
#print(start,end)
if start >= end:
return []
#if end - start >= n:
# pos = target.find(stamp, start, end)
# if pos >= 0:
# return draw(start, pos) + draw(pos + n, end) + [pos]
for j in range(max(0, start - n + 1), min(tlen, end)):
ok = True
for k in range(max(start, j), min(end, j + n)):
if target[k] != stamp[k - j]:
ok = False
break
if ok:
return draw(start, j) + draw(j + n, end) + [j]
error = True
return []
res = draw(0, tlen)
if error:
return []
return res |
96ea3f | 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:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
from bisect import bisect_left
gg = defaultdict(list)
for i,x in enumerate(nums):
gg[x].append(i)
rv = []
for l,r in queries:
valid = []
for i in range(1,101):
j = bisect_left(gg[i],l)
if j>=len(gg[i]) or gg[i][j]>r:
continue
else:
valid.append(i)
if len(valid)<=1:
rv.append(-1)
continue
v = 101
for i in range(len(valid)-1):
v = min(v,valid[i+1]-valid[i])
rv.append(v)
return rv |