sol_id
stringlengths 6
6
| problem_id
stringlengths 6
6
| problem_text
stringlengths 322
4.55k
| solution_text
stringlengths 137
5.74k
|
---|---|---|---|
9cd02a | 83e046 | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.
You start your journey from building 0 and move to the next building by possibly using bricks or ladders.
While moving from building i to building i+1 (0-indexed),
If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.
Example 1:
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 >= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
- Go to building 3 without using ladders nor bricks since 7 >= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
Example 2:
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7
Example 3:
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3
Constraints:
1 <= heights.length <= 100000
1 <= heights[i] <= 1000000
0 <= bricks <= 10^9
0 <= ladders <= heights.length
| class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
n = len(heights)
def check(index):
gap = []
for i in range(1, index+1):
if heights[i] - heights[i-1] > 0:
gap.append(heights[i] - heights[i-1])
gap.sort(reverse=True)
if ladders >= len(gap):
return True
else:
return sum(gap[ladders:]) <= bricks
l, r = 0, n - 1
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l |
b3eff0 | bab122 | You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i] is a non-decreasing array.
| from heapq import heappop, heappush
class Solution(object):
def kthSmallest(self, mat, k):
"""
:type mat: List[List[int]]
:type k: int
:rtype: int
"""
a = mat
n, m = len(a), len(a[0])
q = []
r = 0
s = set()
def consider(v):
k = tuple(v)
if k in s: return
heappush(q, [sum(a[i][x] for i,x in enumerate(v))] + v)
s.add(k)
consider([0]*n)
for _ in xrange(k):
u = heappop(q)
r = u.pop(0)
for i in xrange(n):
if u[i]+1 < len(a[i]):
u[i] += 1
consider(u)
u[i] -= 1
return r |
0435fd | bab122 | You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i] is a non-decreasing array.
| class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
m, n = len(mat), len(mat[0])
h = []
temp = [sum(row[0] for row in mat)] + [0]*m
temp = tuple(temp)
h = [temp]
check = set(tuple([0]*m))
count = 0
while h:
#print(h, h[0])
t = heapq.heappop(h)
count += 1
s = t[0]
if count == k:
return s
cur = list(t[1:])
for i,v in enumerate(cur):
if v < n - 1:
cur[i] += 1
if tuple(cur) not in check:
check.add(tuple(cur))
heapq.heappush(h, tuple([t[0] + mat[i-1][cur[i]] - mat[i-1][cur[i] - 1]] + cur))
cur[i] -= 1 |
0b40cb | 74b03d | You are given an array colors, in which there are three colors: 1, 2 and 3.
You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.
Example 1:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
Output: [3,0,3]
Explanation:
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
Input: colors = [1,2], queries = [[0,3]]
Output: [-1]
Explanation: There is no 3 in the array.
Constraints:
1 <= colors.length <= 5*10^4
1 <= colors[i] <= 3
1 <= queries.length <= 5*10^4
queries[i].length == 2
0 <= queries[i][0] < colors.length
1 <= queries[i][1] <= 3
| class Solution(object):
def shortestDistanceColor(self, colors, queries):
N = len(colors)
lefts = []
rights = []
for _ in xrange(3):
lefts.append([None] * N)
rights.append([None] * N)
lasts = [None, None, None]
for i, c in enumerate(colors):
lasts[c-1] = i
for j in xrange(3):
lefts[j][i] = lasts[j]
lasts = [None, None, None]
for i in xrange(N-1,-1,-1):
c = colors[i]
lasts[c-1] = i
for j in xrange(3):
rights[j][i] = lasts[j]
def solve(query):
i, c = query
left = lefts[c-1][i]
if left is not None: left = i-left
right = rights[c-1][i]
if right is not None: right = right-i
ans = 2 * N
if left is not None and left < ans:
ans = left
if right is not None and right < ans:
ans = right
if ans >= 2 * N:
ans = -1
return ans
return map(solve, queries) |
14a223 | 74b03d | You are given an array colors, in which there are three colors: 1, 2 and 3.
You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.
Example 1:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
Output: [3,0,3]
Explanation:
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
Input: colors = [1,2], queries = [[0,3]]
Output: [-1]
Explanation: There is no 3 in the array.
Constraints:
1 <= colors.length <= 5*10^4
1 <= colors[i] <= 3
1 <= queries.length <= 5*10^4
queries[i].length == 2
0 <= queries[i][0] < colors.length
1 <= queries[i][1] <= 3
| class Solution:
def shortestDistanceColor(self, a: List[int], queries: List[List[int]]) -> List[int]:
INF = 10000000
n = len(a)
nearLeft = [[], [INF] * n,[INF] * n,[INF] * n]
nearRight = [[], [INF] * n,[INF] * n,[INF] * n]
for i in range(0, n):
x = a[i]
for c in [1,2,3]:
if x == c:
nearLeft[c][i] = 0
else:
if i == 0:
nearLeft[c][i] = INF
else:
nearLeft[c][i] = min(INF, nearLeft[c][i - 1] + 1)
for i in reversed(range(0, n)):
x = a[i]
for c in [1,2,3]:
if x == c:
nearRight[c][i] = 0
else:
if i == n - 1:
nearRight[c][i] = INF
else:
nearRight[c][i] = nearRight[c][i + 1] + 1
ans = []
for q in queries:
[i, x] = q
y = min(nearLeft[x][i], nearRight[x][i])
if y == INF:
y = -1
ans.append(y)
return ans |
77776e | 4e5f56 | You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.
You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.
Divide the nodes of the graph into m groups (1-indexed) such that:
Each node in the graph belongs to exactly one group.
For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.
Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.
Example 1:
Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]
Output: 4
Explanation: As shown in the image we:
- Add node 5 to the first group.
- Add node 1 to the second group.
- Add nodes 2 and 4 to the third group.
- Add nodes 3 and 6 to the fourth group.
We can see that every edge is satisfied.
It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.
Example 2:
Input: n = 3, edges = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.
It can be shown that no grouping is possible.
Constraints:
1 <= n <= 500
1 <= edges.length <= 10000
edges[i].length == 2
1 <= ai, bi <= n
ai != bi
There is at most one edge between any pair of vertices.
| class UnionFind:
def __init__(self, n):
self.parent = list(range(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 merge(self, a, b):
self.parent[self.find(b)] = self.find(a)
class Solution:
def magnificentSets(self, n: int, edges: List[List[int]]) -> int:
path = defaultdict(list)
union = UnionFind(n+1)
for x, y in edges:
union.merge(x, y)
path[x].append(y)
path[y].append(x)
ans = [-1] *(n+1)
for i in range(1, n+1):
if ans[i] == -1:
ans[i] = 0
q = deque([i])
while q:
p = q.popleft()
for newp in path[p]:
if ans[newp] == -1:
ans[newp] = 1 - ans[p]
q.append(newp)
elif ans[newp] + ans[p] != 1: return -1
visited = defaultdict(int)
for i in range(1, n+1):
ans[i] = 0
q = deque([i])
v = {i}
cnt = 0
while q:
cnt += 1
for _ in range(len(q)):
p = q.popleft()
for newp in path[p]:
if newp not in v:
v.add(newp)
q.append(newp)
visited[union.find(i)] = max(visited[union.find(i)], cnt)
return sum(visited.values()) |
bfd104 | 4e5f56 | You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.
You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.
Divide the nodes of the graph into m groups (1-indexed) such that:
Each node in the graph belongs to exactly one group.
For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.
Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.
Example 1:
Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]
Output: 4
Explanation: As shown in the image we:
- Add node 5 to the first group.
- Add node 1 to the second group.
- Add nodes 2 and 4 to the third group.
- Add nodes 3 and 6 to the fourth group.
We can see that every edge is satisfied.
It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.
Example 2:
Input: n = 3, edges = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.
It can be shown that no grouping is possible.
Constraints:
1 <= n <= 500
1 <= edges.length <= 10000
edges[i].length == 2
1 <= ai, bi <= n
ai != bi
There is at most one edge between any pair of vertices.
| class Solution(object):
def magnificentSets(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
e = [(u -1, v - 1) for u, v in edges]
adj = [[] for _ in range(n)]
for u, v in e:
adj[u].append(v)
adj[v].append(u)
best = [0] * n
bad = False
for i in range(n):
curr = [-1] * n
curr[i] = 0
up = [i]
it = 0
while up:
nex = []
it += 1
for u in up:
assert curr[u] == it - 1
for v in adj[u]:
if curr[v] == it - 1:
bad = True
elif curr[v] == -1:
curr[v] = it
nex.append(v)
up = nex
val = max(curr) + 1
for i in range(n):
if curr[i] != -1:
best[i] = max(best[i], val)
break
if bad:
return -1
return sum(best)
|
c71255 | bc3478 | Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 10^9 + 7.
Note:
A string is palindromic if it reads the same forward and backward.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = "103301"
Output: 2
Explanation:
There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301".
Two of them (both equal to "10301") are palindromic.
Example 2:
Input: s = "0000000"
Output: 21
Explanation: All 21 subsequences are "00000", which is palindromic.
Example 3:
Input: s = "9999900000"
Output: 2
Explanation: The only two palindromic subsequences are "99999" and "00000".
Constraints:
1 <= s.length <= 10000
s consists of digits.
| mod = 10 ** 9 + 7
class Solution:
def countPalindromes(self, s: str) -> int:
@cache
def getRes(idx, v, flag):
if len(v) == 0 and flag:
return 1
if idx == len(s):
if len(v) == 0 and flag:
return 1
return 0
ans = getRes(idx+1, v, flag)
if not flag:
if len(v) < 2:
ans += getRes(idx+1, v+s[idx], flag)
else:
ans += getRes(idx+1, v, True)
elif v[-1] == s[idx]:
ans += getRes(idx+1, v[:-1], flag)
return ans % mod
ans = getRes(0, '', False)
getRes.cache_clear()
return ans |
1cad49 | bc3478 | Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 10^9 + 7.
Note:
A string is palindromic if it reads the same forward and backward.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = "103301"
Output: 2
Explanation:
There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301".
Two of them (both equal to "10301") are palindromic.
Example 2:
Input: s = "0000000"
Output: 21
Explanation: All 21 subsequences are "00000", which is palindromic.
Example 3:
Input: s = "9999900000"
Output: 2
Explanation: The only two palindromic subsequences are "99999" and "00000".
Constraints:
1 <= s.length <= 10000
s consists of digits.
| class Solution(object):
def countPalindromes(self, s):
"""
:type s: str
:rtype: int
"""
dp = {}
n = len(s)
s = [ord(c)-ord('0') for c in s]
mod = 1000000007
dp2 = {}
cs = [[0]*10 for _ in range(n+1)]
i = n-1
while i>=0:
for k in range(10): cs[i][k]=cs[i+1][k]
cs[i][s[i]]+=1
i-=1
def dfs2(a, b, i):
if i>=n: return 0
kk = (a, b, i)
if kk in dp2: return dp2[kk]
r = dfs2(a, b, i+1)
if s[i]==b:
r+=cs[i+1][a]
r%=mod
dp2[kk]=r
return r
def dfs(a, b, i):
if i>=n: return 0
kk = (a, b, i)
if kk in dp: return dp[kk]
r = dfs(a, b, i+1)
if a!=-1:
r += dfs2(b, a, i+1)
else:
if b!=-1:
r+=dfs(s[i], b, i+1)
else:
r+=dfs(a, s[i], i+1)
r%=mod
dp[kk]=r
return r
return dfs(-1, -1, 0) |
12de8d | 7e772f | You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.
| class Solution(object):
def dfs(self, i, j, col, grid):
grid[i][j] = col
stack = [(i, j)]
sz = 1
while stack:
i, j = stack.pop()
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni = i + di
nj = j + dj
if ni >= 0 and ni < len(grid) and nj >= 0 and nj < len(grid[0]) and grid[ni][nj] == 1:
grid[ni][nj] = col
sz += 1
stack.append((ni, nj))
return sz
def largestIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
N = len(grid)
M = len(grid[0])
col = 1
mp = {}
mxsz = 0
for i in xrange(N):
for j in xrange(M):
if grid[i][j] == 1:
col += 1
mp[col] = self.dfs(i, j, col, grid)
mxsz = max(mp[col], mxsz)
for i in xrange(N):
for j in xrange(M):
newset = set([])
if grid[i][j] == 0:
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni = i + di
nj = j + dj
if ni >= 0 and ni < len(grid) and nj >= 0 and nj < len(grid[0]) and grid[ni][nj] != 0:
newset.add(grid[ni][nj])
newsize = 1 + sum([mp[s] for s in newset])
mxsz = max(mxsz, newsize)
return mxsz
|
8547cd | 7e772f | You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.
| class Solution:
def largestIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def root(f, a):
if f[a] != a:
f[a] = root(f, f[a])
return f[a]
def merge(f, a, b):
if root(f, a) == root(f, b):
return
f[root(f, a)] = root(f, b)
def idx(r, c, x, y):
return x * c + y
r = len(grid)
c = len(grid[0])
n = r * c
father = [i for i in range(n)]
for i in range(r):
for j in range(c):
for (s, t) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
if not 0 <= i + s < r or not 0 <= j + t < c:
continue
if grid[i][j] == 1 and grid[i + s][j + t] == 1:
# print(i, j, i + s, j + t)
merge(father, idx(r, c, i, j), idx(r, c, i + s, j + t))
# print([root(father, i) for i in range(n)])
cnt = [0 for _ in range(n)]
for i in range(r):
for j in range(c):
cnt[root(father, idx(r, c, i, j))] += 1
# print(cnt)
ans = max(cnt)
for i in range(r):
for j in range(c):
if grid[i][j] != 0:
continue
pool = set([])
if i > 0 and grid[i - 1][j] == 1:
pool.add(root(father, idx(r, c, i - 1, j)))
if i < r - 1 and grid[i + 1][j] == 1:
pool.add(root(father, idx(r, c, i + 1, j)))
if j > 0 and grid[i][j - 1] == 1:
pool.add(root(father, idx(r, c, i, j - 1)))
if j < c - 1 and grid[i][j + 1] == 1:
pool.add(root(father, idx(r, c, i, j + 1)))
cur = sum(cnt[e] for e in pool) + 1
# print(i, j, cur, pool)
ans = max(ans, cur)
return ans
|
467d14 | b8a00c | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1.
You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti.
Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph.
Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1.
A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.
Example 1:
Input: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5
Output: 9
Explanation:
The above figure represents the input graph.
The blue edges represent one of the subgraphs that yield the optimal answer.
Note that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.
Example 2:
Input: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2
Output: -1
Explanation:
The above figure represents the input graph.
It can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.
Constraints:
3 <= n <= 100000
0 <= edges.length <= 100000
edges[i].length == 3
0 <= fromi, toi, src1, src2, dest <= n - 1
fromi != toi
src1, src2, and dest are pairwise distinct.
1 <= weight[i] <= 100000
| from heapq import heappush, heappop
class Solution(object):
def minimumWeight(self, n, edges, src1, src2, dest):
"""
:type n: int
:type edges: List[List[int]]
:type src1: int
:type src2: int
:type dest: int
:rtype: int
"""
def sssp(adj, src):
dist = [float('inf')] * n
q = [(0, src)]
dist[src] = 0
while q:
du, u = heappop(q)
if du > dist[u]:
continue
for v, w in adj[u]:
dv = du + w
if dv < dist[v]:
heappush(q, (dv, v))
dist[v] = dv
return dist
adj = [[] for _ in xrange(n)]
adjt = [[] for _ in xrange(n)]
for u, v, w in edges:
adj[u].append((v, w))
adjt[v].append((u, w))
a = sssp(adj, src1)
b = sssp(adj, src2)
c = sssp(adjt, dest)
ans = min(a[i]+b[i]+c[i] for i in xrange(n))
return ans if ans < float('inf') else -1 |
fdec06 | b8a00c | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1.
You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti.
Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph.
Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1.
A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.
Example 1:
Input: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5
Output: 9
Explanation:
The above figure represents the input graph.
The blue edges represent one of the subgraphs that yield the optimal answer.
Note that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.
Example 2:
Input: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2
Output: -1
Explanation:
The above figure represents the input graph.
It can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.
Constraints:
3 <= n <= 100000
0 <= edges.length <= 100000
edges[i].length == 3
0 <= fromi, toi, src1, src2, dest <= n - 1
fromi != toi
src1, src2, and dest are pairwise distinct.
1 <= weight[i] <= 100000
| class Solution:
def minimumWeight(self, N: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:
e = collections.defaultdict(list)
er = collections.defaultdict(list)
for u, v, w in edges:
e[u].append((v, w))
er[v].append((u, w))
INF = 10 ** 10
def calc(e, start):
best = [INF] * N
best[start] = 0
h = []
heapq.heappush(h, (0, start))
while len(h) > 0:
d, current = heapq.heappop(h)
if d > best[current]:
continue
for v, w in e[current]:
if best[v] > d + w:
best[v] = d + w
heapq.heappush(h, (best[v], v))
return best
d1 = calc(e, src1)
d2 = calc(e, src2)
dd = calc(er, dest)
ans = INF * 5
for i in range(N):
ans = min(ans, d1[i] + d2[i] + dd[i])
if ans >= INF:
return -1
return ans |
64805b | f04fae | Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.
The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).
Example 1:
Input: nums = [3,1]
Output: 2
Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]
Example 2:
Input: nums = [2,2,2]
Output: 7
Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.
Example 3:
Input: nums = [3,2,1,5]
Output: 6
Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]
Constraints:
1 <= nums.length <= 16
1 <= nums[i] <= 100000
| class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
count = 0
best = 0
N = len(nums)
for x in nums:
best |= x
def go(index, current):
if index == N:
if current == best:
nonlocal count
count += 1
return
go(index + 1, current)
go(index + 1, current | nums[index])
go(0, 0)
return count |
3f32e7 | f04fae | Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.
The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).
Example 1:
Input: nums = [3,1]
Output: 2
Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]
Example 2:
Input: nums = [2,2,2]
Output: 7
Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.
Example 3:
Input: nums = [3,2,1,5]
Output: 6
Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]
Constraints:
1 <= nums.length <= 16
1 <= nums[i] <= 100000
| from collections import Counter
class Solution(object):
def countMaxOrSubsets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c = Counter()
c[0] += 1
for x in nums:
for k, v in c.items():
c[k|x] += v
return c[max(c)] |
21e61a | 2e4302 | You are given an integer n and an integer p in the range [0, n - 1]. Representing a 0-indexed array arr of length n where all positions are set to 0's, except position p which is set to 1.
You are also given an integer array banned containing some positions from the array. For the ith position in banned, arr[banned[i]] = 0, and banned[i] != p.
You can perform multiple operations on arr. In an operation, you can choose a subarray with size k and reverse the subarray. However, the 1 in arr should never go to any of the positions in banned. In other words, after each operation arr[banned[i]] remains 0.
Return an array ans where for each i from [0, n - 1], ans[i] is the minimum number of reverse operations needed to bring the 1 to position i in arr, or -1 if it is impossible.
A subarray is a contiguous non-empty sequence of elements within an array.
The values of ans[i] are independent for all i's.
The reverse of an array is an array containing the values in reverse order.
Example 1:
Input: n = 4, p = 0, banned = [1,2], k = 4
Output: [0,-1,-1,1]
Explanation: In this case k = 4 so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is 0. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is -1. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is 1.
Example 2:
Input: n = 5, p = 0, banned = [2,4], k = 3
Output: [0,-1,-1,-1,-1]
Explanation: In this case the 1 is initially at position 0, so the answer for that position is 0. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray [0, 2] for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0, making the result for all the other positions -1.
Example 3:
Input: n = 4, p = 2, banned = [0,1,3], k = 1
Output: [-1,-1,0,-1]
Explanation: In this case we can only perform reverse operations of size 1. So the 1 never changes its position.
Constraints:
1 <= n <= 100000
0 <= p <= n - 1
0 <= banned.length <= n - 1
0 <= banned[i] <= n - 1
1 <= k <= n
banned[i] != p
all values in banned are unique
| from sortedcontainers import SortedSet
class Solution(object):
def minReverseOperations(self, n, p, banned, k):
"""
:type n: int
:type p: int
:type banned: List[int]
:type k: int
:rtype: List[int]
"""
a, b, c, q, v = [-1] * n, [False] * n, [SortedSet(), SortedSet()], deque([p]), 0
for x in banned:
b[x] = True
for i in range(n):
if not b[i]:
c[i & 1].add(i)
c[p & 1].remove(p)
while q:
for s in range(len(q), 0, -1):
w = q.popleft()
a[w], x = v, c[abs(w - k + 1) & 1].bisect_right(abs(w - k + 1) - 1)
while x < len(c[abs(w - k + 1) & 1]) and c[abs(w - k + 1) & 1][x] <= n - 1 - abs(n - w - k):
q.append(c[abs(w - k + 1) & 1][x])
c[abs(w - k + 1) & 1].remove(c[abs(w - k + 1) & 1][x])
v += 1
return a |
c30ff2 | 2e4302 | You are given an integer n and an integer p in the range [0, n - 1]. Representing a 0-indexed array arr of length n where all positions are set to 0's, except position p which is set to 1.
You are also given an integer array banned containing some positions from the array. For the ith position in banned, arr[banned[i]] = 0, and banned[i] != p.
You can perform multiple operations on arr. In an operation, you can choose a subarray with size k and reverse the subarray. However, the 1 in arr should never go to any of the positions in banned. In other words, after each operation arr[banned[i]] remains 0.
Return an array ans where for each i from [0, n - 1], ans[i] is the minimum number of reverse operations needed to bring the 1 to position i in arr, or -1 if it is impossible.
A subarray is a contiguous non-empty sequence of elements within an array.
The values of ans[i] are independent for all i's.
The reverse of an array is an array containing the values in reverse order.
Example 1:
Input: n = 4, p = 0, banned = [1,2], k = 4
Output: [0,-1,-1,1]
Explanation: In this case k = 4 so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is 0. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is -1. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is 1.
Example 2:
Input: n = 5, p = 0, banned = [2,4], k = 3
Output: [0,-1,-1,-1,-1]
Explanation: In this case the 1 is initially at position 0, so the answer for that position is 0. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray [0, 2] for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0, making the result for all the other positions -1.
Example 3:
Input: n = 4, p = 2, banned = [0,1,3], k = 1
Output: [-1,-1,0,-1]
Explanation: In this case we can only perform reverse operations of size 1. So the 1 never changes its position.
Constraints:
1 <= n <= 100000
0 <= p <= n - 1
0 <= banned.length <= n - 1
0 <= banned[i] <= n - 1
1 <= k <= n
banned[i] != p
all values in banned are unique
| BL = 300
from collections import deque
class Solution:
def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]:
out = [-1] * n
op = [1] * n
out[p] = 0
op[p] = 0
for v in banned:
op[v] = 0
ect = [0] * (1 + n // BL)
oct = [0] * (1 + n // BL)
for i in range(0,n,2):
ect[i // BL] += op[i]
for i in range(1,n,2):
oct[i // BL] += op[i]
q = deque([p])
while q:
u = q.popleft()
d = out[u]
p = (u + k - 1) % 2
if p:
want = oct
else:
want = ect
l_sw = max(0, u - (k - 1))
r_sw = min(n - k, u)
left = 2 * l_sw + (k - 1) - u
right= 2 * r_sw + (k - 1) - u
#print(u, l_sw, r_sw, left, right)
assert left % 2 == right % 2 == p
while left <= right:
if want[left // BL]:
if op[left]:
out[left] = d + 1
op[left] = 0
want[left // BL] -= 1
q.append(left)
left += 2
else:
left = (300 * (left//BL + 1)) + p
return out
|
b31f48 | 532966 | Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]
Example 2:
Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]
Constraints:
The number of nodes in the tree is in the range [1, 5000].
-100000 <= Node.val <= 100000
-10^9 <= limit <= 10^9
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
def post_order(node, limit):
if node:
node.left, l_mx = post_order(node.left, limit - node.val)
node.right, r_mx = post_order(node.right, limit - node.val)
mx = node.val + max(l_mx, r_mx)
if mx >= limit:
return node, mx
else:
return None, mx
else:
return None, 0
ans, _ = post_order(root, limit)
return ans
|
de765f | 532966 | Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]
Example 2:
Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]
Constraints:
The number of nodes in the tree is in the range [1, 5000].
-100000 <= Node.val <= 100000
-10^9 <= limit <= 10^9
| # 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 sufficientSubset(self, root, limit):
"""
:type root: TreeNode
:type limit: int
:rtype: TreeNode
"""
return self.helper(root, limit)
def helper(self, node, limit):
if not node: return None
if not node.left and not node.right:
if node.val < limit:
return None
else:
return node
left = self.helper(node.left, limit - node.val)
right = self.helper(node.right, limit - node.val)
if not left and not right:
return None
else:
node.left = left
node.right = right
return node
|
af2656 | 971572 | An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
Concatenate the elements of the sequence to get the encoded string: "ab121p".
Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.
Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
Example 1:
Input: s1 = "internationalization", s2 = "i18n"
Output: true
Explanation: It is possible that "internationalization" was the original string.
- "internationalization"
-> Split: ["internationalization"]
-> Do not replace any element
-> Concatenate: "internationalization", which is s1.
- "internationalization"
-> Split: ["i", "nternationalizatio", "n"]
-> Replace: ["i", "18", "n"]
-> Concatenate: "i18n", which is s2
Example 2:
Input: s1 = "l123e", s2 = "44"
Output: true
Explanation: It is possible that "leetcode" was the original string.
- "leetcode"
-> Split: ["l", "e", "et", "cod", "e"]
-> Replace: ["l", "1", "2", "3", "e"]
-> Concatenate: "l123e", which is s1.
- "leetcode"
-> Split: ["leet", "code"]
-> Replace: ["4", "4"]
-> Concatenate: "44", which is s2.
Example 3:
Input: s1 = "a5b", s2 = "c5b"
Output: false
Explanation: It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.
Constraints:
1 <= s1.length, s2.length <= 40
s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
The number of consecutive digits in s1 and s2 does not exceed 3.
| class Solution(object):
def possiblyEquals(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
n1, n2 = len(s1), len(s2)
bal = [[set() for _ in xrange(n2+1)] for _ in xrange(n1+1)]
bal[0][0].add(0)
for i1 in xrange(n1+1):
for i2 in xrange(n2+1):
if i1 < n1 and s1[i1].isalpha() and i2 < n2 and s1[i1] == s2[i2]:
if 0 in bal[i1][i2]:
bal[i1+1][i2+1].add(0)
if i1 < n1:
if s1[i1].isalpha():
for b in bal[i1][i2]:
if b < 0:
bal[i1+1][i2].add(b+1)
else:
v = 0
for j1 in xrange(i1, n1):
if s1[j1].isalpha():
break
v = 10*v + int(s1[j1])
for b in bal[i1][i2]:
bal[j1+1][i2].add(b+v)
if i2 < n2:
if s2[i2].isalpha():
for b in bal[i1][i2]:
if b > 0:
bal[i1][i2+1].add(b-1)
else:
v = 0
for j2 in xrange(i2, n2):
if s2[j2].isalpha():
break
v = 10*v + int(s2[j2])
for b in bal[i1][i2]:
bal[i1][j2+1].add(b-v)
return 0 in bal[n1][n2] |
f48351 | 971572 | An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
Concatenate the elements of the sequence to get the encoded string: "ab121p".
Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.
Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
Example 1:
Input: s1 = "internationalization", s2 = "i18n"
Output: true
Explanation: It is possible that "internationalization" was the original string.
- "internationalization"
-> Split: ["internationalization"]
-> Do not replace any element
-> Concatenate: "internationalization", which is s1.
- "internationalization"
-> Split: ["i", "nternationalizatio", "n"]
-> Replace: ["i", "18", "n"]
-> Concatenate: "i18n", which is s2
Example 2:
Input: s1 = "l123e", s2 = "44"
Output: true
Explanation: It is possible that "leetcode" was the original string.
- "leetcode"
-> Split: ["l", "e", "et", "cod", "e"]
-> Replace: ["l", "1", "2", "3", "e"]
-> Concatenate: "l123e", which is s1.
- "leetcode"
-> Split: ["leet", "code"]
-> Replace: ["4", "4"]
-> Concatenate: "44", which is s2.
Example 3:
Input: s1 = "a5b", s2 = "c5b"
Output: false
Explanation: It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.
Constraints:
1 <= s1.length, s2.length <= 40
s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
The number of consecutive digits in s1 and s2 does not exceed 3.
| class Solution:
def possiblyEquals(self, s1: str, s2: str) -> bool:
def decompose(s):
lst = []
for i in range(3):
if i < len(s) and s[i].isdigit():
lst.append((int(s[:i+1]), s[i+1:]))
else:
break
if not lst:
lst.append((0, s))
return lst
# print(decompose(s1))
# print(decompose(s2))
@lru_cache(None)
def search(s1, s2, diff):
if diff < 0:
return search(s2, s1, -diff)
if diff == 0:
if s1 == s2:
return True
if not s1 or not s2:
return False
if s1[0].isdigit() or s2[0].isdigit():
for n1, sb1 in decompose(s1):
for n2, sb2 in decompose(s2):
if search(sb1, sb2, n1 - n2):
return True
else:
if s1[0] == s2[0]:
return search(s1[1:], s2[1:], diff)
else:
return False
else:
if not s2:
return False
if s2[0].isdigit():
for n2, sb2 in decompose(s2):
if search(s1, sb2, diff - n2):
return True
else:
return search(s1, s2[1:], diff-1)
return search(s1, s2, 0)
# @lru_cache(None)
# def search(s1, s2, diff):
# if diff == 0 and s1 == s2:
# return True
|
597ecb | ef8853 | Alice and Bob have an undirected graph of n nodes and three types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can be traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.
Example 1:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
Example 2:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
Example 3:
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
Output: -1
Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
Constraints:
1 <= n <= 100000
1 <= edges.length <= min(100000, 3 * n * (n - 1) / 2)
edges[i].length == 3
1 <= typei <= 3
1 <= ui < vi <= n
All tuples (typei, ui, vi) are distinct.
|
class DSU:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
self.sz[yr] = self.sz[xr]
return True
def size(self, x):
return self.sz[self.find(x)]
class Solution(object):
def maxNumEdgesToRemove(self, N, edges):
for row in edges:
# row[0] -= 1
row[1] -= 1
row[2] -= 1
alice = []
bob = []
both = []
for t, u, v in edges:
if t == 1:
alice.append([u,v])
elif t==2:
bob.append([u,v])
else:
both.append([u,v])
dsu1 = DSU(N)
dsu2 = DSU(N)
ans = 0
for u,v in both:
dsu2.union(u,v)
if not dsu1.union(u, v):
ans += 1
for u,v in alice:
if not dsu1.union(u,v): ans += 1
for u,v in bob:
if not dsu2.union(u,v): ans += 1
if dsu1.size(0) != N:
return -1
if dsu2.size(0) != N:
return -1
return ans |
6213ca | ef8853 | Alice and Bob have an undirected graph of n nodes and three types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can be traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.
Example 1:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
Example 2:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
Example 3:
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
Output: -1
Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
Constraints:
1 <= n <= 100000
1 <= edges.length <= min(100000, 3 * n * (n - 1) / 2)
edges[i].length == 3
1 <= typei <= 3
1 <= ui < vi <= n
All tuples (typei, ui, vi) are distinct.
| class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
parenta = [x for x in range(n+1)]
parentb = [x for x in range(n+1)]
def ufind(parent, x):
if parent[x] != x:
parent[x] = ufind(parent, parent[x])
return parent[x]
def uunion(parent, a, b):
ua = ufind(parent, a)
ub = ufind(parent, b)
parent[ua] = ub
edges.sort(key=lambda x: (-x[0]))
count = 0
for t, u, v in edges:
if t == 3:
if ufind(parenta, u) != ufind(parenta, v) or ufind(parentb, u) != ufind(parentb, v):
uunion(parenta, u, v)
uunion(parentb, u, v)
else:
count += 1
elif t == 2:
if ufind(parentb, u) != ufind(parentb, v):
uunion(parentb, u, v)
else:
count += 1
else:
if ufind(parenta, u) != ufind(parenta, v):
uunion(parenta, u, v)
else:
count += 1
roota = ufind(parenta, 1)
rootb = ufind(parentb, 1)
for x in range(1, n+1):
if ufind(parenta, x) != roota or ufind(parentb, x) != rootb:
return -1
return count |
b174d8 | a88c46 | Design a text editor with a cursor that can do the following:
Add text to where the cursor is.
Delete text from where the cursor is (simulating the backspace key).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.
void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
Example 1:
Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
Constraints:
1 <= text.length, k <= 40
text consists of lowercase English letters.
At most 2 * 10000 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
Follow-up: Could you find a solution with time complexity of O(k) per call?
| class TextEditor:
def __init__(self):
self.s1 = []
self.s2 = []
def addText(self, text: str) -> None:
self.s1 += list(text)
def deleteText(self, k: int) -> int:
res = 0
for i in range(min(len(self.s1), k)):
del self.s1[-1]
res += 1
return res
def cursorLeft(self, k: int) -> str:
for _ in range(k):
if not self.s1:
break
self.s2.append(self.s1.pop())
return "".join(self.s1[-10:])
def cursorRight(self, k: int) -> str:
for _ in range(k):
if not self.s2:
break
self.s1.append(self.s2.pop())
return "".join(self.s1[-10:])
# Your TextEditor object will be instantiated and called as such:
# obj = TextEditor()
# obj.addText(text)
# param_2 = obj.deleteText(k)
# param_3 = obj.cursorLeft(k)
# param_4 = obj.cursorRight(k) |
66c855 | a88c46 | Design a text editor with a cursor that can do the following:
Add text to where the cursor is.
Delete text from where the cursor is (simulating the backspace key).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.
void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
Example 1:
Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
Constraints:
1 <= text.length, k <= 40
text consists of lowercase English letters.
At most 2 * 10000 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
Follow-up: Could you find a solution with time complexity of O(k) per call?
| class TextEditor(object):
def __init__(self):
self.l, self.r = [], []
def addText(self, text):
"""
:type text: str
:rtype: None
"""
for c in text:
self.l.append(c)
def deleteText(self, k):
"""
:type k: int
:rtype: int
"""
r = 0
while self.l and k > 0:
self.l.pop()
r, k = r + 1, k - 1
return r
def cursorLeft(self, k):
"""
:type k: int
:rtype: str
"""
while self.l and k > 0:
self.r.append(self.l.pop())
k -= 1
s = []
for i in range(10):
if self.l:
s.append(self.l.pop())
for i in range(len(s) - 1, -1, -1):
self.l.append(s[i])
return ''.join(s[::-1])
def cursorRight(self, k):
"""
:type k: int
:rtype: str
"""
while self.r and k > 0:
self.l.append(self.r.pop())
k -= 1
s = []
for i in range(10):
if self.l:
s.append(self.l.pop())
for i in range(len(s) - 1, -1, -1):
self.l.append(s[i])
return ''.join(s[::-1])
# Your TextEditor object will be instantiated and called as such:
# obj = TextEditor()
# obj.addText(text)
# param_2 = obj.deleteText(k)
# param_3 = obj.cursorLeft(k)
# param_4 = obj.cursorRight(k) |
513965 | 9e1bdd | You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Constraints:
1 <= croakOfFrogs.length <= 100000
croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.
| class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
st = {
c : i
for i, c in enumerate('croak')
}
curr = [0 for _ in range(6)]
ans = 0
for c in croakOfFrogs:
if st[c] == 0:
curr[st[c]] += 1
elif curr[st[c] - 1] == 0:
return -1
else:
curr[st[c]] += 1
curr[st[c] - 1] -= 1
ans = max(ans, sum(curr[:4]))
if sum(curr[:4]) != 0:
return -1
else:
return ans |
4a0a20 | 9e1bdd | You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Constraints:
1 <= croakOfFrogs.length <= 100000
croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.
| class Solution(object):
def minNumberOfFrogs(self, S):
state = [0, 0, 0, 0, 0]
if len(S) % 5: return -1
ans = 0
for c in S:
i = 'croak'.find(c)
if i == -1: return -1
if i == 0:
ans += 1
if state[-1] >= 1:
state[-1] -= 1
ans -= 1
state[i] += 1
else:
if state[i-1]:
state[i-1] -= 1
state[i] += 1
else:
return -1
if sum(state) == state[-1]:
return ans
return -1 |
3dd0e2 | b2d2e3 | You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:
If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:
x + nums[i]
x - nums[i]
x ^ nums[i] (bitwise-XOR)
Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.
Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.
Example 1:
Input: nums = [2,4,12], start = 2, goal = 12
Output: 2
Explanation: We can go from 2 → 14 → 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12
Example 2:
Input: nums = [3,5,7], start = 0, goal = -4
Output: 2
Explanation: We can go from 0 → 3 → -4 with the following 2 operations.
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.
Example 3:
Input: nums = [2,8,16], start = 0, goal = 1
Output: -1
Explanation: There is no way to convert 0 into 1.
Constraints:
1 <= nums.length <= 1000
-10^9 <= nums[i], goal <= 10^9
0 <= start <= 1000
start != goal
All the integers in nums are distinct.
| class Solution(object):
def minimumOperations(self, nums, start, goal):
"""
:type nums: List[int]
:type start: int
:type goal: int
:rtype: int
"""
q = set([start])
vis = set()
dist = 0
while q:
if goal in q:
return dist
vis.update(q)
qq = set()
for u in q:
if 0 <= u <= 1000:
for x in nums:
for v in u+x, u-x, u^x:
if v not in vis:
qq.add(v)
q = qq
dist += 1
return -1 |
d7dda8 | b2d2e3 | You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:
If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:
x + nums[i]
x - nums[i]
x ^ nums[i] (bitwise-XOR)
Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.
Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.
Example 1:
Input: nums = [2,4,12], start = 2, goal = 12
Output: 2
Explanation: We can go from 2 → 14 → 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12
Example 2:
Input: nums = [3,5,7], start = 0, goal = -4
Output: 2
Explanation: We can go from 0 → 3 → -4 with the following 2 operations.
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.
Example 3:
Input: nums = [2,8,16], start = 0, goal = 1
Output: -1
Explanation: There is no way to convert 0 into 1.
Constraints:
1 <= nums.length <= 1000
-10^9 <= nums[i], goal <= 10^9
0 <= start <= 1000
start != goal
All the integers in nums are distinct.
| class Solution:
def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:
visited = set([start])
ops = [
lambda x, y: x + y,
lambda x, y: x - y,
lambda x, y: x ^ y,
]
lst = [start]
res = 1
while goal not in visited and lst:
lst_new = []
for v in lst:
for n in nums:
for op in ops:
vnew = op(v, n)
if vnew == goal:
return res
elif vnew not in visited and 0 <= vnew <= 1000:
visited.add(vnew)
lst_new.append(vnew)
lst = lst_new
res += 1
return -1
|
40d85d | db5f9a | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000
-1000000 <= xi, yi <= 1000000
All pairs (xi, yi) are distinct.
| class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
costs = []
for i in range(len(points)) :
xi, yi = points[i]
for j in range(i+1, len(points)) :
xj, yj = points[j]
costs.append([abs(xi-xj)+abs(yi-yj), i, j])
costs = sorted(costs)
fathers = {t:t for t in range(len(points))}
def get_father(n) :
while not fathers[n] == fathers[fathers[n]] :
fathers[n] = fathers[fathers[n]]
return fathers[n]
to_ret = 0
for t in costs :
ct, pi, pj = t
if get_father(pi) == get_father(pj) :
continue
fathers[get_father(pj)] = get_father(pi)
to_ret += ct
return to_ret
|
b938b4 | db5f9a | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000
-1000000 <= xi, yi <= 1000000
All pairs (xi, yi) are distinct.
| class DSU:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
#self.sz[yr] = self.sz[xr]
return True
def size(self, x):
return self.sz[self.find(x)]
class Solution(object):
def minCostConnectPoints(self, points):
n = len(points)
def dist(i, j):
return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
edges = []
for i in xrange(n):
for j in range(i + 1, n):
edges.append([dist(i, j), i, j])
edges.sort()
ans = 0
dsu = DSU(n)
for d, i, j in edges:
if dsu.union(i, j):
ans += d
return ans |
f271d7 | d03112 | You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:
0 <= i < j <= n - 1 and
nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
Return the number of pairs that satisfy the conditions.
Example 1:
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.
Example 2:
Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1
Output: 0
Explanation:
Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
n == nums1.length == nums2.length
2 <= n <= 100000
-10000 <= nums1[i], nums2[i] <= 10000
-10000 <= diff <= 10000
| from sortedcontainers import SortedList
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:
l = SortedList()
ans = 0
for i in range(len(nums1)):
cur = nums1[i]-nums2[i]
ans += l.bisect_left(cur+diff+1)
l.add(cur)
return ans |
999f64 | d03112 | You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:
0 <= i < j <= n - 1 and
nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
Return the number of pairs that satisfy the conditions.
Example 1:
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.
Example 2:
Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1
Output: 0
Explanation:
Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
n == nums1.length == nums2.length
2 <= n <= 100000
-10000 <= nums1[i], nums2[i] <= 10000
-10000 <= diff <= 10000
| class Solution(object):
def numberOfPairs(self, nums1, nums2, diff):
"""
:type nums1: List[int]
:type nums2: List[int]
:type diff: int
:rtype: int
"""
n = len(nums1)
nums = [nums1[i]-nums2[i] for i in range(n)]
arr = []
ans = 0
for num in nums:
loc = bisect.bisect(arr,num+diff)
ans += loc
bisect.insort(arr,num)
# print(ans,"*")
return ans
|
9b3237 | fab50b | We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i] and target consist of lowercase English letters.
| import functools
class Solution:
def minStickers(self, stickers, target):
"""
:type stickers: List[str]
:type target: str
:rtype: int
"""
set_stickers = set()
for s in stickers:
set_stickers |= set(s)
set_target = set(target)
if not set_target.issubset(set_stickers):
return -1
tp_stickers = [Solution.letterCount(s) for s in stickers]
tp_target = Solution.letterCount(target)
@functools.lru_cache(maxsize=None)
def recur(tp_tgt, i, cnt):
while i < 26 and tp_tgt[i] == 0:
i += 1
if i == 26:
return 0
return min([recur(Solution.minus(tp_tgt, tp), i, cnt+1)
for tp in tp_stickers if tp[i] > 0]) + 1
return recur(tp_target, 0, 0)
@staticmethod
def letterCount(s):
cnt = [0] * 26
for c in s:
cnt[ord(c) - ord('a')] += 1
return tuple(cnt)
@staticmethod
def minus(tp_a, tp_b):
return tuple([tp_a[i] - tp_b[i] if tp_a[i] - tp_b[i] > 0 else 0
for i in range(26)])
|
a10b23 | fab50b | We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i] and target consist of lowercase English letters.
| class Solution(object):
def minStickers(self, stickers, target):
"""
:type stickers: List[str]
:type target: str
:rtype: int
"""
c2i = dict()
t_tar = list()
for c in target:
if c not in c2i:
c2i[c] = len(t_tar)
t_tar.append(1)
else:
t_tar[c2i[c]] += 1
n = len(t_tar)
l_stickers = list()
n_found = set()
for sticker in stickers:
t = [0] * n
for c in sticker:
if c in c2i:
n_found.add(c)
t[c2i[c]] += 1
l_stickers.append(t)
if len(n_found) < n:
return -1
n_stickers = len(l_stickers)
deleted = [False] * n_stickers
for i in xrange(n_stickers):
if deleted[i]:
continue
for j in xrange(i+1, n_stickers):
if deleted[j]:
continue
if self.le(l_stickers[i], l_stickers[j]):
deleted[i] = True
elif self.le(l_stickers[j], l_stickers[i]):
deleted[j] = True
stickers = list()
for i in xrange(n_stickers):
if not deleted[i]:
stickers.append(l_stickers[i])
#print stickers, t_tar
q = collections.deque()
q.append(t_tar)
level = 0
while q:
n_temp = len(q)
level += 1
for i in xrange(n_temp):
t = q.popleft()
for s in stickers:
if self.le(t, s):
return level
for s in stickers:
new_t = self.sub(t, s)
q.append(new_t)
return -1
def sub(self, t, s):
n = len(t)
ret = [0] * n
for i in xrange(n):
ret[i] = t[i] - s[i]
return ret
def le(self, s1, s2):
n = len(s1)
for i in xrange(n):
if s1[i] > s2[i]:
return False
return True
|
76cd16 | 709350 | You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.
Remove the smallest k elements and the largest k elements from the container.
Calculate the average value for the rest of the elements rounded down to the nearest integer.
Implement the MKAverage class:
MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.
void addElement(int num) Inserts a new element num into the stream.
int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.
Example 1:
Input
["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
Output
[null, null, null, -1, null, 3, null, null, null, 5]
Explanation
MKAverage obj = new MKAverage(3, 1);
obj.addElement(3); // current elements are [3]
obj.addElement(1); // current elements are [3,1]
obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.
obj.addElement(10); // current elements are [3,1,10]
obj.calculateMKAverage(); // The last 3 elements are [3,1,10].
// After removing smallest and largest 1 element the container will be [3].
// The average of [3] equals 3/1 = 3, return 3
obj.addElement(5); // current elements are [3,1,10,5]
obj.addElement(5); // current elements are [3,1,10,5,5]
obj.addElement(5); // current elements are [3,1,10,5,5,5]
obj.calculateMKAverage(); // The last 3 elements are [5,5,5].
// After removing smallest and largest 1 element the container will be [5].
// The average of [5] equals 5/1 = 5, return 5
Constraints:
3 <= m <= 100000
1 <= k*2 < m
1 <= num <= 100000
At most 100000 calls will be made to addElement and calculateMKAverage.
| class MKAverage:
def __init__(self, m: int, k: int):
self.list = []
self.sorted_list = []
self.m = m
self.k = k
self.v = m-2*k
def addElement(self, num: int) -> None:
self.list.append(num)
pt = bisect.bisect(self.sorted_list, num)
self.sorted_list.insert(pt, num)
if len(self.sorted_list) > self.m :
pt = bisect.bisect(self.sorted_list, self.list[-self.m-1]-0.001)
# print(pt, self.list[-self.m-1], self.sorted_list)
self.sorted_list.pop(pt)
def calculateMKAverage(self) -> int:
if len(self.list) < self.m :
return -1
return sum(self.sorted_list[self.k:-self.k]) // self.v |
47f97b | 709350 | You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.
Remove the smallest k elements and the largest k elements from the container.
Calculate the average value for the rest of the elements rounded down to the nearest integer.
Implement the MKAverage class:
MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.
void addElement(int num) Inserts a new element num into the stream.
int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.
Example 1:
Input
["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
Output
[null, null, null, -1, null, 3, null, null, null, 5]
Explanation
MKAverage obj = new MKAverage(3, 1);
obj.addElement(3); // current elements are [3]
obj.addElement(1); // current elements are [3,1]
obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.
obj.addElement(10); // current elements are [3,1,10]
obj.calculateMKAverage(); // The last 3 elements are [3,1,10].
// After removing smallest and largest 1 element the container will be [3].
// The average of [3] equals 3/1 = 3, return 3
obj.addElement(5); // current elements are [3,1,10,5]
obj.addElement(5); // current elements are [3,1,10,5,5]
obj.addElement(5); // current elements are [3,1,10,5,5,5]
obj.calculateMKAverage(); // The last 3 elements are [5,5,5].
// After removing smallest and largest 1 element the container will be [5].
// The average of [5] equals 5/1 = 5, return 5
Constraints:
3 <= m <= 100000
1 <= k*2 < m
1 <= num <= 100000
At most 100000 calls will be made to addElement and calculateMKAverage.
| from collections import deque
from bisect import insort, bisect_left
class MKAverage(object):
def __init__(self, m, k):
"""
:type m: int
:type k: int
"""
self.data = deque()
self.sortedData = []
self.sum = 0
self.m = m
self.k = k
self.validNum = self.m - self.k * 2
def addElement(self, num):
"""
:type num: int
:rtype: None
"""
self.data.append(num)
self.sum += num
if len(self.data) > self.m:
popElement = self.data.popleft()
self.sum -= popElement
self.sortedData.pop(bisect_left(self.sortedData, popElement))
insort(self.sortedData, num)
def calculateMKAverage(self):
"""
:rtype: int
"""
if len(self.data) < self.m:
return -1
lowSum = sum(self.sortedData[:self.k])
highSum = sum(self.sortedData[-self.k:])
return (self.sum - lowSum - highSum) // self.validNum
# Your MKAverage object will be instantiated and called as such:
# obj = MKAverage(m, k)
# obj.addElement(num)
# param_2 = obj.calculateMKAverage() |
e80a43 | 0f7d3c | You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
Return true if it is possible to form a palindrome string, otherwise return false.
Notice that x + y denotes the concatenation of strings x and y.
Example 1:
Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
Example 2:
Input: a = "xbdef", b = "xecab"
Output: false
Example 3:
Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
Constraints:
1 <= a.length, b.length <= 100000
a.length == b.length
a and b consist of lowercase English letters
| class Solution(object):
def checkPalindromeFormation(self, S, T):
# if S[..i] + T[j..] is a palindrome or
def pali(A, i, j):
if i >= j: return True
for k in xrange(j -i+ 1):
if A[i+k] != A[j-k]: return False
return True
N = len(S)
i = 0
j = N - 1
while i < j and S[i] == T[j]:
i += 1
j -= 1
if pali(S, i, j) or pali(T, i, j):
return True
i = 0
j = N - 1
while i < j and T[i] == S[j]:
i += 1
j -= 1
if pali(S, i, j) or pali(T, i, j):
return True
return False |
9abf41 | 0f7d3c | You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
Return true if it is possible to form a palindrome string, otherwise return false.
Notice that x + y denotes the concatenation of strings x and y.
Example 1:
Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
Example 2:
Input: a = "xbdef", b = "xecab"
Output: false
Example 3:
Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
Constraints:
1 <= a.length, b.length <= 100000
a.length == b.length
a and b consist of lowercase English letters
| class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
# print(a)
def check_kernal(strt) :
s = (len(strt)-1)//2
e = len(strt)//2
for i in range(s) :
if not strt[s-i] == strt[e+i] :
return (e+i) - (s-i) - 1
return len(strt)
la, lb = map(check_kernal, [a, b])
if la == len(a) or lb == len(b) :
return True
max_kernal = max(la, lb)
nt = (len(a) - max_kernal) // 2
# print(max_kernal, la, lb, nt)
cka, ckb = True, True
for i in range(nt) :
if not a[i] == b[-i-1] :
cka = False
break
for i in range(nt) :
if not b[i] == a[-i-1] :
ckb = False
break
return cka or ckb |
f3720e | 153434 | Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
Input: nums = [1,2,3,4], k = 3
Output: false
Constraints:
1 <= k <= nums.length <= 16
1 <= nums[i] <= 10000
The frequency of each element is in the range [1, 4].
| class Solution(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
n = len(nums)
sumN = sum(nums)
if sumN%k!=0: return False
avg = sumN / k
nums.sort(reverse = True)
p = [0] * k
self.flag = False
def dfs(i):
if i==n or self.flag:
self.flag = True
return
for j in range(k):
if (j==0 or p[j]!=p[j-1]) and p[j]+nums[i]<=avg:
p[j] += nums[i]
dfs(i+1)
p[j] -= nums[i]
dfs(0)
return self.flag |
caf58d | 153434 | Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
Input: nums = [1,2,3,4], k = 3
Output: false
Constraints:
1 <= k <= nums.length <= 16
1 <= nums[i] <= 10000
The frequency of each element is in the range [1, 4].
| class Solution:
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if k==1:
return True
s = sum(nums)
x = s/k
if x != int(x):
return False
nums.sort(reverse=True)
su = [0]*k
location = [-1]*len(nums)
location[0] = 0
su[0] = nums[0]
if su[0] > x: return False
i = 1
while i != 0 and i<len(nums):
li = location[i]
if li != -1:
su[li] -= nums[i]
if li == k-1:
location[i] = -1
i = i-1
continue
location[i] = li + 1
su[li+1] += nums[i]
if su[li+1]>x:
continue
i = i+1
if i==0:
return False
else:
return True
|
096e3c | 315cc0 | You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.
Example 1:
Input: prob = [0.4], target = 1
Output: 0.40000
Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125
Constraints:
1 <= prob.length <= 1000
0 <= prob[i] <= 1
0 <= target <= prob.length
Answers will be accepted as correct if they are within 10^-5 of the correct answer.
| class Solution(object):
def probabilityOfHeads(self, A, target):
dp = [1.0] #dp[heads] = prob
for p in A:
dp.append(0)
for i in xrange(len(dp) - 1, 0,-1):
dp[i] *= (1 - p)
dp[i] += p * dp[i-1]
dp[0] *= 1-p
#print dp
return dp[target]
|
c74f0e | 315cc0 | You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.
Example 1:
Input: prob = [0.4], target = 1
Output: 0.40000
Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125
Constraints:
1 <= prob.length <= 1000
0 <= prob[i] <= 1
0 <= target <= prob.length
Answers will be accepted as correct if they are within 10^-5 of the correct answer.
| class Solution:
def probabilityOfHeads(self, prob: List[float], target: int) -> float:
dp = [1] + [0] * target
for p in prob:
for i in range(target + 1)[::-1]:
dp[i] = dp[i] * (1 - p)
if i > 0:
dp[i] += dp[i - 1] * p
return dp[-1] |
bb0d8c | c26716 | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 10^9 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 1000
| class Solution(object):
def numTilings(self, N):
"""
:type N: int
:rtype: int
"""
mod=1000000007
x0=1
y0=0
z0=0
x1=1
y1=1
z1=1
while N>1:
nextx=(y0+z0+x1+x0)%mod
nexty=(x1+z1)%mod
nextz=(x1+y1)%mod
x0=x1
y0=y1
z0=z1
x1=nextx
y1=nexty
z1=nextz
# print x1, y1, z1
N-=1
return x1 |
4f999a | c26716 | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 10^9 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 1000
| class Solution:
def numTilings(self, N):
"""
:type N: int
:rtype: int
"""
m = 10**9+7
dp = {}
def num_tile(n, a):
if n < 0:
return 0
if a == 0:
if n == 0:
return 1
if a == 1:
if n == 0:
return 0
if a == 2:
if n == 0:
return 0
return dp[(n, a)]
for n in range(1, N+1):
for a in range(0, 2+1):
if a == 0:
dp[(n, a)] = (num_tile(n-1, 0) + num_tile(n-2, 0) + num_tile(n-1, 1) + num_tile(n-1, 2)) % m
if a == 1:
dp[(n, a)] = (num_tile(n-1, 2) + num_tile(n-2, 0)) % m
if a == 2:
dp[(n, a)] = (num_tile(n-1, 1) + num_tile(n-2, 0)) % m
return num_tile(N, 0)
|
b10789 | 04ca61 | There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given an integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an array coins of size n where coins[i] can be either 0 or 1, where 1 indicates the presence of a coin in the vertex i.
Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times:
Collect all the coins that are at a distance of at most 2 from the current vertex, or
Move to any adjacent vertex in the tree.
Find the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex.
Note that if you pass an edge several times, you need to count it into the answer several times.
Example 1:
Input: coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2.
Example 2:
Input: coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]]
Output: 2
Explanation: Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0.
Constraints:
n == coins.length
1 <= n <= 3 * 10000
0 <= coins[i] <= 1
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
| class Solution:
def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int:
sum_coins = sum(coins)
if sum_coins <= 1 or len(coins) <= 5:
return 0
neighbour = collections.defaultdict(set)
for a, b in edges :
neighbour[a].add(b)
neighbour[b].add(a)
leaf_1 = set()
leaf_0 = []
set_leaf0 = set()
for t in neighbour :
if len(neighbour[t]) == 1 :
if coins[t] == 1 :
leaf_1.add(t)
else :
leaf_0.append(t)
set_leaf0.add(t)
while len(leaf_0) :
tt = leaf_0.pop(0)
for ft in neighbour[tt] :
neighbour[ft].remove(tt)
if len(neighbour[ft]) <= 1 and not ft in set_leaf0:
if coins[ft] == 1 :
leaf_1.add(ft)
else :
set_leaf0.add(ft)
leaf_0.append(ft)
n_leaf2 = set()
for t in neighbour :
if t in leaf_1 or t in set_leaf0 :
continue
t_neighbour = len(neighbour[t])
t_n_leaf1 = len([tt for tt in neighbour[t] if tt in leaf_1])
if t_n_leaf1 >= t_neighbour - 1 :
n_leaf2.add(t)
nodes = len(neighbour) - len(set_leaf0) - len(leaf_1) - len(n_leaf2)
# print(set_leaf0)
# print(leaf_1)
# print(n_leaf2)
return max(2 * (nodes - 1), 0)
|
2f86ae | 04ca61 | There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given an integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an array coins of size n where coins[i] can be either 0 or 1, where 1 indicates the presence of a coin in the vertex i.
Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times:
Collect all the coins that are at a distance of at most 2 from the current vertex, or
Move to any adjacent vertex in the tree.
Find the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex.
Note that if you pass an edge several times, you need to count it into the answer several times.
Example 1:
Input: coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2.
Example 2:
Input: coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]]
Output: 2
Explanation: Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0.
Constraints:
n == coins.length
1 <= n <= 3 * 10000
0 <= coins[i] <= 1
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
| class Solution(object):
def collectTheCoins(self, coins, edges):
"""
:type coins: List[int]
:type edges: List[List[int]]
:rtype: int
"""
t, l, a = [set() for _ in range(len(coins))], [], 0
for e, f in edges:
t[e].add(f)
t[f].add(e)
for i in range(len(coins)):
u = i
while len(t[u]) == 1 and not coins[u]:
v = next(iter(t[u]))
t[u].remove(v)
t[v].remove(u)
u = v
if len(t[u]) == 1:
l.append(u)
for i in range(2):
w = []
for u in l:
if len(t[u]) == 1:
v = next(iter(t[u]))
t[u].remove(v)
t[v].remove(u)
if len(t[v]) == 1:
w.append(v)
l = w
for i in range(len(coins)):
a += len(t[i])
return a |
6ea596 | 00cd4f | You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.
You want to share the chocolate with your k friends so you start cutting the chocolate bar into k + 1 pieces using k cuts, each piece consists of some consecutive chunks.
Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.
Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
Example 1:
Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
Example 2:
Input: sweetness = [5,6,7,8,9,1,2,3,4], k = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.
Example 3:
Input: sweetness = [1,2,2,1,2,2,1,2,2], k = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
Constraints:
0 <= k < sweetness.length <= 10000
1 <= sweetness[i] <= 100000
| class Solution(object):
def maximizeSweetness(self, A, K):
if K == 0:
return sum(A)
def cuttable(size):
pieces = 0
piece = 0
for x in A:
if x + piece < size:
piece += x
else:
pieces += 1
piece = 0
return pieces >= K+1
lo = 0
hi = sum(A)
while lo < hi:
mi = (lo + hi + 1)/ 2
if cuttable(mi):
lo = mi
else:
hi = mi - 1
return lo |
6e2084 | 00cd4f | You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.
You want to share the chocolate with your k friends so you start cutting the chocolate bar into k + 1 pieces using k cuts, each piece consists of some consecutive chunks.
Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.
Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
Example 1:
Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
Example 2:
Input: sweetness = [5,6,7,8,9,1,2,3,4], k = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.
Example 3:
Input: sweetness = [1,2,2,1,2,2,1,2,2], k = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
Constraints:
0 <= k < sweetness.length <= 10000
1 <= sweetness[i] <= 100000
| class Solution:
def maximizeSweetness(self, A: List[int], K: int) -> int:
def possible(x):
k, temp = 0, 0
for a in A:
temp += a
if temp >= x:
k, temp = k + 1, 0
return k >= K + 1
l, h = min(A), sum(A)
while l < h:
m = (l + h + 1) // 2
print(l, h)
if possible(m):
l = m
else:
h = m - 1
return l |
7db845 | 7be8d9 | Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters.
Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/ | class Solution:
def smallestSubsequence(self, text: str) -> str:
text = tuple(map(ord, text))
right = {num : i for i, num in enumerate(text)}
seen = set()
stack = []
for i, num in enumerate(text):
if num not in seen:
while stack and num < stack[-1] and right[stack[-1]] > i:
seen.remove(stack.pop())
stack.append(num)
seen.add(num)
return ''.join(map(chr, stack))
|
26edd4 | 7be8d9 | Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters.
Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/ | class Solution(object):
def smallestSubsequence(self, text):
"""
:type text: str
:rtype: str
"""
chars = set()
for c in text: chars.add(c)
w = len(chars)
rtn = ''
min_index = 0
n = len(text)
for i in range(w):
# dp[j] stores number of elements in chars.
dp = [0] * n
running_set = set()
for j in range(n - 1, -1, -1):
if text[j] in chars:
running_set.add(text[j])
dp[j] = len(running_set)
# Choose one index each time.
to_choose = -1
for j in range(min_index, n):
if text[j] in chars and (to_choose == -1 or text[j] < text[to_choose]) and dp[j] >= len(chars):
to_choose = j
rtn += text[to_choose]
chars.remove(text[to_choose])
min_index = to_choose + 1
return rtn |
5d9c93 | e0e822 | Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.
You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.
Return the total number of seconds that Ashe is poisoned.
Example 1:
Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Example 2:
Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
Constraints:
1 <= timeSeries.length <= 10000
0 <= timeSeries[i], duration <= 10^7
timeSeries is sorted in non-decreasing order.
| class Solution(object):
def findPosisonedDuration(self, A, duration):
events = []
OPEN, CLOSE = range(2)
for x in A:
events.append((x, OPEN))
events.append((x+duration, CLOSE))
events.sort()
ans = bal = 0
prev = float('-inf')
for x, typ in events:
if bal > 0:
ans += x - prev
prev = x
if typ == OPEN:
bal += 1
else:
bal -= 1
return ans |
062554 | 45a9e1 | A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Example 1:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
Example 2:
Input: words = ["t"]
Output: 2
Explanation: A valid encoding would be s = "t#" and indices = [0].
Constraints:
1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] consists of only lowercase letters.
| class node:
def __init__(self,c):
self.val=c
self.next=[None]*26
class Solution(object):
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
od=lambda x:ord(x)-ord('a')
root=node('#')
for w in words:
p = root
for c in w[::-1]:
if p.next[od(c)] is None:
p.next[od(c)]=node(c)
p=p.next[od(c)]
def search(r):
if not r:
return [0,1]
ans,cnt=[0,0]
for i in range(26):
if r.next[i]:
temp=search(r.next[i])
ans+=temp[0]+temp[1]
cnt+=temp[1]
if not cnt:
return [1,1]
return [ans,cnt]
return search(root)[0] |
42f724 | 45a9e1 | A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Example 1:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
Example 2:
Input: words = ["t"]
Output: 2
Explanation: A valid encoding would be s = "t#" and indices = [0].
Constraints:
1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] consists of only lowercase letters.
| class Solution:
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
# sort by longest, then check if in string
avail = set()
total_len = 0
words.sort(key=lambda w: -len(w))
for w in words:
if w not in avail:
total_len += len(w) + 1
for i in range(len(w) - 1):
avail.add(w[i:])
return total_len |
378cbd | e97738 | You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
It does not occupy a cell containing the character '#'.
The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word, return true if word can be placed in board, or false otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
Output: true
Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
Output: false
Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
Output: true
Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 100000
board[i][j] will be ' ', '#', or a lowercase English letter.
1 <= word.length <= max(m, n)
word will contain only lowercase English letters.
| class Solution(object):
def placeWordInCrossword(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def is_match(s):
if len(s) != len(word):
return False
if all(s[i]==' ' or s[i]==v for i, v in enumerate(word)):
return True
s = s[::-1]
return all(s[i]==' ' or s[i]==v for i, v in enumerate(word))
def check(a):
n = len(a[0])
for row in a:
if any(is_match(part) for part in ''.join(row).split('#')):
return True
return False
return check(board) or check(zip(*board)) |
188cf6 | e97738 | You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
It does not occupy a cell containing the character '#'.
The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word, return true if word can be placed in board, or false otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
Output: true
Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
Output: false
Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
Output: true
Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 100000
board[i][j] will be ' ', '#', or a lowercase English letter.
1 <= word.length <= max(m, n)
word will contain only lowercase English letters.
| class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
for i in range(m) :
temp = []
for j in range(-1, n) :
if j == n-1 or board[i][j+1] == '#' :
if len(temp) == len(word) :
mark = True
for k in range(len(word)) :
if not temp[k] == word[k] and not temp[k] == ' ' :
mark = False
break
if mark :
return True
mark = True
for k in range(len(word)) :
if not temp[k] == word[-k-1] and not temp[k] == ' ' :
mark = False
break
if mark :
return True
temp = []
continue
if not j == n-1 :
temp.append(board[i][j+1])
for i in range(n) :
temp = []
for j in range(-1, m) :
if j == m-1 or board[j+1][i] == '#' :
if len(temp) == len(word) :
mark = True
for k in range(len(word)) :
if not temp[k] == word[k] and not temp[k] == ' ' :
mark = False
break
if mark :
return True
mark = True
for k in range(len(word)) :
if not temp[k] == word[-k-1] and not temp[k] == ' ' :
mark = False
break
if mark :
return True
temp = []
continue
if not j == m-1 :
temp.append(board[j+1][i])
return False |
607df0 | 1508e4 | You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
| class Solution(object):
def totalSteps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s, a, r = [], [0] * len(nums), 0
for i in range(len(nums) - 1, -1, -1):
while s and nums[i] > nums[s[-1]]:
a[i] = max(a[i] + 1, a[s.pop()])
s.append(i)
r = max(r, a[i])
return r |
0293db | 1508e4 | You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
| class Solution:
def totalSteps(self, a: List[int]) -> int:
z = 0
b = []
n = len(a)
l = 0
for i in a[::-1]:
c = 0
while len(b) and i > b[-1][0]:
x, y = b.pop()
c += 1 + max(y - c - 1, 0)
z = max(z, c)
b.append((i, c))
return z |
93dfa5 | 1835fa | A concert hall has n rows numbered from 0 to n - 1, each with m seats, numbered from 0 to m - 1. You need to design a ticketing system that can allocate seats in the following cases:
If a group of k spectators can sit together in a row.
If every member of a group of k spectators can get a seat. They may or may not sit together.
Note that the spectators are very picky. Hence:
They will book seats only if each member of their group can get a seat with row number less than or equal to maxRow. maxRow can vary from group to group.
In case there are multiple rows to choose from, the row with the smallest number is chosen. If there are multiple seats to choose in the same row, the seat with the smallest number is chosen.
Implement the BookMyShow class:
BookMyShow(int n, int m) Initializes the object with n as number of rows and m as number of seats per row.
int[] gather(int k, int maxRow) Returns an array of length 2 denoting the row and seat number (respectively) of the first seat being allocated to the k members of the group, who must sit together. In other words, it returns the smallest possible r and c such that all [c, c + k - 1] seats are valid and empty in row r, and r <= maxRow. Returns [] in case it is not possible to allocate seats to the group.
boolean scatter(int k, int maxRow) Returns true if all k members of the group can be allocated seats in rows 0 to maxRow, who may or may not sit together. If the seats can be allocated, it allocates k seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returns false.
Example 1:
Input
["BookMyShow", "gather", "gather", "scatter", "scatter"]
[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]
Output
[null, [0, 0], [], true, false]
Explanation
BookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each
bms.gather(4, 0); // return [0, 0]
// The group books seats [0, 3] of row 0.
bms.gather(2, 0); // return []
// There is only 1 seat left in row 0,
// so it is not possible to book 2 consecutive seats.
bms.scatter(5, 1); // return True
// The group books seat 4 of row 0 and seats [0, 3] of row 1.
bms.scatter(5, 1); // return False
// There is only one seat left in the hall.
Constraints:
1 <= n <= 5 * 10000
1 <= m, k <= 10^9
0 <= maxRow <= n - 1
At most 5 * 10000 calls in total will be made to gather and scatter.
| class Fenwick:
def __init__(self, n):
self.A = [0] * (n + 2)
self.n = n
def query(self, k):
n = self.n
if k < 0: return 0
# assert 0 <= k
if k >= n: k = n - 1
r = 0
k += 1
while k > 0:
r += self.A[k]
k -= k & -k
return r
def update(self, k, v):
assert 0 <= k < self.n
k += 1
while k < len(self.A):
self.A[k] += v
k += k & -k
class Segment:
def __init__(self, l, r, A):
self.l, self.r = l, r
if l == r:
self.left, self.right = None, None
self.val = A[l]
else:
mid = (self.l + self.r) // 2
self.left, self.right = Segment(l, mid, A), Segment(mid + 1, r, A)
self.val = max(self.left.val, self.right.val)
def query(self, l, r):
if l < self.l: l = self.l
if r > self.r: r = self.r
if l > r: return 0
if l == self.l and r == self.r: return self.val
# mid = (self.l + self.r) // 2
return max(self.left.query(l, r), self.right.query(l, r))
def update(self, k, v):
if k < self.l or k > self.r: return
if k == self.l == self.r:
self.val += v
# print("update",k,v,self.val)
else:
self.left.update(k, v)
self.right.update(k, v)
self.val = max(self.left.val, self.right.val)
class Link:
def __init__(self, n):
self.n = n
self.L, self.R = [i-1 for i in range(n+2)], [i+1 for i in range(n+2)]
self.L[0] = 0
self.R[n+1] = n+1
def remove(self, k):
l, r = self.L[k+1], self.R[k+1]
self.L[r] = l
self.R[l] = r
# print("update", k, l, r)
self.L[k+1] = self.R[k+1] = -1
def forward(self, k):
index = self.R[k + 1]
if index-1 < self.n:
return index - 1
else:
return None
class BookMyShow:
def __init__(self, n: int, m: int):
self.n, self.m = n, m
self.A = [m] * n
self.F = Fenwick(n)
self.S = Segment(0, n - 1, self.A)
self.L = Link(n)
for i in range(n):
self.F.update(i, m)
def find(self, k, maxRow):
lo, hi = 0, maxRow
while lo < hi:
mid = (lo + hi) // 2
if self.S.query(0, mid) >= k:
hi = mid
else:
lo = mid + 1
if self.S.query(0, lo) < k:
index = None
else:
index = lo
return index
def gather(self, k: int, maxRow: int) -> List[int]:
index = self.find(k, maxRow)
# print(">",[self.S.query(0, i) for i in range(self.n)])
# index_brute = min((i for i in range(maxRow + 1) if self.A[i] >= k), default=None)
# assert index == index_brute, (index, index_brute, lo ,hi)
if index is None: return []
p = self.m - self.A[index]
self.A[index] -= k
if self.A[index] == 0:
self.L.remove(index)
self.S.update(index, -k)
self.F.update(index, -k)
return [index, p]
def scatter(self, k: int, maxRow: int) -> bool:
s = self.F.query(maxRow)
# s_brute = sum(self.A[:maxRow + 1])
# assert s == s_brute
if s < k: return False
# index = self.find(1, maxRow)
index = self.L.forward(-1)
# print(index, self.L.L, self.L.R)
# for i in range(index, maxRow + 1):
i = index
while i <= maxRow:
if k == 0: break
u = min(self.A[i], k)
self.A[i] -= u
ni = self.L.forward(i)
if self.A[i] == 0:
self.L.remove(i)
self.S.update(i, -u)
self.F.update(i, -u)
k -= u
if k == 0: break
i = ni
# print('now', i)
return True
|
9de72f | 1835fa | A concert hall has n rows numbered from 0 to n - 1, each with m seats, numbered from 0 to m - 1. You need to design a ticketing system that can allocate seats in the following cases:
If a group of k spectators can sit together in a row.
If every member of a group of k spectators can get a seat. They may or may not sit together.
Note that the spectators are very picky. Hence:
They will book seats only if each member of their group can get a seat with row number less than or equal to maxRow. maxRow can vary from group to group.
In case there are multiple rows to choose from, the row with the smallest number is chosen. If there are multiple seats to choose in the same row, the seat with the smallest number is chosen.
Implement the BookMyShow class:
BookMyShow(int n, int m) Initializes the object with n as number of rows and m as number of seats per row.
int[] gather(int k, int maxRow) Returns an array of length 2 denoting the row and seat number (respectively) of the first seat being allocated to the k members of the group, who must sit together. In other words, it returns the smallest possible r and c such that all [c, c + k - 1] seats are valid and empty in row r, and r <= maxRow. Returns [] in case it is not possible to allocate seats to the group.
boolean scatter(int k, int maxRow) Returns true if all k members of the group can be allocated seats in rows 0 to maxRow, who may or may not sit together. If the seats can be allocated, it allocates k seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returns false.
Example 1:
Input
["BookMyShow", "gather", "gather", "scatter", "scatter"]
[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]
Output
[null, [0, 0], [], true, false]
Explanation
BookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each
bms.gather(4, 0); // return [0, 0]
// The group books seats [0, 3] of row 0.
bms.gather(2, 0); // return []
// There is only 1 seat left in row 0,
// so it is not possible to book 2 consecutive seats.
bms.scatter(5, 1); // return True
// The group books seat 4 of row 0 and seats [0, 3] of row 1.
bms.scatter(5, 1); // return False
// There is only one seat left in the hall.
Constraints:
1 <= n <= 5 * 10000
1 <= m, k <= 10^9
0 <= maxRow <= n - 1
At most 5 * 10000 calls in total will be made to gather and scatter.
| class segment_tree(object):
# minimum value
def merge(self,num,minimum):
return max(minimum,num)
def __init__(self,n,initial):
self.n = n
self.arr = [0]*(2*n)
for i in range(2*n-1,0,-1):
if i>=n: self.arr[i] = initial[i-n]
else: self.arr[i] = self.merge(self.arr[2*i],self.arr[2*i+1])
def update(self,index,target):
self.arr[index] = target
if index & 1:
nexttarget = self.merge( self.arr[index], self.arr[index-1])
else:
nexttarget = self.merge( self.arr[index], self.arr[index+1])
if index>0: self.update(index>>1,nexttarget )
def addnum(self,index,diff):
self.update(index+self.n, self.arr[index+self.n] + diff)
def query(self,left,right):
i,j = self.n+left, self.n+right+1
output = 0 # initial output should be changed if you want to change the merge function
while i<j:
if i&1:
output = self.merge(self.arr[i],output)
i += 1
if j&1:
j -= 1
output = self.merge(self.arr[j],output)
i = i >> 1
j = j >> 1
return output
class fenwick(object):
def __init__(self, n):
self.n = n
self.cul = [0]*n
def update(self,index,diff):
i = index
while i<self.n:
self.cul[i] += diff
i += (i+1)&(-i-1)
def getaccu(self,index):
output = 0
i = index
while i>=0:
output += self.cul[i]
i -= (i+1)&(-i-1)
return output
class BookMyShow(object):
def __init__(self, n, m):
"""
:type n: int
:type m: int
"""
self.avail = segment_tree(n,[m]*n)
self.accu = fenwick(n)
self.m = m
for i in range(n):
self.accu.update(i,m)
self.nonzero_index = 0
def gather(self, k, maxRow):
"""
:type k: int
:type maxRow: int
:rtype: List[int]
"""
front = 0
rear = maxRow
# print self.avail.query(0,maxRow)
if self.avail.query(0,maxRow) < k:
return []
while front<rear:
mid = (front+rear)//2
if self.avail.query(0,mid) < k:
front = mid + 1
else:
rear = mid
output = [front,self.m - self.avail.query(front,front)]
self.avail.addnum(front,-k)
self.accu.update(front,-k)
return output
def scatter(self, k, maxRow):
"""
:type k: int
:type maxRow: int
:rtype: bool
"""
totrest = self.accu.getaccu(maxRow)
# print totrest,k,"--"
if totrest < k:
return False
# print "ha"
rest = k
while self.nonzero_index <= maxRow:
num = self.avail.query(self.nonzero_index,self.nonzero_index)
# print self.nonzero_index,num
if num >= rest:
self.avail.addnum(self.nonzero_index,-rest)
self.accu.update(self.nonzero_index,-rest)
return True
else:
rest -= num
self.avail.addnum(self.nonzero_index,-num)
self.accu.update(self.nonzero_index,-num)
self.nonzero_index += 1
return True
# Your BookMyShow object will be instantiated and called as such:
# obj = BookMyShow(n, m)
# param_1 = obj.gather(k,maxRow)
# param_2 = obj.scatter(k,maxRow) |
612494 | 64b698 | You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.
Return an array answer of the same length as queries where answer[j] is the answer to the jth query.
Example 1:
Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
- For queries[1]=2, the items which can be considered are [1,2] and [2,4].
The maximum beauty among them is 4.
- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
The maximum beauty among them is 5.
- For queries[4]=5 and queries[5]=6, all items can be considered.
Hence, the answer for them is the maximum beauty of all items, i.e., 6.
Example 2:
Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4.
Note that multiple items can have the same price and/or beauty.
Example 3:
Input: items = [[10,1000]], queries = [5]
Output: [0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen.
Hence, the answer to the query is 0.
Constraints:
1 <= items.length, queries.length <= 100000
items[i].length == 2
1 <= pricei, beautyi, queries[j] <= 10^9
| """
输入:items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
输出:[2,4,5,5,6,6]
"""
class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
qs = [[q, i] for i, q in enumerate(queries)]
qs.sort()
items.sort()
idx = 0
tn = len(items)
ma = 0
qn = len(qs)
res = [0] * qn
for q, i in qs:
while idx < tn and items[idx][0] <= q:
ma = max(ma, items[idx][1])
idx += 1
res[i] = ma
return res
|
5514cd | 64b698 | You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.
Return an array answer of the same length as queries where answer[j] is the answer to the jth query.
Example 1:
Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
- For queries[1]=2, the items which can be considered are [1,2] and [2,4].
The maximum beauty among them is 4.
- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
The maximum beauty among them is 5.
- For queries[4]=5 and queries[5]=6, all items can be considered.
Hence, the answer for them is the maximum beauty of all items, i.e., 6.
Example 2:
Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4.
Note that multiple items can have the same price and/or beauty.
Example 3:
Input: items = [[10,1000]], queries = [5]
Output: [0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen.
Hence, the answer to the query is 0.
Constraints:
1 <= items.length, queries.length <= 100000
items[i].length == 2
1 <= pricei, beautyi, queries[j] <= 10^9
| class Solution(object):
def maximumBeauty(self, A, queries):
res = {}
A.sort()
A = [[-b, p] for p, b in A]
heapq.heapify(A)
Q = sorted(queries)[::-1]
for q in Q:
while A and A[0][1] > q:
b, p = heapq.heappop(A)
res[q] = -A[0][0] if A else 0
return [res[q] for q in queries] |
6061c1 | a9fde2 | We define str = [s, n] as the string str which consists of the string s concatenated n times.
For example, str == ["abc", 3] =="abcabcabc".
We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.
For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by removing the bolded underlined characters.
You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2].
Return the maximum integer m such that str = [str2, m] can be obtained from str1.
Example 1:
Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
Output: 2
Example 2:
Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
Output: 1
Constraints:
1 <= s1.length, s2.length <= 100
s1 and s2 consist of lowercase English letters.
1 <= n1, n2 <= 1000000
| class Solution(object):
def getMaxRepetitions(self, s1, n1, s2, n2):
D1 = {}
D2 = {}
for i,x in enumerate(s1):
if x not in D1:
D1[x] = [i]
else:
D1[x].append(i)
for i,x in enumerate(s2):
if x not in D2:
D2[x] = [i]
else:
D2[x].append(i)
for x in D2:
if x not in D1:
return 0
L = [{} for i in range(len(s1))]
for i,x in enumerate(s1):
if x not in D2:
continue
for j in D2[x]:
poss = D1[s2[j+1]] if j+1 <len(s2) else D1[s2[0]]
if i >= poss[-1]:
L[i][j] = [poss[0], 1]
else:
for k in poss:
if k > i:
break
L[i][j] = [k, 0]
p2 = 0
p1 = D1[s2[0]][0]
useds1 = 0
useds2 = 0
roundandpos = {p1:[0,0]}
sign = 0
while useds1 < n1:
v = L[p1][p2]
p1 = v[0]
useds1 += v[1]
p2 += 1
if p2 == len(s2):
useds2 +=1
p2 = 0
if sign == 0:
if p1 in roundandpos:
sign = 1
[l1, k1] = roundandpos[p1]
l2, k2 = useds1, useds2
s1left = n1 - l2
roundsleft = s1left/(l2-l1) - 1
useds1 += roundsleft * (l2-l1)
useds2 += roundsleft * (k2-k1)
else:
roundandpos[p1] = [useds1, useds2]
return useds2/n2
"""
:type s1: str
:type n1: int
:type s2: str
:type n2: int
:rtype: int
"""
|
d1ea6d | 51b981 | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
Example 3:
Input: steps = 4, arrLen = 2
Output: 8
Constraints:
1 <= steps <= 500
1 <= arrLen <= 1000000
| class Solution:
def numWays(self, n: int, t: int) -> int:
l=min(t,n+1)
cur=[0]*(l)
cur[0]=1
mod=10**9+7
for _ in range(n):
nxt=[0]*(l)
for i in range(l):
for j in [-1,0,1]:
if 0<=i+j<l:
nxt[i]+=cur[i+j]
nxt[i]%=mod
cur=nxt
return cur[0]
|
ac730a | 51b981 | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
Example 3:
Input: steps = 4, arrLen = 2
Output: 8
Constraints:
1 <= steps <= 500
1 <= arrLen <= 1000000
| class Solution(object):
def numWays(self, steps, arrLen):
"""
:type steps: int
:type arrLen: int
:rtype: int
"""
N = min(steps, arrLen)
f = [0] * N
f[0] = 1
for i in range(steps):
g = [0] * N
for j in range(N):
s = f[j]
if j > 0:
s += f[j-1]
if j < N-1:
s += f[j+1]
g[j] = s % 1000000007
f = list(g)
return f[0] |
f1063c | f04eec | There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.
Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, k = 2
Output: 3
Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
Example 2:
Input: n = 5, k = 5
Output: 1
Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
Example 3:
Input: n = 20, k = 11
Output: 647427950
Explanation: There are 647427950 (mod 10^9 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
Constraints:
1 <= n <= 1000
1 <= k <= n
| class Solution:
def rearrangeSticks(self, n: int, k: int) -> int:
dts = [1]
for i in range(1, 1001) :
dts.append(dts[-1]*i%(10**9+7))
@functools.lru_cache(None)
def solve(n, k) :
if n == k :
return 1
if k == 1 :
return dts[n-1]
return (solve(n-1, k-1) + solve(n-1, k) * (n-1)) % (10**9+7)
return solve(n, k) |
31977c | f04eec | There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.
Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, k = 2
Output: 3
Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
Example 2:
Input: n = 5, k = 5
Output: 1
Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
Example 3:
Input: n = 20, k = 11
Output: 647427950
Explanation: There are 647427950 (mod 10^9 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
Constraints:
1 <= n <= 1000
1 <= k <= n
| class Solution(object):
def rearrangeSticks(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
mod = 10**9 + 7
f = [[0]*(k+1) for _ in xrange(n+1)]
f[0][0] = 1
for i in xrange(1,1+n):
for j in xrange(1,1+k):
f[i][j] = (f[i-1][j-1]+(i-1)*f[i-1][j]) % mod
return f[n][k] |
338e03 | c8fff4 | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
If the CPU is idle and there are no available tasks to process, the CPU remains idle.
If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
Once a task is started, the CPU will process the entire task without stopping.
The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
Example 2:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
Constraints:
tasks.length == n
1 <= n <= 100000
1 <= enqueueTimei, processingTimei <= 10^9
| import heapq
class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
arr = []
d = {}
for i in range(len(tasks)):
eq, pr = tasks[i]
if eq not in d:
d[eq] = []
d[eq].append((pr, i))
keys = sorted(d.keys())
ans = []
t = 0
pq = []
for key in keys:
while len(pq) != 0 and t < key:
pr, i, eq = heapq.heappop(pq)
if eq >= key:
heapq.heappush(pq, (pr, i, eq))
break
t = max(eq, t) + pr
ans.append(i)
for pr, i in d[key]:
heapq.heappush(pq, (pr, i, key))
while len(pq) != 0:
pr, i, eq = heapq.heappop(pq)
t = max(eq, t) + pr
ans.append(i)
return ans
|
654dbc | c8fff4 | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
If the CPU is idle and there are no available tasks to process, the CPU remains idle.
If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
Once a task is started, the CPU will process the entire task without stopping.
The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
Example 2:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
Constraints:
tasks.length == n
1 <= n <= 100000
1 <= enqueueTimei, processingTimei <= 10^9
| from heapq import heappush, heappop
class Solution(object):
def getOrder(self, tasks):
"""
:type tasks: List[List[int]]
:rtype: List[int]
"""
a = sorted((avail, dur, idx) for idx, (avail, dur) in enumerate(tasks))
r = []
i = t = 0
q = []
while i < len(a) or q:
if not q:
t = max(t, a[i][0])
while i < len(a) and a[i][0] <= t:
avil, dur, idx = a[i]
heappush(q, (dur, idx))
i += 1
dur, idx = heappop(q)
r.append(idx)
t += dur
return r |
c5b45c | e9b5a1 | Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.
Example 1:
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Example 2:
Input: n = 1
Output: 2
Example 3:
Input: n = 2
Output: 3
Constraints:
1 <= n <= 10^9
| class Solution(object):
def findIntegers(self, num):
"""
:type num: int
:rtype: int
"""
n = 32
arr = []
for i in range(n):
arr.append(num % 2)
num /= 2
arr.reverse()
# print arr
dp1 = [1] + [None] * (n - 1)
for i in range(1, n):
if arr[i] != 1 or arr[i - 1] != 1:
dp1[i] = dp1[i - 1]
else:
dp1[i] = 0
# print dp1
dp2 = [[0, 0]] + [[None, None] for i in range(n - 1)]
for i in range(1, n):
if arr[i] == 0:
dp2[i][0] = dp2[i - 1][0] + dp2[i - 1][1]
dp2[i][1] = dp2[i - 1][0]
else:
dp2[i][0] = dp2[i - 1][0] + dp2[i - 1][1] + dp1[i - 1]
dp2[i][1] = dp2[i - 1][0]
# print dp2
return dp1[n - 1] + dp2[n - 1][0] + dp2[n - 1][1]
|
1c05ad | e9b5a1 | Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.
Example 1:
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Example 2:
Input: n = 1
Output: 2
Example 3:
Input: n = 2
Output: 3
Constraints:
1 <= n <= 10^9
| class Solution:
def nearest(self, num):
prev = False
exact = True
for i in map(lambda x: x == '1', bin(num)[2:]):
if prev and i:
exact = False
yield False
prev = False
elif exact:
yield i
prev = i
else:
yield not prev
prev = not prev
def findIntegers(self, num):
"""
:type num: int
:rtype: int
"""
lookup = []
x_0 = 1
x_1 = 1
for i in range(31):
lookup.append((x_0, x_1))
x_0, x_1 = x_0 + x_1, x_0
print(lookup)
ans = 0
num = list(self.nearest(num))
for _, n in enumerate(num):
i = len(num) - _ - 1
if n:
ans += lookup[i][0]
if i == 0:
ans += lookup[i][1]
print(i, n, ans)
prev = n
return ans
|
ad6a4b | c9c60f | You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > i
nums[j] > nums[i]
There exists exactly one index k such that nums[k] > nums[i] and i < k < j.
If there is no such nums[j], the second greater integer is considered to be -1.
For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i] <= 10^9
| class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
from sortedcontainers import SortedList
tmp = defaultdict(list)
for idx,i in enumerate(nums):
tmp[i].append(idx)
q = SortedList()
res = [-1]*len(nums)
for k in sorted(tmp.keys(),reverse=True):
for i in tmp[k]:
idx = q.bisect_left(i)
if idx+1<len(q):
res[i]=nums[q[idx+1]]
for i in tmp[k]:
q.add(i)
return res
|
7d1c17 | c9c60f | You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > i
nums[j] > nums[i]
There exists exactly one index k such that nums[k] > nums[i] and i < k < j.
If there is no such nums[j], the second greater integer is considered to be -1.
For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i] <= 10^9
| class Solution(object):
def secondGreaterElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
mx=1
while mx<=n: mx<<=1
ix = [0]*(mx+mx)
r =[-1]*n
i = n-1
def addv(i, v):
i+=mx
ix[i]=v
i>>=1
while i:
ix[i]=max(ix[i*2], ix[i*2+1])
i>>=1
def findx(i, v):
s=i+mx
e=mx+mx-1
while s<=e:
if ix[s]>=v: break
if s&1: s+=1
if (e&1)==0: e-=1
s>>=1
e>>=1
if s>e: return n+1
while s<mx:
if ix[s*2]>=v: s=s*2
else: s=s*2+1
return s-mx
while i>=0:
j = findx(i+1, nums[i]+1)
if j<n:
j=findx(j+1, nums[i]+1)
if j<n: r[i]=nums[j]
addv(i, nums[i])
i-=1
return r |
8e1399 | dc7940 | You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:
The number of prime factors of n (not necessarily distinct) is at most primeFactors.
The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.
Return the number of nice divisors of n. Since that number can be too large, return it modulo 10^9 + 7.
Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.
Example 1:
Input: primeFactors = 5
Output: 6
Explanation: 200 is a valid value of n.
It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
There is not other value of n that has at most 5 prime factors and more nice divisors.
Example 2:
Input: primeFactors = 8
Output: 18
Constraints:
1 <= primeFactors <= 10^9
| class Solution(object):
def maxNiceDivisors(self, n):
MOD = 10 ** 9 + 7
if n <=4: return n
if n==5: return 6
if n==6: return 9
if n==7: return 12
q,r = divmod(n-4, 3)
return pow(3, q, MOD) * self.maxNiceDivisors(r+4) % MOD |
3e65f5 | dc7940 | You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:
The number of prime factors of n (not necessarily distinct) is at most primeFactors.
The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.
Return the number of nice divisors of n. Since that number can be too large, return it modulo 10^9 + 7.
Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.
Example 1:
Input: primeFactors = 5
Output: 6
Explanation: 200 is a valid value of n.
It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
There is not other value of n that has at most 5 prime factors and more nice divisors.
Example 2:
Input: primeFactors = 8
Output: 18
Constraints:
1 <= primeFactors <= 10^9
| MOD = 1000000007
class Solution:
def maxNiceDivisors(self, n: int) -> int:
if n <= 3:
return n
if n % 3 == 1:
return 4 * pow(3, (n - 4) // 3, MOD) % MOD
elif n % 3 == 2:
return 2 * pow(3, n // 3, MOD) % MOD
else:
return pow(3, n // 3, MOD) |
bf4ad6 | 1532ba | You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
if the ith character is 'Y', it means that customers come at the ith hour
whereas 'N' indicates that no customers come at the ith hour.
If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
For every hour when the shop is open and no customers come, the penalty increases by 1.
For every hour when the shop is closed and customers come, the penalty increases by 1.
Return the earliest hour at which the shop must be closed to incur a minimum penalty.
Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
Example 1:
Input: customers = "YYNY"
Output: 2
Explanation:
- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
Example 2:
Input: customers = "NNNNN"
Output: 0
Explanation: It is best to close the shop at the 0th hour as no customers arrive.
Example 3:
Input: customers = "YYYY"
Output: 4
Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 100000
customers consists only of characters 'Y' and 'N'.
| class Solution:
def bestClosingTime(self, customers: str) -> int:
tmp = [0]
for x in customers:
if x == 'Y':
tmp.append(tmp[-1] + 1)
else:
tmp.append(tmp[-1] - 1)
return tmp.index(max(tmp)) |
af2c68 | 1532ba | You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
if the ith character is 'Y', it means that customers come at the ith hour
whereas 'N' indicates that no customers come at the ith hour.
If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
For every hour when the shop is open and no customers come, the penalty increases by 1.
For every hour when the shop is closed and customers come, the penalty increases by 1.
Return the earliest hour at which the shop must be closed to incur a minimum penalty.
Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
Example 1:
Input: customers = "YYNY"
Output: 2
Explanation:
- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
Example 2:
Input: customers = "NNNNN"
Output: 0
Explanation: It is best to close the shop at the 0th hour as no customers arrive.
Example 3:
Input: customers = "YYYY"
Output: 4
Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 100000
customers consists only of characters 'Y' and 'N'.
| class Solution(object):
def bestClosingTime(self, customers):
"""
:type customers: str
:rtype: int
"""
n = len(customers)
c1=0
lx = [0]*(n+1)
rx = [0]*(n+1)
for i in range(n):
lx[i]=c1
if customers[i]=='N': c1+=1
i=n-1
lx[n] = c1
c1=0
while i>=0:
if customers[i]=='Y': c1+=1
rx[i]=c1
i-=1
r=0
for i in range(n+1):
if lx[i]+rx[i]<lx[r]+rx[r]: r=i
return r
|
43d1bc | 9e3abf | Let's define a function countUniqueChars(s) that returns the number of unique characters on s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Example 1:
Input: s = "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.
Example 3:
Input: s = "LEETCODE"
Output: 92
Constraints:
1 <= s.length <= 100000
s consists of uppercase English letters only.
| class Solution(object):
def uniqueLetterString(self, S):
"""
:type S: str
:rtype: int
"""
mydic={}
for i in xrange(len(S)):
c=S[i]
if c in mydic: mydic[c].append(i)
else: mydic[c]=[i]
res=0
for k in mydic:
res+=self.cal(mydic[k], len(S))
return res
def cal(self, index, end):
res=0
index.append(end)
left=0
for i in xrange(len(index)-1):
d1=index[i]-left
d2=index[i+1]-index[i]-1
res+=(1+d1+d2)*(2+d1+d2)/2-d1*(d1+1)/2-d2*(d2+1)/2
left=index[i]+1
return res |
d724ec | 9e3abf | Let's define a function countUniqueChars(s) that returns the number of unique characters on s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Example 1:
Input: s = "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.
Example 3:
Input: s = "LEETCODE"
Output: 92
Constraints:
1 <= s.length <= 100000
s consists of uppercase English letters only.
| from collections import defaultdict
class Solution:
def uniqueLetterString(self, S):
"""
:type S: str
:rtype: int
"""
last=defaultdict(list)
n=len(S)
ans=0
for i,c in enumerate(S):
last[c].append(i)
for j in last:
k=last[j]
if len(k)==1:
ans+=k[-1]+1
else:
ans+=k[-1]-k[-2]
return ans |
0e794a | d9a176 | You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected.
The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities 1 and n.
Note:
A path is a sequence of roads between two cities.
It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path.
The test cases are generated such that there is at least one path between 1 and n.
Example 1:
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
It can be shown that no other path has less score.
Example 2:
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
2 <= n <= 100000
1 <= roads.length <= 100000
roads[i].length == 3
1 <= ai, bi <= n
ai != bi
1 <= distancei <= 10000
There are no repeated edges.
There is at least one path between 1 and n.
| class UnionFind:
def __init__(self, n):
self.parent = list(range(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 merge(self, a, b):
self.parent[self.find(b)] = self.find(a)
class Solution:
def minScore(self, n: int, roads: List[List[int]]) -> int:
union = UnionFind(n+1)
for x, y, v in roads: union.merge(x, y)
ans = inf
for x, y, v in roads:
if union.find(x) == union.find(1):
ans = min(ans, v)
return ans |
fdd1f9 | d9a176 | You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected.
The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities 1 and n.
Note:
A path is a sequence of roads between two cities.
It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path.
The test cases are generated such that there is at least one path between 1 and n.
Example 1:
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
It can be shown that no other path has less score.
Example 2:
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
2 <= n <= 100000
1 <= roads.length <= 100000
roads[i].length == 3
1 <= ai, bi <= n
ai != bi
1 <= distancei <= 10000
There are no repeated edges.
There is at least one path between 1 and n.
| class Solution(object):
def minScore(self, n, roads):
adj = [[] for i in range(n)]
dist = [10 ** 6] * n
for u,v,w in roads:
u -=1; v-=1
dist[u] = min(dist[u], w)
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
q = [0]
seen[0] = 1
while q:
u = q.pop()
for v in adj[u]:
if not seen[v]:
seen[v] = 1
q.append(v)
best = 10 ** 6
for i in range(n):
if seen[i]:
best = min(best, dist[i])
return best
|
192838 | ec6248 | Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
| class Solution(object):
def maxDotProduct(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
a, b = nums1, nums2
if max(a)<0<min(b): return max(a)*min(b)
if max(b)<0<min(a): return max(b)*min(a)
n, m = len(a), len(b)
f = [[0]*(m+1) for _ in xrange(n+1)]
for i in xrange(n):
for j in xrange(m):
f[i+1][j+1] = max(f[i][j+1], f[i+1][j], f[i][j]+a[i]*b[j])
return f[n][m] |
ff165a | ec6248 | Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
| class Solution:
def maxDotProduct(self, a: List[int], b: List[int]) -> int:
from functools import lru_cache
@lru_cache(None)
def solve(n,m,fl):
if n==-1 or m==-1:
return 0 if fl else -(1<<30)
return max(a[n]*b[m]+solve(n-1,m-1,True),solve(n-1,m,fl),solve(n,m-1,fl))
return solve(len(a)-1,len(b)-1,False)
|
6c769a | ceae1b | Alice and Bob are opponents in an archery competition. The competition has set the following rules:
Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.
The points are then calculated as follows:
The target has integer scoring sections ranging from 0 to 11 inclusive.
For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points.
However, if ak == bk == 0, then nobody takes k points.
For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.
You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.
Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.
If there are multiple ways for Bob to earn the maximum total points, return any one of them.
Example 1:
Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]
Output: [0,0,0,0,1,1,0,0,1,2,3,1]
Explanation: The table above shows how the competition is scored.
Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.
It can be shown that Bob cannot obtain a score higher than 47 points.
Example 2:
Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]
Output: [0,0,0,0,0,0,0,0,1,1,1,0]
Explanation: The table above shows how the competition is scored.
Bob earns a total point of 8 + 9 + 10 = 27.
It can be shown that Bob cannot obtain a score higher than 27 points.
Constraints:
1 <= numArrows <= 100000
aliceArrows.length == bobArrows.length == 12
0 <= aliceArrows[i], bobArrows[i] <= numArrows
sum(aliceArrows[i]) == numArrows
| class Solution:
def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:
ans = 0
plan = [0] * 10
def search(i, arrows, current, current_plan):
nonlocal ans, plan
if i == len(aliceArrows):
if current > ans:
ans = current
plan = current_plan[:]
return
if aliceArrows[i] + 1 <= arrows:
current_plan.append(aliceArrows[i] + 1)
search(i + 1, arrows - aliceArrows[i] - 1, current + i, current_plan)
current_plan.pop()
current_plan.append(0)
search(i + 1, arrows, current, current_plan)
current_plan.pop()
search(1, numArrows, 0, [])
return [numArrows - sum(plan)] + plan
|
be5ebb | ceae1b | Alice and Bob are opponents in an archery competition. The competition has set the following rules:
Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.
The points are then calculated as follows:
The target has integer scoring sections ranging from 0 to 11 inclusive.
For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points.
However, if ak == bk == 0, then nobody takes k points.
For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.
You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.
Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.
If there are multiple ways for Bob to earn the maximum total points, return any one of them.
Example 1:
Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]
Output: [0,0,0,0,1,1,0,0,1,2,3,1]
Explanation: The table above shows how the competition is scored.
Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.
It can be shown that Bob cannot obtain a score higher than 47 points.
Example 2:
Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]
Output: [0,0,0,0,0,0,0,0,1,1,1,0]
Explanation: The table above shows how the competition is scored.
Bob earns a total point of 8 + 9 + 10 = 27.
It can be shown that Bob cannot obtain a score higher than 27 points.
Constraints:
1 <= numArrows <= 100000
aliceArrows.length == bobArrows.length == 12
0 <= aliceArrows[i], bobArrows[i] <= numArrows
sum(aliceArrows[i]) == numArrows
| class Solution(object):
def maximumBobPoints(self, numArrows, aliceArrows):
"""
:type numArrows: int
:type aliceArrows: List[int]
:rtype: List[int]
"""
dp = {}
dpi = {}
def dfs(k, i):
if i>=12: return 0
kk = (k, i)
if kk in dp: return dp[kk]
r=dfs(k, i+1)
s=0
if k>aliceArrows[i]:
t=dfs(k-aliceArrows[i]-1, i+1)+i
if r<t:
r=t
s=1
dp[kk]=r
dpi[kk]=s
return r
dfs(numArrows, 0)
k, i = numArrows, 0
bb = [0]*12
while i<12:
s = dpi[(k,i)]
bb[i]=0
if s:
k-=(aliceArrows[i]+1)
bb[i]=aliceArrows[i]+1
i+=1
else:
i+=1
if k: bb[0]+=k
return bb
|
7c1042 | b2d1af | There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2:
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Constraints:
2 <= n <= 100000
n - 1 <= connections.length <= 100000
0 <= ai, bi <= n - 1
ai != bi
There are no repeated connections.
| class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
graph=collections.defaultdict(set)
for x,y in connections:
graph[x].add(y)
graph[y].add(x)
def bridgeUtil(u, visited, parent, low, disc, time):
# Mark the current node as visited and print it
visited[u]= True
# Initialize discovery time and low value
disc[u] = time[0]
low[u] = time[0]
time[0]+=1
#Recur for all the vertices adjacent to this vertex
ans=[]
for v in graph[u]:
# If v is not visited yet, then make it a child of u
# in DFS tree and recur for it
if visited[v] == False :
parent[v] = u
find = bridgeUtil(v, visited, parent, low, disc,time)
ans.extend(find)
# Check if the subtree rooted with v has a connection to
# one of the ancestors of u
low[u] = min(low[u], low[v])
''' If the lowest vertex reachable from subtree
under v is below u in DFS tree, then u-v is
a bridge'''
if low[v] > disc[u]:
ans.append([u,v])
elif v != parent[u]: # Update low value of u for parent function calls.
low[u] = min(low[u], disc[v])
return ans
visited = [False] * (n)
disc = [float("Inf")] * (n)
low = [float("Inf")] * (n)
parent = [-1] * (n)
# Call the recursive helper function to find bridges
# in DFS tree rooted with vertex 'i'
ans=[]
time=[0]
for i in range(n):
if visited[i] == False:
ans.extend(bridgeUtil(i, visited, parent, low, disc,time))
return ans
|
67e3af | b2d1af | There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2:
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Constraints:
2 <= n <= 100000
n - 1 <= connections.length <= 100000
0 <= ai, bi <= n - 1
ai != bi
There are no repeated connections.
| class Solution(object):
def criticalConnections(self, n, connections):
graph = [[] for _ in xrange(n)]
for u, v in connections:
graph[u].append(v)
graph[v].append(u)
seen = [False] * n
time = [-1] * n
low = [-1] * n
t = [0]
self.ans = []
def dfs(node, parent = None):
seen[node] = True
time[node] = low[node] = t[0]
t[0] += 1
for nei in graph[node]:
if nei == parent: continue
if seen[nei]:
low[node] = min(low[node], time[nei])
else:
dfs(nei, node)
low[node] = min(low[nei], low[node])
if low[nei] > time[node]:
self.ans.append([node, nei])
for node, s in enumerate(seen):
if not s:
dfs(node)
return self.ans |
fb6c41 | c7901e | You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros.
Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: binary = "001"
Output: 2
Explanation: The good subsequences of binary are ["0", "0", "1"].
The unique good subsequences are "0" and "1".
Example 2:
Input: binary = "11"
Output: 2
Explanation: The good subsequences of binary are ["1", "1", "11"].
The unique good subsequences are "1" and "11".
Example 3:
Input: binary = "101"
Output: 5
Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
The unique good subsequences are "0", "1", "10", "11", and "101".
Constraints:
1 <= binary.length <= 100000
binary consists of only '0's and '1's.
| class Solution(object):
def numberOfUniqueGoodSubsequences(self, binary):
"""
:type binary: str
:rtype: int
"""
a, b, c = 0, 0, 0
for i in range(len(binary) - 1, -1, -1):
if binary[i] == '0':
a += b + 1
a %= 1000000007
c = 1
else:
b += a + 1
b %= 1000000007
return b + c |
24634c | c7901e | You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros.
Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: binary = "001"
Output: 2
Explanation: The good subsequences of binary are ["0", "0", "1"].
The unique good subsequences are "0" and "1".
Example 2:
Input: binary = "11"
Output: 2
Explanation: The good subsequences of binary are ["1", "1", "11"].
The unique good subsequences are "1" and "11".
Example 3:
Input: binary = "101"
Output: 5
Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
The unique good subsequences are "0", "1", "10", "11", and "101".
Constraints:
1 <= binary.length <= 100000
binary consists of only '0's and '1's.
| class Solution:
def numberOfUniqueGoodSubsequences(self, S: str) -> int:
MOD = 10 ** 9 + 7
numEndingWith = defaultdict(int)
for c in S:
extend = sum(numEndingWith.values())
byItself = 1 if c != '0' else 0
numEndingWith[c] = extend + byItself
numEndingWith[c] %= MOD
hasZero = 0
if '0' in S:
hasZero = 1
return (sum(numEndingWith.values()) + hasZero) % MOD
|
2c6fbb | 431f3f | In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Example 2:
Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
Explanation: The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
Constraints:
n == price.length == needs.length
1 <= n <= 6
0 <= price[i], needs[i] <= 10
1 <= special.length <= 100
special[i].length == n + 1
0 <= special[i][j] <= 50
| class Solution(object):
def shoppingOffers(self, price, special, needs):
"""
:type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int
"""
mem = dict()
def search(state):
ret = mem.get(state, None)
if ret is not None:
return ret
ret = sum(a*b for a,b in zip(price, state))
if ret == 0:
mem[state] = ret
return ret
for item in special:
sp, pp = item[:-1], item[-1]
if pp >= ret:
continue
new_state = tuple(b-a for a,b in zip(sp, state))
if any(x < 0 for x in new_state):
continue
ret = min(ret, pp + search(new_state))
mem[state] = ret
return ret
return search(tuple(needs))
|
a7221b | 431f3f | In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Example 2:
Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
Explanation: The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
Constraints:
n == price.length == needs.length
1 <= n <= 6
0 <= price[i], needs[i] <= 10
1 <= special.length <= 100
special[i].length == n + 1
0 <= special[i][j] <= 50
| class Solution:
def shoppingOffers(self, price, special, needs):
"""
:type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int
"""
N = len(needs)
comb = {((0,) * N): 0}
for sale in special:
comb2 = {}
for k, v in comb.items():
k = list(k)
while True:
for i in range(N):
k[i] += sale[i]
if k[i] > needs[i]: break
else:
v += sale[-1]
k2 = tuple(k)
comb2[k2] = min(comb.get(k2, float('inf')), v)
continue
break
comb.update(comb2)
cost = float('inf')
for k, v in comb.items():
p2 = sum(price[i] * (needs[i] - k[i]) for i in range(N))
cost = min(cost, p2 + v)
return cost |
37d8a0 | 758e4e | There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
The items that belong to the same group are next to each other in the sorted list.
There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
Return any solution if there is more than one solution and return an empty list if there is no solution.
Example 1:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]
Example 2:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
Constraints:
1 <= m <= n <= 3 * 10000
group.length == beforeItems.length == n
-1 <= group[i] <= m - 1
0 <= beforeItems[i].length <= n - 1
0 <= beforeItems[i][j] <= n - 1
i != beforeItems[i][j]
beforeItems[i] does not contain duplicates elements.
| class Solution:
def topoSort(self, nodes, edges):
# if fail: return -1
if not edges:
return nodes
inDegree = {i:0 for i in nodes}
to = {i:[] for i in nodes}
for s, t in edges:
inDegree[t] += 1
to[s].append(t)
finishCount = 0
targetCount = len(nodes)
q = []
qHead = 0
for i in nodes:
if inDegree[i] == 0:
q.append(i)
finishCount += 1
while qHead < len(q):
cur = q[qHead]
for t in to[cur]:
inDegree[t] -= 1
if inDegree[t] == 0:
q.append(t)
finishCount += 1
qHead += 1
if finishCount < targetCount:
return -1
return q
def sortItems(self, n: int, m: int, group, beforeItems):
for i in range(len(group)):
if group[i] == -1:
group[i] = m
m += 1
itemInGroup = [[] for _ in range(m)]
for i in range(len(group)):
itemInGroup[group[i]].append(i)
edgeInGroup = [set() for _ in range(m)]
edgeBetweenGroup = set()
for i in range(len(beforeItems)):
for pre in beforeItems[i]:
if group[i] == group[pre]:
edgeInGroup[group[i]].add((pre, i))
else:
edgeBetweenGroup.add((group[pre], group[i]))
for i in range(m):
if edgeInGroup[i]:
res = self.topoSort(itemInGroup[i], edgeInGroup[i])
if res == -1:
return []
itemInGroup[i] = res
groupOrder = list(range(m))
res = self.topoSort(groupOrder, edgeBetweenGroup)
if res == -1:
return []
groupOrder = res
ans = []
for g in groupOrder:
for i in itemInGroup[g]:
ans.append(i)
return ans
|
6ed54b | 758e4e | There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
The items that belong to the same group are next to each other in the sorted list.
There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
Return any solution if there is more than one solution and return an empty list if there is no solution.
Example 1:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]
Example 2:
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
Constraints:
1 <= m <= n <= 3 * 10000
group.length == beforeItems.length == n
-1 <= group[i] <= m - 1
0 <= beforeItems[i].length <= n - 1
0 <= beforeItems[i][j] <= n - 1
i != beforeItems[i][j]
beforeItems[i] does not contain duplicates elements.
| class Solution(object):
def sortItems(self, n, m, group, beforeItems):
items = list(enumerate(group))
items.sort(key = lambda z: z[1])
groups = []
groupsets = []
setsindex = [None] * n
GRAY, BLACK = 0, 1
def topological(graph, enter=None):
ans,state = [], {}
if enter is None: enter = set(graph)
else: enter = set(range(n))
def dfs(node):
state[node] = GRAY
for k in graph.get(node, ()):
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK: continue
enter.discard(k)
dfs(k)
ans.append(node)
state[node] = BLACK
while enter: dfs(enter.pop())
return ans[::-1]
def topological_list(graph):
ans,state = [], {}
enter = set(range(len(graph)))
def dfs(node):
state[node] = GRAY
for k in graph[node]:
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK: continue
enter.discard(k)
dfs(k)
ans.append(node)
state[node] = BLACK
while enter: dfs(enter.pop())
return ans[::-1]
def internalsort(aset):
graph = collections.defaultdict(list)
for u in aset:
graph[u]
for v in beforeItems[u]:
if v in aset:
graph[v].append(u)
try:
return topological(graph)
except:
#print 'isort err', aset, [beforeItems[u] for u in aset]
return None
index = 0
for k, grp in itertools.groupby(items, key = lambda z: z[1]):
grp = list(grp)
rowset = {x for x, y in grp}
groupsets.append(rowset)
for x in rowset:
setsindex[x] = index
row = internalsort(rowset)
groups.append(row)
if row is None: return []
index += 1
# Merge before requirements
graph2 = [set() for _ in xrange(len(groups))]
for gx, group in enumerate(groups):
beforeset = set()
for y in group:
for x in beforeItems[y]:
hx = setsindex[x]
if hx != gx:
graph2[hx].add(gx)
try:
ans = topological_list(graph2)
fans = []
for gx in ans:
fans.extend(groups[gx])
return fans
except:
return [] |
af8bde | e9384c | Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.
A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.
Example 1:
Input: nums = [1,4,2,7], low = 2, high = 6
Output: 6
Explanation: All nice pairs (i, j) are as follows:
- (0, 1): nums[0] XOR nums[1] = 5
- (0, 2): nums[0] XOR nums[2] = 3
- (0, 3): nums[0] XOR nums[3] = 6
- (1, 2): nums[1] XOR nums[2] = 6
- (1, 3): nums[1] XOR nums[3] = 3
- (2, 3): nums[2] XOR nums[3] = 5
Example 2:
Input: nums = [9,8,4,2,1], low = 5, high = 14
Output: 8
Explanation: All nice pairs (i, j) are as follows:
- (0, 2): nums[0] XOR nums[2] = 13
- (0, 3): nums[0] XOR nums[3] = 11
- (0, 4): nums[0] XOR nums[4] = 8
- (1, 2): nums[1] XOR nums[2] = 12
- (1, 3): nums[1] XOR nums[3] = 10
- (1, 4): nums[1] XOR nums[4] = 9
- (2, 3): nums[2] XOR nums[3] = 6
- (2, 4): nums[2] XOR nums[4] = 5
Constraints:
1 <= nums.length <= 2 * 10000
1 <= nums[i] <= 2 * 10000
1 <= low <= high <= 2 * 10000
| class Solution:
def countPairs(self, nums: List[int], low: int, high: int) -> int:
# indexing = [2**i for i in range(15, -1, -1)]
to_key = lambda t : bin(t)[2:].rjust(16,'0')
count = collections.Counter()
for t in nums :
key = to_key(t)
for i in range(16) :
count[key[:i+1]] += 1
# print(dict(count))
def countm(maxv) :
to_ret = 0
ky = to_key(maxv)
for t in nums :
k = to_key(t)
# print(ky, k)
prex = ''
for i in range(16) :
if ky[i] == '0' :
prex += k[i]
else :
# print('check', prex+k[i], count[prex+k[i]])
to_ret += count[prex+k[i]]
prex += '1' if k[i] == '0' else '0'
# print('to_ret', to_ret)
# print('maxv', maxv, to_ret)
return to_ret
# return countm(high+1)
# return countm(low)
return (countm(high+1) - countm(low)) // 2
|
17259a | e9384c | Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.
A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.
Example 1:
Input: nums = [1,4,2,7], low = 2, high = 6
Output: 6
Explanation: All nice pairs (i, j) are as follows:
- (0, 1): nums[0] XOR nums[1] = 5
- (0, 2): nums[0] XOR nums[2] = 3
- (0, 3): nums[0] XOR nums[3] = 6
- (1, 2): nums[1] XOR nums[2] = 6
- (1, 3): nums[1] XOR nums[3] = 3
- (2, 3): nums[2] XOR nums[3] = 5
Example 2:
Input: nums = [9,8,4,2,1], low = 5, high = 14
Output: 8
Explanation: All nice pairs (i, j) are as follows:
- (0, 2): nums[0] XOR nums[2] = 13
- (0, 3): nums[0] XOR nums[3] = 11
- (0, 4): nums[0] XOR nums[4] = 8
- (1, 2): nums[1] XOR nums[2] = 12
- (1, 3): nums[1] XOR nums[3] = 10
- (1, 4): nums[1] XOR nums[4] = 9
- (2, 3): nums[2] XOR nums[3] = 6
- (2, 4): nums[2] XOR nums[4] = 5
Constraints:
1 <= nums.length <= 2 * 10000
1 <= nums[i] <= 2 * 10000
1 <= low <= high <= 2 * 10000
| class TrieNode:
def __init__(self):
self.cnt = 0
self.child = [None, None]
class Solution(object):
def countPairs(self, nums, low, high):
"""
:type nums: List[int]
:type low: int
:type high: int
:rtype: int
"""
n = len(nums)
m = max(max(nums), high).bit_length() # <= 15
root = TrieNode()
def add(num):
curr = root
for level in xrange(m-1, -1, -1):
curr.cnt += 1
c = (num >> level) & 1
if curr.child[c] is None:
curr.child[c] = TrieNode()
curr = curr.child[c]
curr.cnt += 1
def query(num, lim):
curr = root
r = 0
for level in xrange(m-1, -1, -1):
a = (num >> level) & 1
b = (lim >> level) & 1
if b and curr.child[a]:
r += curr.child[a].cnt
curr = curr.child[a^b]
if curr is None: break
if curr:
r += curr.cnt
return r
for i in nums:
add(i)
def f(lim):
r = sum(query(i, lim) for i in nums)
return (r - n) // 2
return f(high) - f(low-1) |
16c312 | f16d2f | You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.
A subset is a group integers that appear in the array with no particular order.
Example 1:
Input: nums = [1,2,1,4], k = 2
Output: 4
Explanation: The optimal distribution of subsets is [1,2] and [1,4].
The incompatibility is (2-1) + (4-1) = 4.
Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input: nums = [5,3,3,6,3,3], k = 3
Output: -1
Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16
nums.length is divisible by k
1 <= nums[i] <= nums.length
| class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
L = len(nums)
k = L // k
@lru_cache(None)
def f(av):
ns = []
for i in range(L):
if av & (1 << i) == 0:
ns.append(i)
if not ns:
return 0
d = 1e9
for c in itertools.combinations(ns, k):
iii = c
c = [nums[i] for i in c]
if len(set(c)) != len(c):
continue
m = av
for n in iii:
m |= (1 << n)
dd = max(c) - min(c)
dd = dd + f(m)
d = min(d, dd)
# print(ns, d)
return d
r = f(0)
return r if r < 1e8 else -1
|
377cbb | f16d2f | You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.
A subset is a group integers that appear in the array with no particular order.
Example 1:
Input: nums = [1,2,1,4], k = 2
Output: 4
Explanation: The optimal distribution of subsets is [1,2] and [1,4].
The incompatibility is (2-1) + (4-1) = 4.
Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input: nums = [5,3,3,6,3,3], k = 3
Output: -1
Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16
nums.length is divisible by k
1 <= nums[i] <= nums.length
| class Solution(object):
def minimumIncompatibility(self, nums, k):
g = k
k = len(nums)/g
p = [i for i in xrange(k)]
N = [1<<i for i in xrange(len(nums))]
M = []
def S(p):
r = 0
for u in p: r += N[u]
return r
M.append(S(p))
while 1:
if p[-1]<len(nums)-1:
p[-1]+=1
M.append(S(p))
else:
inc = 0
for u in xrange(len(p)-2, -1, -1):
if p[u]<p[u+1]-1:
inc = 1
p[u]+=1
for d in xrange(u+1, len(p)):
p[d]=p[d-1]+1
break
if not inc: break
M.append(S(p))
IN = {}
ValidM = []
for mask in M:
s = set()
b = 0
MAX, MIN = 0, float('inf')
for i in xrange(len(N)):
if mask | N[i] == mask:
if nums[i] in s:
b = 1
break
s.add(nums[i])
MAX = max(MAX, nums[i])
MIN = min(MIN, nums[i])
if not b:
IN[mask] = MAX-MIN
ValidM.append(mask)
M = ValidM
memo = {}
def sol(mask, g):
if (mask, g) in memo: return memo[(mask, g)]
res = -1
if g == 1:
for m in M:
if m & mask == 0:
res = IN[m]
break
else:
for m in M:
if m & mask == 0:
r = sol(mask|m, g-1)
if r != -1:
if res == -1: res = IN[m]+sol(mask|m, g-1)
else:
res = min(res,IN[m]+sol(mask|m, g-1))
memo[(mask, g)]=res
return res
return sol(0, g)
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
|
28d6a7 | 0ebc72 | A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.
If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.
Example 1:
Input: stones = [0,1,3,5,6,8,12,17]
Output: true
Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
Input: stones = [0,1,2,3,4,8,9,11]
Output: false
Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
Constraints:
2 <= stones.length <= 2000
0 <= stones[i] <= 2^31 - 1
stones[0] == 0
stones is sorted in a strictly increasing order.
| class Solution(object):
def canCross(self, stones):
D={}
for p in stones:
D[p]=set()
D[0].add(1)
for p in stones:
for l in D[p]:
if p+l in D:
D[p+l].add(l)
D[p+l].add(l+1)
if l>0:
D[p+l].add(l-1)
return not not D[stones[-1]]
"""
:type stones: List[int]
:rtype: bool
"""
|
5472af | d1bf6d | Design the basic function of Excel and implement the function of the sum formula.
Implement the Excel class:
Excel(int height, char width) Initializes the object with the height and the width of the sheet. The sheet is an integer matrix mat of size height x width with the row index in the range [1, height] and the column index in the range ['A', width]. All the values should be zero initially.
void set(int row, char column, int val) Changes the value at mat[row][column] to be val.
int get(int row, char column) Returns the value at mat[row][column].
int sum(int row, char column, List<String> numbers) Sets the value at mat[row][column] to be the sum of cells represented by numbers and returns the value at mat[row][column]. This sum formula should exist until this cell is overlapped by another value or another sum formula. numbers[i] could be on the format:
"ColRow" that represents a single cell.
For example, "F7" represents the cell mat[7]['F'].
"ColRow1:ColRow2" that represents a range of cells. The range will always be a rectangle where "ColRow1" represent the position of the top-left cell, and "ColRow2" represents the position of the bottom-right cell.
For example, "B3:F7" represents the cells mat[i][j] for 3 <= i <= 7 and 'B' <= j <= 'F'.
Note: You could assume that there will not be any circular sum reference.
For example, mat[1]['A'] == sum(1, "B") and mat[1]['B'] == sum(1, "A").
Example 1:
Input
["Excel", "set", "sum", "set", "get"]
[[3, "C"], [1, "A", 2], [3, "C", ["A1", "A1:B2"]], [2, "B", 2], [3, "C"]]
Output
[null, null, 4, null, 6]
Explanation
Excel excel = new Excel(3, "C");
// construct a 3*3 2D array with all zero.
// A B C
// 1 0 0 0
// 2 0 0 0
// 3 0 0 0
excel.set(1, "A", 2);
// set mat[1]["A"] to be 2.
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 0
excel.sum(3, "C", ["A1", "A1:B2"]); // return 4
// set mat[3]["C"] to be the sum of value at mat[1]["A"] and the values sum of the rectangle range whose top-left cell is mat[1]["A"] and bottom-right cell is mat[2]["B"].
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 4
excel.set(2, "B", 2);
// set mat[2]["B"] to be 2. Note mat[3]["C"] should also be changed.
// A B C
// 1 2 0 0
// 2 0 2 0
// 3 0 0 6
excel.get(3, "C"); // return 6
Constraints:
1 <= height <= 26
'A' <= width <= 'Z'
1 <= row <= height
'A' <= column <= width
-100 <= val <= 100
1 <= numbers.length <= 5
numbers[i] has the format "ColRow" or "ColRow1:ColRow2".
At most 100 calls will be made to set, get, and sum.
| import re
class Excel(object):
CELL_RE = re.compile(r'\A(.)(\d+)\Z')
RANGE_RE = re.compile(r'\A(.)(\d+):(.)(\d+)\Z')
def __init__(self, H,W):
"""
:type H: int
:type W: str
"""
self.height, self.width = self._key(H, W)
self.height += 1
self.width += 1
self.data = [[lambda: 0 for _ in xrange(self.height)]
for _ in xrange(self.width)]
def set(self, r, c, v):
"""
:type r: int
:type c: str
:type v: int
:rtype: void
"""
r, c = self._key(r,c)
self.data[c][r] = lambda: v
def get(self, r, c):
"""
:type r: int
:type c: str
:rtype: int
"""
r, c = self._key(r,c)
return self.data[c][r]()
def sum(self, r, c, strs):
"""
:type r: int
:type c: str
:type strs: List[str]
:rtype: int
"""
r, c = self._key(r,c)
keys = [v for s in strs for v in self._keyrange(s)]
def inner():
return sum(self.data[c][r]() for r, c in keys)
self.data[c][r] = inner
return inner()
@staticmethod
def _key(r, c): return r-1, ord(c)-ord('A')
@staticmethod
def _keyrange(s):
m = Excel.CELL_RE.match(s)
if m:
c, r = m.groups()
yield Excel._key(int(r), c)
m = Excel.RANGE_RE.match(s)
if m:
c1, r1, c2, r2 = m.groups()
r1, c1 = Excel._key(int(r1), c1)
r2, c2 = Excel._key(int(r2), c2)
for r in xrange(r1, r2+1):
for c in xrange(c1, c2+1):
yield r, c
# Your Excel object will be instantiated and called as such:
# obj = Excel(H, W)
# obj.set(r,c,v)
# param_2 = obj.get(r,c)
# param_3 = obj.sum(r,c,strs) |
eebd76 | d1bf6d | Design the basic function of Excel and implement the function of the sum formula.
Implement the Excel class:
Excel(int height, char width) Initializes the object with the height and the width of the sheet. The sheet is an integer matrix mat of size height x width with the row index in the range [1, height] and the column index in the range ['A', width]. All the values should be zero initially.
void set(int row, char column, int val) Changes the value at mat[row][column] to be val.
int get(int row, char column) Returns the value at mat[row][column].
int sum(int row, char column, List<String> numbers) Sets the value at mat[row][column] to be the sum of cells represented by numbers and returns the value at mat[row][column]. This sum formula should exist until this cell is overlapped by another value or another sum formula. numbers[i] could be on the format:
"ColRow" that represents a single cell.
For example, "F7" represents the cell mat[7]['F'].
"ColRow1:ColRow2" that represents a range of cells. The range will always be a rectangle where "ColRow1" represent the position of the top-left cell, and "ColRow2" represents the position of the bottom-right cell.
For example, "B3:F7" represents the cells mat[i][j] for 3 <= i <= 7 and 'B' <= j <= 'F'.
Note: You could assume that there will not be any circular sum reference.
For example, mat[1]['A'] == sum(1, "B") and mat[1]['B'] == sum(1, "A").
Example 1:
Input
["Excel", "set", "sum", "set", "get"]
[[3, "C"], [1, "A", 2], [3, "C", ["A1", "A1:B2"]], [2, "B", 2], [3, "C"]]
Output
[null, null, 4, null, 6]
Explanation
Excel excel = new Excel(3, "C");
// construct a 3*3 2D array with all zero.
// A B C
// 1 0 0 0
// 2 0 0 0
// 3 0 0 0
excel.set(1, "A", 2);
// set mat[1]["A"] to be 2.
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 0
excel.sum(3, "C", ["A1", "A1:B2"]); // return 4
// set mat[3]["C"] to be the sum of value at mat[1]["A"] and the values sum of the rectangle range whose top-left cell is mat[1]["A"] and bottom-right cell is mat[2]["B"].
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 4
excel.set(2, "B", 2);
// set mat[2]["B"] to be 2. Note mat[3]["C"] should also be changed.
// A B C
// 1 2 0 0
// 2 0 2 0
// 3 0 0 6
excel.get(3, "C"); // return 6
Constraints:
1 <= height <= 26
'A' <= width <= 'Z'
1 <= row <= height
'A' <= column <= width
-100 <= val <= 100
1 <= numbers.length <= 5
numbers[i] has the format "ColRow" or "ColRow1:ColRow2".
At most 100 calls will be made to set, get, and sum.
| class Excel:
def __init__(self, H,W):
"""
:type H: int
:type W: str
"""
self.h = H
self.w = ord(W) - ord('A') + 1
self.entries = [[0 for i in range(self.w)] for i in range(self.h)] #self.entries[h][w]
self.sums = [[0 for i in range(self.w+1)] for i in range(self.h+1)]
def set(self, r, c, v):
"""
:type r: int
:type c: str
:type v: int
:rtype: void
"""
self.entries[r-1][ord(c)-ord('A')] = v
self.recal_sums()
def get(self, r, c):
"""
:type r: int
:type c: str
:rtype: int
"""
X = self.entries[r-1][ord(c)-ord('A')]
if isinstance(X, list):
result = 0
for s in X:
result += self.get_sum(s)
return result
else:
return X
def sum(self, r, c, strs):
"""
:type r: int
:type c: str
:type strs: List[str]
:rtype: int
"""
self.entries[r-1][ord(c)-ord('A')] = strs
self.recal_sums()
return self.get(r, c)
def exp_to_entry(self, str):
height = int(str[1:]) - 1
width = ord(str[0]) - ord('A')
return height, width
def recal_sums(self):
for i in range(self.w):
for j in range(self.h):
self.sums[j+1][i+1] = self.get(j+1,chr(ord('A') + i)) + self.sums[j][i+1] + self.sums[j+1][i] - self.sums[j][i]
def get_sum(self, s):
if ":" not in s:
h,w = self.exp_to_entry(s)
return self.get(h+1, chr(ord('A')+w))
else:
[A, B] = s.split(":")
ha, wa = self.exp_to_entry(A)
hb, wb = self.exp_to_entry(B)
return self.sums[hb+1][wb+1] - self.sums[hb+1][wa] - self.sums[ha][wb+1]+self.sums[ha][wa]
# Your Excel object will be instantiated and called as such:
# obj = Excel(H, W)
# obj.set(r,c,v)
# param_2 = obj.get(r,c)
# param_3 = obj.sum(r,c,strs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.