sol_id
stringlengths 6
6
| problem_id
stringlengths 6
6
| problem_text
stringlengths 322
4.55k
| solution_text
stringlengths 137
5.74k
|
---|---|---|---|
392ead | 0fb806 | You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
Example 1:
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
Example 3:
Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i] only consists of lowercase English letters.
| class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len)
f = collections.defaultdict(int)
ans = 0
for w in words:
l = len(w)
for i in range(l):
f[w] = max(f[w], f[w[:i] + w[i+1:]] + 1)
ans = max(ans, f[w])
return ans |
cb5860 | 0fb806 | You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
Example 1:
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
Example 3:
Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i] only consists of lowercase English letters.
| class Solution(object):
def longestStrChain(self, words):
"""
:type words: List[str]
:rtype: int
"""
words.sort(key=len)
dp = [1]*len(words)
for i in range(len(words)):
for j in range(i):
if self.isPredecessor(words[i], words[j]):
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
def isPredecessor(self, w1, w2):
if len(w1) - len(w2) != 1:
return False
i, j = 0, 0
indicator = False
while j < len(w2):
if w1[i] == w2[j]:
i += 1
j += 1
else:
if indicator:
return False
i += 1
indicator = True
return True |
ad21b0 | 95673e | A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n" ("s ubstitutio n")
"sub4u4" ("sub stit u tion")
"12" ("substitution")
"su3i1u2on" ("su bst i t u ti on")
"substitution" (no substrings replaced)
Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because the replaced substrings are adjacent.
The length of an abbreviation is the number of letters that were not replaced plus the number of substrings that were replaced. For example, the abbreviation "s10n" has a length of 3 (2 letters + 1 substring) and "su3i1u2on" has a length of 9 (6 letters + 3 substrings).
Given a target string target and an array of strings dictionary, return an abbreviation of target with the shortest possible length such that it is not an abbreviation of any string in dictionary. If there are multiple shortest abbreviations, return any of them.
Example 1:
Input: target = "apple", dictionary = ["blade"]
Output: "a4"
Explanation: The shortest abbreviation of "apple" is "5", but this is also an abbreviation of "blade".
The next shortest abbreviations are "a4" and "4e". "4e" is an abbreviation of blade while "a4" is not.
Hence, return "a4".
Example 2:
Input: target = "apple", dictionary = ["blade","plain","amber"]
Output: "1p3"
Explanation: "5" is an abbreviation of both "apple" but also every word in the dictionary.
"a4" is an abbreviation of "apple" but also "amber".
"4e" is an abbreviation of "apple" but also "blade".
"1p3", "2p2", and "3l1" are the next shortest abbreviations of "apple".
Since none of them are abbreviations of words in the dictionary, returning any of them is correct.
Constraints:
m == target.length
n == dictionary.length
1 <= m <= 21
0 <= n <= 1000
1 <= dictionary[i].length <= 100
log2(n) + m <= 21 if n > 0
target and dictionary[i] consist of lowercase English letters.
dictionary does not contain target.
| class Solution(object):
def minAbbreviation(self, target, dictionary):
"""
:type target: str
:type dictionary: List[str]
:rtype: str
"""
ans = {}
self.dfs(ans, target, [], 0)
for i in range(1, len(target) + 1):
if i in ans:
for abbr in ans[i]:
found = False
for d in dictionary:
if self.check(abbr, d):
found = True
break
if not found:
return abbr
return ""
def dfs(self, ans, word, cur, i):
if i == len(word):
l = len(cur)
s = "".join(cur)
if not l in ans:
ans[l] = [s]
else:
ans[l].append(s)
return
for j in range(i + 1, len(word)):
cur.append(str(j - i + 1))
if j + 1 < len(word):
cur.append(word[j + 1])
self.dfs(ans, word, cur, j + 2)
cur.pop()
cur.pop()
else:
self.dfs(ans, word, cur, j + 1)
cur.pop()
cur.append(word[i])
self.dfs(ans, word, cur, i + 1)
cur.pop()
def check(self, abbr, word):
i = 0
j = 0
while i < len(abbr) and j < len(word):
if not self.isdigit(abbr[i]):
if abbr[i] != word[j]:
return False
i += 1
j += 1
else:
n = 0
while i < len(abbr) and self.isdigit(abbr[i]):
n = n * 10 + (ord(abbr[i]) - 48)
i += 1
j += n
return i == len(abbr) and j == len(word)
def isdigit(self, c):
return 48 <= ord(c) <= 57 |
fe75d8 | 33ccd9 | There is an exam room with n seats in a single row labeled from 0 to n - 1.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.
Design a class that simulates the mentioned exam room.
Implement the ExamRoom class:
ExamRoom(int n) Initializes the object of the exam room with the number of the seats n.
int seat() Returns the label of the seat at which the next student will set.
void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.
Example 1:
Input
["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]
[[10], [], [], [], [], [4], []]
Output
[null, 0, 9, 4, 2, null, 5]
Explanation
ExamRoom examRoom = new ExamRoom(10);
examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.
examRoom.seat(); // return 9, the student sits at the last seat number 9.
examRoom.seat(); // return 4, the student sits at the last seat number 4.
examRoom.seat(); // return 2, the student sits at the last seat number 2.
examRoom.leave(4);
examRoom.seat(); // return 5, the student sits at the last seat number 5.
Constraints:
1 <= n <= 10^9
It is guaranteed that there is a student sitting at seat p.
At most 10000 calls will be made to seat and leave.
| class ExamRoom:
def __init__(self, N):
"""
:type N: int
"""
self.n = N
self.a = []
def seat(self):
"""
:rtype: int
"""
if len(self.a) == 0:
self.a = [0]
return 0
cur = self.a[0]
mark = 0
for i in range(len(self.a) - 1):
h, t = self.a[i], self.a[i + 1]
m = (h + t) // 2
if m - h > cur:
cur = m - h
mark = m
if (self.n - 1) - self.a[-1] > cur:
cur = (self.n - 1) - self.a[-1]
mark = self.n - 1
if mark == 0:
self.a = [mark] + self.a
elif mark == self.n - 1:
self.a = self.a + [mark]
else:
idx = None
for i in range(len(self.a) - 1):
if self.a[i] < mark < self.a[i + 1]:
idx = i + 1
break
self.a = self.a[:idx] + [mark] + self.a[idx:]
return mark
def leave(self, p):
"""
:type p: int
:rtype: void
"""
idx = None
for i in range(len(self.a)):
if self.a[i] == p:
idx = i
break
self.a = self.a[:idx] + self.a[idx + 1:]
|
60f00b | 33ccd9 | There is an exam room with n seats in a single row labeled from 0 to n - 1.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.
Design a class that simulates the mentioned exam room.
Implement the ExamRoom class:
ExamRoom(int n) Initializes the object of the exam room with the number of the seats n.
int seat() Returns the label of the seat at which the next student will set.
void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.
Example 1:
Input
["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]
[[10], [], [], [], [], [4], []]
Output
[null, 0, 9, 4, 2, null, 5]
Explanation
ExamRoom examRoom = new ExamRoom(10);
examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.
examRoom.seat(); // return 9, the student sits at the last seat number 9.
examRoom.seat(); // return 4, the student sits at the last seat number 4.
examRoom.seat(); // return 2, the student sits at the last seat number 2.
examRoom.leave(4);
examRoom.seat(); // return 5, the student sits at the last seat number 5.
Constraints:
1 <= n <= 10^9
It is guaranteed that there is a student sitting at seat p.
At most 10000 calls will be made to seat and leave.
| class Note():
def __init__(self, val):
self.val = val
self.next = None
class ExamRoom(object):
def __init__(self, N):
"""
:type N: int
"""
self.root = None
self.n = N
def seat(self):
"""
:rtype: int
"""
if not self.root:
self.root = Note(0)
return 0
m = -1
mnote = None
mpos = -1
note = self.root
if note.val != 0:
l = (note.val - 0)
if l > m:
m = l
mnote = None
mpos = 0
while note.next is not None:
l = (note.next.val - note.val) / 2
if l > m:
m = l
mnote = note
mpos = (note.next.val - note.val) / 2 + note.val
note = note.next
if note.val != self.n - 1:
l = self.n - 1 - note.val
if l > m:
m = l
mnote = note
mpos = self.n - 1
if mpos == 0:
newroot = Note(0)
newroot.next = self.root
self.root = newroot
return 0
elif mpos == self.n - 1:
newn = Note(mpos)
mnote.next = newn
return mpos
else:
newn = Note(mpos)
newn.next = mnote.next
mnote.next = newn
return mpos
def leave(self, p):
"""
:type p: int
:rtype: void
"""
if p == self.root.val:
self.root = self.root.next
return
note = self.root
while note.next.val != p:
note = note.next
note.next = note.next.next
# Your ExamRoom object will be instantiated and called as such:
# obj = ExamRoom(N)
# param_1 = obj.seat()
# obj.leave(p) |
1c067e | 418959 | You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).
You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.
Return the smallest possible total score that you can achieve with some triangulation of the polygon.
Example 1:
Input: values = [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
Example 2:
Input: values = [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
The minimum score is 144.
Example 3:
Input: values = [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
Constraints:
n == values.length
3 <= n <= 50
1 <= values[i] <= 100
| import functools
class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
@functools.lru_cache(None)
def solve(labels):
if len(labels) == 3:
return functools.reduce(operator.mul, labels)
res = math.inf
n = len(labels)
for i in range(2, n - 1):
left = solve(labels[:i + 1])
right = solve((labels[0],) + labels[i:])
res = min(res, left + right)
return min(res, labels[-1] * labels[0] * labels[1] + solve(labels[1:]))
return solve(tuple(A))
|
b7ebaa | 418959 | You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).
You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.
Return the smallest possible total score that you can achieve with some triangulation of the polygon.
Example 1:
Input: values = [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
Example 2:
Input: values = [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
The minimum score is 144.
Example 3:
Input: values = [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
Constraints:
n == values.length
3 <= n <= 50
1 <= values[i] <= 100
| class Solution(object):
def minScoreTriangulation(self, A):
"""
:type A: List[int]
:rtype: int
"""
n=len(A)
L=[[0]*n for _ in xrange(n)]
for d in xrange(1,n):
for i in xrange(n-d):
if d==1:
L[i][i+d]=0
elif d==2:
L[i][i+2]=A[i]*A[i+1]*A[i+2]
else:
minn=float("inf")
for k in xrange(1,d):
minn=min(minn, A[i]*A[i+k]*A[i+d]+L[i][i+k]+L[i+k][i+d])
L[i][i+d]=minn
return L[0][n-1] |
015369 | de3d39 | You are given a 0-indexed m x n matrix grid consisting of positive integers.
You can start at any cell in the first column of the matrix, and traverse the grid in the following way:
From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell.
Return the maximum number of moves that you can perform.
Example 1:
Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
Output: 3
Explanation: We can start at the cell (0, 0) and make the following moves:
- (0, 0) -> (0, 1).
- (0, 1) -> (1, 2).
- (1, 2) -> (2, 3).
It can be shown that it is the maximum number of moves that can be made.
Example 2:
Input: grid = [[3,2,4],[2,1,9],[1,1,7]]
Output: 0
Explanation: Starting from any cell in the first column we cannot perform any moves.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 10^5
1 <= grid[i][j] <= 10^6
| class Solution(object):
def maxMoves(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
q, a = deque(), -1
for i in range(len(grid)):
q.append([i, 0])
grid[i][0] *= -1
while q:
for s in range(len(q), 0, -1):
e = q.popleft()
for i in range(e[0] - 1, e[0] + 2):
if 0 <= i and i < len(grid) and 0 <= e[1] + 1 and e[1] + 1 < len(grid[0]) and -grid[e[0]][e[1]] < grid[i][e[1] + 1]:
q.append([i, e[1] + 1])
grid[i][e[1] + 1] *= -1
a += 1
return max(0, a) |
267ce9 | de3d39 | You are given a 0-indexed m x n matrix grid consisting of positive integers.
You can start at any cell in the first column of the matrix, and traverse the grid in the following way:
From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell.
Return the maximum number of moves that you can perform.
Example 1:
Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
Output: 3
Explanation: We can start at the cell (0, 0) and make the following moves:
- (0, 0) -> (0, 1).
- (0, 1) -> (1, 2).
- (1, 2) -> (2, 3).
It can be shown that it is the maximum number of moves that can be made.
Example 2:
Input: grid = [[3,2,4],[2,1,9],[1,1,7]]
Output: 0
Explanation: Starting from any cell in the first column we cannot perform any moves.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 10^5
1 <= grid[i][j] <= 10^6
| class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[0]*n for _ in range(m)]
for j in range(n-2, -1, -1):
for i in range(m-1, -1, -1):
for dx in [-1, 0, 1]:
nx = i + dx
if 0 <= nx < m and grid[nx][j+1] > grid[i][j]:
dp[i][j] = max(dp[i][j], 1 + dp[nx][j+1])
return max(dp[i][0] for i in range(m))
|
a17ec6 | e803b6 | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
Note: Test cases are generated such that there will always be at least one correct answer.
Example 1:
Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Explanation: [1,2,-3] is able to achieve the given subset sums:
- []: sum is 0
- [1]: sum is 1
- [2]: sum is 2
- [1,2]: sum is 3
- [-3]: sum is -3
- [1,-3]: sum is -2
- [2,-3]: sum is -1
- [1,2,-3]: sum is 0
Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.
Example 2:
Input: n = 2, sums = [0,0,0,0]
Output: [0,0]
Explanation: The only correct answer is [0,0].
Example 3:
Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]
Output: [0,-1,4,5]
Explanation: [0,-1,4,5] is able to achieve the given subset sums.
Constraints:
1 <= n <= 15
sums.length == 2n
-10000 <= sums[i] <= 10000
| class Solution:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
def remove_v(nt, t) :
assert t >= 0
to_remove = collections.Counter()
small = []
large = []
for v in nt :
if to_remove[v] > 0 :
to_remove[v] -= 1
continue
small.append(v)
large.append(v+t)
to_remove[v+t] += 1
if not len(small)*2==len(nt) :
return None, None
return small, large
def solve(n=n, sums=sums) :
if n == 1 :
return [sums[1]] if sums[0] == 0 else [sums[0]]
sums = sorted(sums)
t = sums[-1]-sums[-2]
# 要么存在t,要么存在-t
small, large = remove_v(sums, t)
if small is None :
return None
if t in sums:
t1 = solve(n-1, small)
if not t1 is None :
return [t] + t1
if -t in sums :
t1 = solve(n-1, large)
if not t1 is None :
return [-t] + t1
return None
return solve()
|
c376f3 | e803b6 | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
Note: Test cases are generated such that there will always be at least one correct answer.
Example 1:
Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Explanation: [1,2,-3] is able to achieve the given subset sums:
- []: sum is 0
- [1]: sum is 1
- [2]: sum is 2
- [1,2]: sum is 3
- [-3]: sum is -3
- [1,-3]: sum is -2
- [2,-3]: sum is -1
- [1,2,-3]: sum is 0
Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.
Example 2:
Input: n = 2, sums = [0,0,0,0]
Output: [0,0]
Explanation: The only correct answer is [0,0].
Example 3:
Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]
Output: [0,-1,4,5]
Explanation: [0,-1,4,5] is able to achieve the given subset sums.
Constraints:
1 <= n <= 15
sums.length == 2n
-10000 <= sums[i] <= 10000
| class Solution(object):
def recoverArray(self, n, sums):
"""
:type n: int
:type sums: List[int]
:rtype: List[int]
"""
sums, ans, m = sorted(sums), [], max(sums)
while len(sums) > 1:
i, left, right = 0, [], []
ans.append(sums[1] - sums[0])
for s in sums:
if len(right) > i and s == right[i]:
i += 1
else:
left.append(s)
right.append(s + sums[1] - sums[0])
sums = left
def dfs(i, a, t):
if i == len(a):
return t == 0
if dfs(i + 1, a, t - a[i]):
return True
a[i] = -a[i]
if dfs(i + 1, a, t):
return True
a[i] = -a[i]
return False
dfs(0, ans, m)
return ans |
a617b0 | 1851fa | There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.
A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.
The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.
Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
Example 2:
Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
Constraints:
1 <= n <= 2 * 10000
n - 1 <= edges.length <= 4 * 10000
edges[i].length == 3
1 <= ui, vi <= n
ui != vi
1 <= weighti <= 100000
There is at most one edge between any two nodes.
There is at least one path between any two nodes.
| class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
gra = defaultdict(dict)
for u, v, w in edges:
gra[u][v] = w
gra[v][u] = w
bfs = deque()
bfs.append((1, 0))
ans = 0
mod = 10 ** 9 + 7
visited = set()
visited.add(1)
heap =[(0,n)]
dist = {}
while heap:
time, u = heapq.heappop(heap)
if u not in dist:
dist[u]=time
for v in gra[u]:
heapq.heappush(heap, (time+gra[u][v],v))
@cache
def f(node, dis):
if node == n:
return 1
else:
ans = 0
for v in gra[node]:
if v not in visited and dist[v] < dis:
ans += f(v, dist[v])
return ans % ( 10 ** 9 + 7)
return f(1, dist[1])
|
d33d76 | 1851fa | There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.
A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.
The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.
Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
Example 2:
Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
Constraints:
1 <= n <= 2 * 10000
n - 1 <= edges.length <= 4 * 10000
edges[i].length == 3
1 <= ui, vi <= n
ui != vi
1 <= weighti <= 100000
There is at most one edge between any two nodes.
There is at least one path between any two nodes.
| from heapq import heappush, heappop
class Solution(object):
def countRestrictedPaths(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
adj = [[] for _ in xrange(n)]
for u, v, w in edges:
adj[u-1].append((v-1, w))
adj[v-1].append((u-1, w))
h = []
d = [float('inf')] * n
def _consider(u, du):
if d[u] <= du: return
d[u] = du
heappush(h, (du, u))
_consider(n-1, 0)
while h:
du, u = heappop(h)
for v, w in adj[u]: _consider(v, du + w)
mod = 10**9 + 7
ways = [0] * n
ways[n-1] = 1
for u in sorted(xrange(n), key=lambda i: d[i]):
for v, _ in adj[u]:
if d[v] < d[u]: ways[u] += ways[v]
ways[u] %= mod
return ways[0] |
0bc4d9 | 11800f | You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.
The happiness of each person is calculated as follows:
Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).
Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).
Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
Example 1:
Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
Output: 240
Explanation: Assume the grid is 1-indexed with coordinates (row, column).
We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).
- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120
- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
The grid happiness is 120 + 60 + 60 = 240.
The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
Example 2:
Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
Output: 260
Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).
- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80
- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
The grid happiness is 90 + 80 + 90 = 260.
Example 3:
Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
Output: 240
Constraints:
1 <= m, n <= 5
0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
| class Solution(object):
def getMaxGridHappiness(self, m, n, introvertsCount, extrovertsCount):
"""
:type m: int
:type n: int
:type introvertsCount: int
:type extrovertsCount: int
:rtype: int
"""
p, q = introvertsCount, extrovertsCount
if m < n: m, n = n, m
# col + counts = 11907 sx, 243 tx
def _dec(x):
r = []
for _ in xrange(n):
r.append(x%3)
x//=3
return tuple(r)
configs = []
for x in xrange(3**n):
a = _dec(x)
b = [0]*n
for i in xrange(n):
if a[i] == 0: continue
if i > 0: b[i-1] += 1
if i+1 < n: b[i+1] += 1
score = intro = extro = 0
for i in xrange(n):
if a[i] == 1:
score += 120 - 30 * b[i]
intro += 1
elif a[i] == 2:
score += 40 + 20 * b[i]
extro += 1
configs.append((x, intro, extro, score))
cross = [[0]*(3**n) for _ in xrange(3**n)]
for x in xrange(3**n):
a = _dec(x)
for y in xrange(3**n):
b = _dec(y)
for i in xrange(n):
if a[i] == 1 and b[i] == 1:
cross[x][y] -= 60
elif a[i] == 2 and b[i] == 2:
cross[x][y] += 40
elif a[i] + b[i] == 3:
cross[x][y] -= 10
f = Counter()
f[(0, introvertsCount, extrovertsCount)] = 0
for _ in xrange(m):
ff = Counter()
for (x, i, e), s in f.iteritems():
for xx, ii, ee, ss in configs:
if i-ii < 0 or e-ee < 0: continue
kk = (xx, i-ii, e-ee)
vv = s + ss + cross[x][xx]
ff[kk] = max(ff[kk], vv)
f = ff
return max(f.itervalues()) |
4909e3 | 11800f | You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.
The happiness of each person is calculated as follows:
Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).
Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).
Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
Example 1:
Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
Output: 240
Explanation: Assume the grid is 1-indexed with coordinates (row, column).
We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).
- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120
- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
The grid happiness is 120 + 60 + 60 = 240.
The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
Example 2:
Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
Output: 260
Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).
- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80
- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
The grid happiness is 90 + 80 + 90 = 260.
Example 3:
Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
Output: 240
Constraints:
1 <= m, n <= 5
0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
| class Solution:
def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:
state = [[{} for _ in range(n + 1)] for _ in range(n + 1)]
all_state = {}
def make(now, k, a):
if k == n:
c = collections.Counter(a)
state[c[1]][c[2]][now] = a
all_state[now] = a
return
for i in range(3):
make(now + (3 ** k) * i, k + 1, a + [i])
make(0, 0, [])
cost = {}
def calc(s, t):
if (s, t) not in cost:
ret = 0
a, b = all_state[s], all_state[t]
for i in range(n):
if a[i] == 1 and b[i] != 0:
ret -= 30
if a[i] == 2 and b[i] != 0:
ret += 20
if b[i] == 1:
ret += 120
if a[i] != 0:
ret -= 30
if i > 0 and b[i - 1] != 0:
ret -= 30
if i < n - 1 and b[i + 1] != 0:
ret -= 30
elif b[i] == 2:
ret += 40
if a[i] != 0:
ret += 20
if i > 0 and b[i - 1] != 0:
ret += 20
if i < n - 1 and b[i + 1] != 0:
ret += 20
cost[(s, t)] = ret
return cost[(s, t)]
f = [[[{} for _ in range(extrovertsCount + 1)] for _ in range(introvertsCount + 1)] for _ in range(m + 1)]
f[0][0][0][0] = 0
ret = 0
for i in range(m):
for j in range(introvertsCount + 1):
for k in range(extrovertsCount + 1):
for s in f[i][j][k]:
for jj in range(j, introvertsCount + 1):
if jj - j > n:
continue
for kk in range(k, extrovertsCount + 1):
if kk - k > n:
continue
for t in state[jj - j][kk - k]:
v = calc(s, t) + f[i][j][k][s]
if t not in f[i + 1][jj][kk] or f[i + 1][jj][kk][t] < v:
f[i + 1][jj][kk][t] = v
ret = max(v, ret)
return ret |
b7cbe4 | 561639 | You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.
For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.
Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7.
Note: The answer should be the minimum product before the modulo operation is done.
Example 1:
Input: p = 1
Output: 1
Explanation: nums = [1].
There is only one element, so the product equals that element.
Example 2:
Input: p = 2
Output: 6
Explanation: nums = [01, 10, 11].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 * 2 * 3 = 6 is already minimized.
Example 3:
Input: p = 3
Output: 1512
Explanation: nums = [001, 010, 011, 100, 101, 110, 111]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is [001, 110, 011, 100, 001, 110, 111].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is [001, 110, 001, 110, 001, 110, 111].
The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.
Constraints:
1 <= p <= 60
| class Solution:
def minNonZeroProduct(self, p: int) -> int:
def power(a, b):
if b == 0:
return 1
ret = power(a, b>>1)
ret = (ret*ret)%1000000007
if b&1:
ret = (ret*a)%1000000007
return ret
return (power(2**p-2, 2**(p-1)-1)*(2**p-1))%1000000007 |
871931 | 561639 | You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.
For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.
Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7.
Note: The answer should be the minimum product before the modulo operation is done.
Example 1:
Input: p = 1
Output: 1
Explanation: nums = [1].
There is only one element, so the product equals that element.
Example 2:
Input: p = 2
Output: 6
Explanation: nums = [01, 10, 11].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 * 2 * 3 = 6 is already minimized.
Example 3:
Input: p = 3
Output: 1512
Explanation: nums = [001, 010, 011, 100, 101, 110, 111]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is [001, 110, 011, 100, 001, 110, 111].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is [001, 110, 001, 110, 001, 110, 111].
The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.
Constraints:
1 <= p <= 60
| class Solution(object):
def minNonZeroProduct(self, p):
m=10**9+7
x=(1<<p)-1
y=pow(x-1,(x-1)//2,m)
return x*y%m |
2ce929 | ed4cc1 | There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:
the price needed to open the gate at node i, if amount[i] is negative, or,
the cash reward obtained on opening the gate at node i, otherwise.
The game goes on as follows:
Initially, Alice is at node 0 and Bob is at node bob.
At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.
For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
If the gate is already open, no price will be required, nor will there be any cash reward.
If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.
If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.
Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output: 6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output: -7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
2 <= n <= 100000
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= bob < n
amount.length == n
amount[i] is an even integer in the range [-10000, 10000].
| class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
path = defaultdict(list)
for u, v in edges:
path[u].append(v)
path[v].append(u)
father = [-1] * (len(edges) + 1)
note = [[] for _ in range(len(edges) + 1)]
q = deque([0])
while q:
p = q.popleft()
for newp in path[p]:
if father[newp] == -1 and newp != 0:
father[newp] = p
q.append(newp)
note[p].append(newp)
bob_path = [bob]
while father[bob_path[-1]] >= 0:
bob_path.append(father[bob_path[-1]])
x = set()
for i in bob_path[:len(bob_path) // 2]:
x.add(i)
tmp = set()
if len(bob_path) % 2:
tmp.add(bob_path[len(bob_path) // 2])
def getRes(idx):
if idx in x:
val = 0
elif idx in tmp:
val = amount[idx] // 2
else:
val = amount[idx]
if len(note[idx]) == 0:
return val
return max(getRes(i) for i in note[idx]) + val
return getRes(0) |
cc3aa8 | ed4cc1 | There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:
the price needed to open the gate at node i, if amount[i] is negative, or,
the cash reward obtained on opening the gate at node i, otherwise.
The game goes on as follows:
Initially, Alice is at node 0 and Bob is at node bob.
At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.
For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
If the gate is already open, no price will be required, nor will there be any cash reward.
If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.
If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.
Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output: 6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output: -7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
2 <= n <= 100000
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= bob < n
amount.length == n
amount[i] is an even integer in the range [-10000, 10000].
| class Solution(object):
def mostProfitablePath(self, edges, bob, amount):
"""
:type edges: List[List[int]]
:type bob: int
:type amount: List[int]
:rtype: int
"""
n = len(edges) + 1
neigh = [[] for _ in range(n)]
for [u,v] in edges:
neigh[v].append(u)
neigh[u].append(v)
children = [[] for _ in range(n)]
parent = [-2]*n
layer = [0]*n
accu = [0]*n
parent[0] = -1
accu[0] = amount[0]
queue = deque()
queue.append(0)
while queue:
index = queue.popleft()
for nextindex in neigh[index]:
if parent[nextindex] > -2: continue
queue.append(nextindex)
parent[nextindex] = index
children[index].append(nextindex)
layer[nextindex] = layer[index] + 1
if nextindex==bob:
curr = nextindex
orilayer = layer[curr]
while layer[curr] > orilayer // 2:
amount[curr] = 0
curr = parent[curr]
if layer[curr] * 2 == orilayer:
amount[curr] = amount[curr]// 2
# print amount
queue.append(0)
while queue:
index = queue.popleft()
for nextindex in children[index]:
accu[nextindex] = accu[index] + amount[nextindex]
queue.append(nextindex)
# print layer
# print accu
ans = -float('inf')
for i in range(n):
if len(children[i])==0: ans = max(ans, accu[i])
return ans
|
9f954e | aff3be | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.
Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: inventory = [2,5], orders = 4
Output: 14
Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
Example 2:
Input: inventory = [3,5], orders = 6
Output: 19
Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
Constraints:
1 <= inventory.length <= 100000
1 <= inventory[i] <= 10^9
1 <= orders <= min(sum(inventory[i]), 10^9)
| class Solution:
def maxProfit(self, a: List[int], orders: int) -> int:
mod = 10**9 + 7
l, r, ans = 0, max(a), -1
rest = sum(a) - orders
while l <= r:
mid = (l + r) // 2
cur = 0
for o in a:
cur += min(o, mid)
if cur <= rest:
ans = mid
l = mid + 1
else:
r = mid - 1
calc = lambda x: x * (x + 1) // 2
good = rest - sum(min(o, ans) for o in a)
value = 0
for o in a:
if o > ans:
value += calc(o)
if good:
value -= calc(ans + 1)
good -= 1
else:
value -= calc(ans)
return value % mod |
9ed623 | aff3be | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.
Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: inventory = [2,5], orders = 4
Output: 14
Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
Example 2:
Input: inventory = [3,5], orders = 6
Output: 19
Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
Constraints:
1 <= inventory.length <= 100000
1 <= inventory[i] <= 10^9
1 <= orders <= min(sum(inventory[i]), 10^9)
| class Solution(object):
def maxProfit(self, inventory, orders):
"""
:type inventory: List[int]
:type orders: int
:rtype: int
"""
arr = inventory
t = lambda x: x*(x+1)//2
sell_cnt = lambda x: sum(max(i-x,0) for i in arr)
sell_amt = lambda x: sum(max(t(i)-t(x),0) for i in arr)
n = orders
x, y = 0, max(arr)
while x + 1 < y:
z = (x + y) >> 1
if sell_cnt(z) >= orders: x = z
else: y = z
r = sell_amt(y)
r += y * (orders - sell_cnt(y))
return r % (10**9 + 7) |
c7008d | cc22eb | There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
Example 1:
Input: batchSize = 3, groups = [1,2,3,4,5,6]
Output: 4
Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.
Example 2:
Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]
Output: 4
Constraints:
1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 10^9
| class Solution(object):
def maxHappyGroups(self, batchSize, groups):
"""
:type batchSize: int
:type groups: List[int]
:rtype: int
"""
n = batchSize
gs = [c%n for c in groups]
cs = [0]*n
for c in gs:
cs[c]+=1
r = cs[0]
dp = {}
def dfs(s):
k=0
for v in cs[1:]:
k=(k<<5)+v
if k==0: return 0
k = (k<<4)+s
if k in dp: return dp[k]
r = 0
for i in range(1, n):
if cs[i]==0: continue
cs[i]-=1
t = dfs((s+i)%n)
if s==0: t+=1
if r<t: r=t
cs[i]+=1
dp[k]=r
return r
return r+dfs(0) |
ab03b7 | cc22eb | There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
Example 1:
Input: batchSize = 3, groups = [1,2,3,4,5,6]
Output: 4
Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.
Example 2:
Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]
Output: 4
Constraints:
1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 10^9
| class Solution:
def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:
mods = [0 for _ in range(10)]
for g in groups:
mods[g % batchSize] += 1
@functools.lru_cache(maxsize=None)
def h(mods, currmod):
if sum(mods) == 0:
return 0
result = 0
if currmod == 0:
result += 1
best = 0
for i in range(10):
if mods[i]:
new_mods = tuple(mods[j] if j != i else mods[j] - 1 for j in range(10))
best = max(best, h(new_mods, (currmod + i) % batchSize))
return best + result
return h(tuple(mods), 0) |
fd9b56 | dc4f41 | Given an integer array nums sorted in non-decreasing order and an integer k, return true if this array can be divided into one or more disjoint increasing subsequences of length at least k, or false otherwise.
Example 1:
Input: nums = [1,2,2,3,3,4,4], k = 3
Output: true
Explanation: The array can be divided into two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
Example 2:
Input: nums = [5,6,6,7,8], k = 3
Output: false
Explanation: There is no way to divide the array using the conditions required.
Constraints:
1 <= k <= nums.length <= 100000
1 <= nums[i] <= 100000
nums is sorted in non-decreasing order.
|
class Solution:
def canDivideIntoSubsequences(self, nums: List[int], K: int) -> bool:
cnts = collections.Counter(nums)
M = max(cnts.values())
return len(nums) >= M * K
|
02da58 | dc4f41 | Given an integer array nums sorted in non-decreasing order and an integer k, return true if this array can be divided into one or more disjoint increasing subsequences of length at least k, or false otherwise.
Example 1:
Input: nums = [1,2,2,3,3,4,4], k = 3
Output: true
Explanation: The array can be divided into two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
Example 2:
Input: nums = [5,6,6,7,8], k = 3
Output: false
Explanation: There is no way to divide the array using the conditions required.
Constraints:
1 <= k <= nums.length <= 100000
1 <= nums[i] <= 100000
nums is sorted in non-decreasing order.
| class Solution(object):
def canDivideIntoSubsequences(self, A, K):
"""
:type nums: List[int]
:type K: int
:rtype: bool
"""
count = collections.Counter(A)
groups = max(count.values())
return len(A) >= K * groups
|
c6a2d5 | 9fdcdd | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
if root==None: return 0
def good(root: TreeNode,mm:int) -> int:
if root==None: return 0
if root.val>=mm:
x = good(root.left,root.val)
y = good(root.right,root.val)
return x+y+1
else:
x = good(root.left,mm)
y = good(root.right,mm)
return x+y
x = good(root.left,root.val)
y = good(root.right,root.val)
return x+y+1
|
20fa08 | 9fdcdd | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
| # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def goodNodes(self, root,x=-10001):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
if root.val>=x: return self.goodNodes(root.left,root.val)+self.goodNodes(root.right,root.val)+1
return self.goodNodes(root.left,x)+self.goodNodes(root.right,x) |
1485c7 | eda2c2 | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
Example 1:
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10000
1 <= x <= 10^9
| class Solution(object):
def minOperations(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
if x == 0:
return 0
n = len(nums)
lhs = {0: 0}
lhs_cnt = lhs_sum = 0
rhs_cnt = rhs_sum = 0
for v in nums:
lhs_cnt += 1
lhs_sum += v
if lhs_sum not in lhs:
lhs[lhs_sum] = lhs_cnt
r = lhs.get(x, n + 1)
for v in reversed(nums):
rhs_cnt += 1
rhs_sum += v
if x - rhs_sum in lhs:
r = min(r, rhs_cnt + lhs[x - rhs_sum])
return r if r <= n else -1 |
2f70b0 | eda2c2 | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
Example 1:
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10000
1 <= x <= 10^9
| class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
tot = sum(nums)
if tot < x:
return -1
if tot == x:
return len(nums)
n = len(nums)
ret = 10 ** 9
a = [nums[0]]
for i in range(1, n):
a.append(a[-1] + nums[i])
b = [nums[-1]] * n
for i in range(n - 2, -1, -1):
b[i] = b[i + 1] + nums[i]
for i in range(n):
if a[i] == x:
ret = min(ret, i + 1)
if b[i] == x:
ret = min(ret, n - i)
j = 0
while j < n and b[j] > x:
j += 1
if j < n and b[j] == x:
ret = min(ret, n - j)
for i in range(n):
while j < i:
j += 1
while j < n and a[i] + b[j] > x:
j += 1
if j < n and a[i] + b[j] == x:
ret = min(i + 1 + n - j, ret)
if ret > n:
return -1
return ret |
1a5e89 | b8e53b | You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where:
The left node has the value 2 * val, and
The right node has the value 2 * val + 1.
You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem:
Add an edge between the nodes with values ai and bi.
Find the length of the cycle in the graph.
Remove the added edge between nodes with values ai and bi.
Note that:
A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once.
The length of a cycle is the number of edges visited in the cycle.
There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return an array answer of length m where answer[i] is the answer to the ith query.
Example 1:
Input: n = 3, queries = [[5,3],[4,7],[2,3]]
Output: [4,5,3]
Explanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes [5,2,1,3]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes [4,2,1,3,7]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes [2,1,3]. Thus answer to the third query is 3. We delete the added edge.
Example 2:
Input: n = 2, queries = [[1,2]]
Output: [2]
Explanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes [2,1]. Thus answer for the first query is 2. We delete the added edge.
Constraints:
2 <= n <= 30
m == queries.length
1 <= m <= 100000
queries[i].length == 2
1 <= ai, bi <= 2n - 1
ai != bi
| import sys
sys.setrecursionlimit(10 ** 9)
"""
// END NO SAD
// REMEMBER CLEAR GLOBAL STATE
// REMEMBER READ THE PROBLEM STATEMENT AND DON'T SOLVE A DIFFERENT PROBLEM
// REMEMBER LOOK FOR RANDOM UNINTUITIVE DETAILS IN THE PROBLEM
// remember hidden T factor of 1e2
// read the bounds for stupid cases
// did you restart your editor
// pushing back vectors is garbage, preinitialize them
// function calls are not free
// unordered naive is faster than lb vector standard
"""
class Solution:
def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
ret = []
for x, y in queries:
ans = 1
while x != y:
if x > y:
x //= 2
else:
y //= 2
ans += 1
ret.append(ans)
return ret |
c9de5f | b8e53b | You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where:
The left node has the value 2 * val, and
The right node has the value 2 * val + 1.
You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem:
Add an edge between the nodes with values ai and bi.
Find the length of the cycle in the graph.
Remove the added edge between nodes with values ai and bi.
Note that:
A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once.
The length of a cycle is the number of edges visited in the cycle.
There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return an array answer of length m where answer[i] is the answer to the ith query.
Example 1:
Input: n = 3, queries = [[5,3],[4,7],[2,3]]
Output: [4,5,3]
Explanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes [5,2,1,3]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes [4,2,1,3,7]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes [2,1,3]. Thus answer to the third query is 3. We delete the added edge.
Example 2:
Input: n = 2, queries = [[1,2]]
Output: [2]
Explanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes [2,1]. Thus answer for the first query is 2. We delete the added edge.
Constraints:
2 <= n <= 30
m == queries.length
1 <= m <= 100000
queries[i].length == 2
1 <= ai, bi <= 2n - 1
ai != bi
| class Solution(object):
def cycleLengthQueries(self, n, queries):
"""
:type n: int
:type queries: List[List[int]]
:rtype: List[int]
"""
def g(n):
r = []
while n > 0:
r.append(n)
n /= 2
return r
r = [0] * len(queries)
for i in range(len(queries)):
p, q, s, t = g(queries[i][0]), g(queries[i][1]), len(g(queries[i][0])) - 1, len(g(queries[i][1])) - 1
while s >= 0 and t >= 0 and p[s] == q[t]:
s, t = s - 1, t - 1
r[i] = s + t + 3
return r |
7863bb | acab93 | Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.
The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.
Example 1:
Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.
Example 2:
Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
Explanation:
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
Example 3:
Input: sentence = ["i","had","apple","pie"], rows = 4, cols = 5
Output: 1
Explanation:
i-had
apple
pie-i
had--
The character '-' signifies an empty space on the screen.
Constraints:
1 <= sentence.length <= 100
1 <= sentence[i].length <= 10
sentence[i] consists of lowercase English letters.
1 <= rows, cols <= 2 * 10000
| class Solution(object):
def wordsTyping(self, sentence, rows, cols):
"""
:type sentence: List[str]
:type rows: int
:type cols: int
:rtype: int
"""
s = 0
for word in sentence:
if len(word) > cols:
return 0
s += len(word)
s += 1
x = 0
y = -1
n = rows
m = cols
res = 0
while True:
if m - y >= s:
res += (m - y) / s
y += (m - y) / s * s
for word in sentence:
if m - y >= len(word) + 1 or (y <= 0 and m - y >= len(word)):
y += len(word) + (y != 0)
# print x, y
else:
x += 1
y = len(word)
# print x, y
if x < n:
res += 1
else:
break
return res
print Solution().wordsTyping(["a", "bcd", "e"], 3, 6) |
32ec1a | 6c4b20 | You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.
Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.
Example 1:
Input: message = "this is really a very awesome message", limit = 9
Output: ["thi<1/14>","s i<2/14>","s r<3/14>","eal<4/14>","ly <5/14>","a v<6/14>","ery<7/14>"," aw<8/14>","eso<9/14>","me<10/14>"," m<11/14>","es<12/14>","sa<13/14>","ge<14/14>"]
Explanation:
The first 9 parts take 3 characters each from the beginning of message.
The next 5 parts take 2 characters each to finish splitting message.
In this example, each part, including the last, has length 9.
It can be shown it is not possible to split message into less than 14 parts.
Example 2:
Input: message = "short message", limit = 15
Output: ["short mess<1/2>","age<2/2>"]
Explanation:
Under the given constraints, the string can be split into two parts:
- The first part comprises of the first 10 characters, and has a length 15.
- The next part comprises of the last 3 characters, and has a length 8.
Constraints:
1 <= message.length <= 10000
message consists only of lowercase English letters and ' '.
1 <= limit <= 10000
| class Solution:
def splitMessage(self, message: str, limit: int) -> List[str]:
if len(message) + 5 <= limit:
return [message + '<1/1>']
note, v = 1, 0
while True:
note *= 10
v += 1
tmp = note - 1
length = 1
cnt = 0
if 2 * v + 3 > limit: return []
while length <= v:
cnt += (limit - length - 3 - v) * 9 * pow(10, length - 1)
length += 1
if cnt >= len(message):
break
ans = []
for char in message:
if len(ans) == 0 or len(ans[-1]) + len(str(len(ans))) + 3 + v == limit:
ans.append('')
ans[-1] += char
return [x + f'<{idx}/{len(ans)}>' for idx, x in enumerate(ans, 1)] |
640eb7 | 6c4b20 | You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.
Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.
Example 1:
Input: message = "this is really a very awesome message", limit = 9
Output: ["thi<1/14>","s i<2/14>","s r<3/14>","eal<4/14>","ly <5/14>","a v<6/14>","ery<7/14>"," aw<8/14>","eso<9/14>","me<10/14>"," m<11/14>","es<12/14>","sa<13/14>","ge<14/14>"]
Explanation:
The first 9 parts take 3 characters each from the beginning of message.
The next 5 parts take 2 characters each to finish splitting message.
In this example, each part, including the last, has length 9.
It can be shown it is not possible to split message into less than 14 parts.
Example 2:
Input: message = "short message", limit = 15
Output: ["short mess<1/2>","age<2/2>"]
Explanation:
Under the given constraints, the string can be split into two parts:
- The first part comprises of the first 10 characters, and has a length 15.
- The next part comprises of the last 3 characters, and has a length 8.
Constraints:
1 <= message.length <= 10000
message consists only of lowercase English letters and ' '.
1 <= limit <= 10000
| class Solution(object):
def splitMessage(self, message, limit):
L=len(message)
i=int(L/(limit-3))
sumtoi=sum([len(str(j)) for j in range(1,i+1)])
while limit*i<L+3*i+len(str(i))*i+sumtoi:
i+=1
sumtoi+=len(str(i))
if 3+2*len(str(i))>=limit:
return []
ar=[]
for j in range(1,i+1):
ar.append("{}<{}/{}>".format(message[:limit-(3+len(str(j))+len(str(i)))],j,i))
message=message[limit-(3+len(str(j))+len(str(i))):]
return ar
|
ca8a3c | ad5d79 | Given an integer array nums containing n integers, find the beauty of each subarray of size k.
The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers.
Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,-1,-3,-2,3], k = 3, x = 2
Output: [-1,-2,-2]
Explanation: There are 3 subarrays with size k = 3.
The first subarray is [1, -1, -3] and the 2nd smallest negative integer is -1.
The second subarray is [-1, -3, -2] and the 2nd smallest negative integer is -2.
The third subarray is [-3, -2, 3] and the 2nd smallest negative integer is -2.
Example 2:
Input: nums = [-1,-2,-3,-4,-5], k = 2, x = 2
Output: [-1,-2,-3,-4]
Explanation: There are 4 subarrays with size k = 2.
For [-1, -2], the 2nd smallest negative integer is -1.
For [-2, -3], the 2nd smallest negative integer is -2.
For [-3, -4], the 2nd smallest negative integer is -3.
For [-4, -5], the 2nd smallest negative integer is -4.
Example 3:
Input: nums = [-3,1,2,-3,0,-3], k = 2, x = 1
Output: [-3,0,-3,-3,-3]
Explanation: There are 5 subarrays with size k = 2.
For [-3, 1], the 1st smallest negative integer is -3.
For [1, 2], there is no negative integer so the beauty is 0.
For [2, -3], the 1st smallest negative integer is -3.
For [-3, 0], the 1st smallest negative integer is -3.
For [0, -3], the 1st smallest negative integer is -3.
Constraints:
n == nums.length
1 <= n <= 10^5
1 <= k <= n
1 <= x <= k
-50 <= nums[i] <= 50
| class Solution:
def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]:
sh = 50
count = [0] * (2 * sh + 1)
def f():
s = 0
for i in range(sh):
s += count[i]
if s >= x:
return i - sh
return 0
res = []
for i in range(k):
count[nums[i] + sh] += 1
res.append(f())
for i in range(k, len(nums)):
count[nums[i] + sh] += 1
count[nums[i - k] + sh] -= 1
res.append(f())
return res |
cfa379 | ad5d79 | Given an integer array nums containing n integers, find the beauty of each subarray of size k.
The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers.
Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,-1,-3,-2,3], k = 3, x = 2
Output: [-1,-2,-2]
Explanation: There are 3 subarrays with size k = 3.
The first subarray is [1, -1, -3] and the 2nd smallest negative integer is -1.
The second subarray is [-1, -3, -2] and the 2nd smallest negative integer is -2.
The third subarray is [-3, -2, 3] and the 2nd smallest negative integer is -2.
Example 2:
Input: nums = [-1,-2,-3,-4,-5], k = 2, x = 2
Output: [-1,-2,-3,-4]
Explanation: There are 4 subarrays with size k = 2.
For [-1, -2], the 2nd smallest negative integer is -1.
For [-2, -3], the 2nd smallest negative integer is -2.
For [-3, -4], the 2nd smallest negative integer is -3.
For [-4, -5], the 2nd smallest negative integer is -4.
Example 3:
Input: nums = [-3,1,2,-3,0,-3], k = 2, x = 1
Output: [-3,0,-3,-3,-3]
Explanation: There are 5 subarrays with size k = 2.
For [-3, 1], the 1st smallest negative integer is -3.
For [1, 2], there is no negative integer so the beauty is 0.
For [2, -3], the 1st smallest negative integer is -3.
For [-3, 0], the 1st smallest negative integer is -3.
For [0, -3], the 1st smallest negative integer is -3.
Constraints:
n == nums.length
1 <= n <= 10^5
1 <= k <= n
1 <= x <= k
-50 <= nums[i] <= 50
| class Solution(object):
def getSubarrayBeauty(self, nums, k, x):
"""
:type nums: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
f, a = [0] * 201, [0] * (len(nums) - k + 1)
for i in range(len(nums)):
f[nums[i] + 100] += 1
if i >= k - 1:
c = 0
for j in range(100):
c += f[j]
if c >= x:
a[i - k + 1] = j - 100
break
f[nums[i - k + 1] + 100] -= 1
return a |
222411 | d3d188 | Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.
Example 1:
Input: nums = [1,0,1,1,0]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
Constraints:
1 <= nums.length <= 100000
nums[i] is either 0 or 1.
| class Solution(object):
def findMaxConsecutiveOnes(self, nums):
if not nums:
return 0
if all(nums):
return len(nums)
if not any(nums):
return 1
items = []
nums.append(0)
n = len(nums)
l, r = -1, -1
for i in xrange(n):
cur = nums[i]
if cur == 0:
if l != r:
items.append((l, r))
l = r = i + 1
else:
if l == -1 and r == -1:
l = i
r = i + 1
m = len(items)
ans = items[0][1] - items[0][0] + 1
for i in xrange(m - 1):
a, b = items[i], items[i + 1]
if a[1] + 1 == b[0]:
ans = max(ans, b[1] - a[0])
ans = max(ans, a[1] - a[0] + 1, b[1] - b[0] + 1)
return ans
assert Solution().findMaxConsecutiveOnes([1,0,1,1,0,1]) == 4
assert Solution().findMaxConsecutiveOnes([1,1,1,1,0,1]) == 6
assert Solution().findMaxConsecutiveOnes([0,0,1,1,0,1]) == 4
assert Solution().findMaxConsecutiveOnes([0,0,1,0,0,1]) == 2
assert Solution().findMaxConsecutiveOnes([0,0,1]) == 2
assert Solution().findMaxConsecutiveOnes([]) == 0
assert Solution().findMaxConsecutiveOnes([0,0]) == 1
assert Solution().findMaxConsecutiveOnes([0,1]) == 2
assert Solution().findMaxConsecutiveOnes([1,1]) == 2
|
8bb8ba | c63ed3 | You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 100000
1 <= queries.length <= 100000
intervals[i].length == 2
1 <= lefti <= righti <= 10^7
1 <= queries[j] <= 10^7
| from sortedcontainers import SortedList
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
n = len(intervals)
m = len(queries)
# [left, right]
# size of the smallest interval which covers queries[j] (some point)
# offline queries, dynamic oracle
# onload and offload sizes from the pool
# you can used sortedlist, yes
ret = [-1] * m
# onload and offload events
# onload at left
# offload and right+1
onloads = []
offloads = []
for left,right in intervals:
sz = right-left+1
onloads.append([left, sz])
offloads.append([right+1, sz])
onloads = deque(sorted(onloads))
offloads = deque(sorted(offloads))
pool = SortedList()
for i,point in sorted(enumerate(queries), key=lambda en:en[1]):
while onloads and onloads[0][0] <= point:
pool.add(onloads.popleft()[1])
while offloads and offloads[0][0] <= point:
pool.remove(offloads.popleft()[1])
if pool:
ret[i] = pool[0]
return ret
|
511646 | c63ed3 | You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 100000
1 <= queries.length <= 100000
intervals[i].length == 2
1 <= lefti <= righti <= 10^7
1 <= queries[j] <= 10^7
| from heapq import heappush, heappop
class MinHeapRem:
def __init__(self):
self._h = []
def insert(self, val):
heappush(self._h, (val, 1))
def remove(self, val):
heappush(self._h, (val, -1))
def top(self):
h = self._h
k = 0
while h and (k < 0 or h[0][1] < 0):
k += heappop(h)[1]
return h[0][0] if h else -1
class Solution(object):
def minInterval(self, intervals, queries):
"""
:type intervals: List[List[int]]
:type queries: List[int]
:rtype: List[int]
"""
evt = []
for start, end in intervals:
size = 1 + end - start
evt.append((start, -1, size))
evt.append((end, 1, size))
for idx, query in enumerate(queries):
evt.append((query, 0, idx))
evt.sort()
h = MinHeapRem()
ans = [-1] * len(queries)
for _, typ, dat in evt:
if typ == -1:
h.insert(dat)
elif typ == 1:
h.remove(dat)
else:
ans[dat] = h.top()
return ans |
b3febb | 6d1abd | You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.
You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.
Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.
A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.
Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.
Note: If uj and vj are already direct friends, the request is still successful.
Example 1:
Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]
Output: [true,false]
Explanation:
Request 0: Person 0 and person 2 can be friends, so they become direct friends.
Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).
Example 2:
Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]
Output: [true,false]
Explanation:
Request 0: Person 1 and person 2 can be friends, so they become direct friends.
Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).
Example 3:
Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]
Output: [true,false,true,false]
Explanation:
Request 0: Person 0 and person 4 can be friends, so they become direct friends.
Request 1: Person 1 and person 2 cannot be friends since they are directly restricted.
Request 2: Person 3 and person 1 can be friends, so they become direct friends.
Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).
Constraints:
2 <= n <= 1000
0 <= restrictions.length <= 1000
restrictions[i].length == 2
0 <= xi, yi <= n - 1
xi != yi
1 <= requests.length <= 1000
requests[j].length == 2
0 <= uj, vj <= n - 1
uj != vj
| class Solution(object):
def friendRequests(self, n, restrictions, requests):
"""
:type n: int
:type restrictions: List[List[int]]
:type requests: List[List[int]]
:rtype: List[bool]
"""
ufp = [-1] * n
ufr = [0] * n
def _find(u):
p = []
while ufp[u] >= 0:
p.append(u)
u = ufp[u]
for v in p:
ufp[v] = u
return u
def _union(u, v):
u = _find(u)
v = _find(v)
if u == v:
return
if ufr[u] < ufr[v]:
u, v = v, u
ufp[v] = u
if ufr[u] == ufr[v]:
ufr[u] += 1
def _check(u, v):
u = _find(u)
v = _find(v)
if u == v:
return True
for x, y in restrictions:
x = _find(x)
y = _find(y)
assert x != y
if x == u and y == v:
return False
if x == v and y == u:
return False
return True
r = []
for u, v in requests:
u = _find(u)
v = _find(v)
if _check(u, v):
r.append(True)
_union(u, v)
else:
r.append(False)
return r |
d76d6b | 6d1abd | You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.
You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.
Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.
A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.
Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.
Note: If uj and vj are already direct friends, the request is still successful.
Example 1:
Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]
Output: [true,false]
Explanation:
Request 0: Person 0 and person 2 can be friends, so they become direct friends.
Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).
Example 2:
Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]
Output: [true,false]
Explanation:
Request 0: Person 1 and person 2 can be friends, so they become direct friends.
Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).
Example 3:
Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]
Output: [true,false,true,false]
Explanation:
Request 0: Person 0 and person 4 can be friends, so they become direct friends.
Request 1: Person 1 and person 2 cannot be friends since they are directly restricted.
Request 2: Person 3 and person 1 can be friends, so they become direct friends.
Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).
Constraints:
2 <= n <= 1000
0 <= restrictions.length <= 1000
restrictions[i].length == 2
0 <= xi, yi <= n - 1
xi != yi
1 <= requests.length <= 1000
requests[j].length == 2
0 <= uj, vj <= n - 1
uj != vj
| class Union :
def __init__(self, n) :
self.fathers = {i:i for i in range(n)}
# self.size = {i:1 for i in range(n)}
def find(self, idt) :
while not self.fathers[self.fathers[idt]] == self.fathers[idt] :
self.fathers[idt] = self.fathers[self.fathers[idt]]
return self.fathers[idt]
# def get_size(self, idt) :
# return self.size[self.find(idt)]
def union(self, x, y) :
fx = self.find(x)
fy = self.find(y)
if fx == fy :
return
self.fathers[fx] = fy
# self.size[fy] += self.size[fx]
class Solution:
def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
res_set = set()
for a, b in restrictions :
res_set.add(tuple(sorted([a, b])))
union = Union(n)
to_ret = []
for a, b in requests :
a, b = sorted([union.find(a), union.find(b)])
if (a, b) in res_set :
to_ret.append(False)
continue
union.union(a, b)
res_set = set(tuple(sorted([union.find(a), union.find(b)])) for a, b in res_set)
to_ret.append(True)
# print(res_set)
return to_ret
|
6bdab4 | f871a0 | You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.
Example 1:
Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
Constraints:
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 10^8
| class Solution(object):
def makesquare(self, A):
"""
:type nums: List[int]
:rtype: bool
"""
if len(A) == 0: return False
if len(A) < 4: return False
T = sum(A)
if T%4: return False
T /= 4
if max(A) > T: return False
N = len(A)
A.sort()
memo = {}
def dp(mask, cur = T):
if (mask, cur) in memo: return memo[mask,cur]
if mask == 0: return True
if cur == 0: return dp(mask, T)
ans = False
for bit in xrange(N):
if mask & (1<<bit):
if A[bit] > cur: break
if dp(mask ^ (1<<bit), cur - A[bit]):
ans = True
break
memo[mask,cur] = ans
return ans
return dp(2**N - 1)
|
63b6e5 | 02e795 | A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
In the beginning, curOrder will be ["king"].
Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].
Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:
ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.
Example 1:
Input
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
Output
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
Explanation
ThroneInheritance t= new ThroneInheritance("king"); // order: king
t.birth("king", "andy"); // order: king > andy
t.birth("king", "bob"); // order: king > andy > bob
t.birth("king", "catherine"); // order: king > andy > bob > catherine
t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
Constraints:
1 <= kingName.length, parentName.length, childName.length, name.length <= 15
kingName, parentName, childName, and name consist of lowercase English letters only.
All arguments childName and kingName are distinct.
All name arguments of death will be passed to either the constructor or as childName to birth first.
For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
At most 100000 calls will be made to birth and death.
At most 10 calls will be made to getInheritanceOrder.
| class Node:
def __init__(self, name):
self.children = []
self.name = name
def add_children(self, name):
node = Node(name)
self.children.append(node)
return node
class ThroneInheritance:
def __init__(self, kingName: str):
self.root = Node(kingName)
self.dead = set()
self.lookup = dict()
self.lookup[kingName] = self.root
def birth(self, parentName: str, childName: str) -> None:
self.lookup[childName] = self.lookup[parentName].add_children(childName)
def death(self, name: str) -> None:
self.dead.add(name)
def getInheritanceOrder(self) -> List[str]:
results = []
def dfs(x):
nonlocal results
if x.name not in self.dead:
results.append(x.name)
for y in x.children:
dfs(y)
dfs(self.root)
return results
|
0cf59b | 02e795 | A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
In the beginning, curOrder will be ["king"].
Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].
Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:
ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.
Example 1:
Input
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
Output
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
Explanation
ThroneInheritance t= new ThroneInheritance("king"); // order: king
t.birth("king", "andy"); // order: king > andy
t.birth("king", "bob"); // order: king > andy > bob
t.birth("king", "catherine"); // order: king > andy > bob > catherine
t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
Constraints:
1 <= kingName.length, parentName.length, childName.length, name.length <= 15
kingName, parentName, childName, and name consist of lowercase English letters only.
All arguments childName and kingName are distinct.
All name arguments of death will be passed to either the constructor or as childName to birth first.
For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
At most 100000 calls will be made to birth and death.
At most 10 calls will be made to getInheritanceOrder.
| class TreeNode:
def __init__(self, name):
self.name = name
self.children = []
self.dead = False
class ThroneInheritance(object):
def __init__(self, kingName):
"""
:type kingName: str
"""
self.king = TreeNode(kingName)
self.find = {'king': self.king}
def birth(self, parentName, childName):
"""
:type parentName: str
:type childName: str
:rtype: None
"""
child = TreeNode(childName)
self.find[childName] = child
self.find[parentName].children.append(child)
def death(self, name):
"""
:type name: str
:rtype: None
"""
self.find[name].dead = True
def getInheritanceOrder(self):
"""
:rtype: List[str]
"""
ans = []
def _dfs(node):
if not node.dead: ans.append(node.name)
for c in node.children: _dfs(c)
_dfs(self.king)
return ans
# Your ThroneInheritance object will be instantiated and called as such:
# obj = ThroneInheritance(kingName)
# obj.birth(parentName,childName)
# obj.death(name)
# param_3 = obj.getInheritanceOrder() |
a5bf6b | eec5b3 | You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
The subsequence can contain leading zeroes.
The empty string is considered to be equal to 0.
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 = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= k <= 10^9
| class Solution:
def longestSubsequence(self, s: str, k: int) -> int:
ct = collections.Counter(s)
to_ret = ct['0']
vt = 0
n = 1
for c in s[::-1] :
c = int(c)
vt = vt + c * n
n = n * 2
if vt > k :
break
if c == 1 :
to_ret += 1
return to_ret
|
5e27ca | eec5b3 | You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
The subsequence can contain leading zeroes.
The empty string is considered to be equal to 0.
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 = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= k <= 10^9
| class Solution(object):
def longestSubsequence(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
c, p, d = 0, 1, 0
for i in range(len(s) - 1, -1, -1):
d, c, p = d + 1 if c + (ord(s[i]) - ord('0')) * p <= k else d, c + (ord(s[i]) - ord('0')) * p if c + (ord(s[i]) - ord('0')) * p <= k else c, p * 2
return d |
726883 | bb7692 | You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile.
In one move, you can perform either of the following:
If the pile is not empty, remove the topmost element of the pile.
If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.
You are also given an integer k, which denotes the total number of moves to be made.
Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.
Example 1:
Input: nums = [5,2,2,4,0,6], k = 4
Output: 5
Explanation:
One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:
- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].
- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].
- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].
- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].
Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.
Example 2:
Input: nums = [2], k = 1
Output: -1
Explanation:
In the first move, our only option is to pop the topmost element of the pile.
Since it is not possible to obtain a non-empty pile after one move, we return -1.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i], k <= 10^9
| class Solution:
def maximumTop(self, nums: List[int], k: int) -> int:
n = len(nums)
if n == 1 and k%2:
return -1
l = [(nums[i], i) for i in range(n)]
l.sort(reverse=True)
for val, pos in l:
if pos > k:
continue
if pos == k-1:
continue
return val
return -1
|
ed7e65 | bb7692 | You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile.
In one move, you can perform either of the following:
If the pile is not empty, remove the topmost element of the pile.
If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.
You are also given an integer k, which denotes the total number of moves to be made.
Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.
Example 1:
Input: nums = [5,2,2,4,0,6], k = 4
Output: 5
Explanation:
One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:
- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].
- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].
- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].
- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].
Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.
Example 2:
Input: nums = [2], k = 1
Output: -1
Explanation:
In the first move, our only option is to pop the topmost element of the pile.
Since it is not possible to obtain a non-empty pile after one move, we return -1.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i], k <= 10^9
| class Solution(object):
def maximumTop(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
a = nums
n = len(a)
if n == 1:
return [a[0], -1][k & 1]
if k <= 1:
return a[k]
if k > n:
return max(a)
ans = max(a[i] for i in xrange(k-1))
if k < n:
ans = max(ans, a[k])
return ans
|
d8093c | e58ebb | You are given a 0-indexed integer array nums.
We say that an integer x is expressible from nums if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums.
Return the minimum positive non-zero integer that is not expressible from nums.
Example 1:
Input: nums = [2,1]
Output: 4
Explanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
Example 2:
Input: nums = [5,3,2]
Output: 1
Explanation: We can show that 1 is the smallest number that is not expressible.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
| class Solution:
def minImpossibleOR(self, nums: List[int]) -> int:
tmp = set(nums)
ans = 1
while ans in tmp:
ans *= 2
return ans |
6687d7 | e58ebb | You are given a 0-indexed integer array nums.
We say that an integer x is expressible from nums if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums.
Return the minimum positive non-zero integer that is not expressible from nums.
Example 1:
Input: nums = [2,1]
Output: 4
Explanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
Example 2:
Input: nums = [5,3,2]
Output: 1
Explanation: We can show that 1 is the smallest number that is not expressible.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
| class Solution(object):
def minImpossibleOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
vs= set(nums)
v=1
while True:
if v not in nums:
return v
v<<=1
|
5426f9 | 5f32d8 | You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Example 1:
Input: nums = [2,3,1,4,0]
Output: 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4]
Output: 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i] < nums.length
| class Solution(object):
def bestRotation(self, A):
"""
:type A: List[int]
:rtype: int
"""
ks = [0 for _ in range(len(A) + 1)]
lst = [-1 for _ in range(len(A))]
for i, num in enumerate(A):
if num <= i:
if num <= 0:
pass
else:
a = 0
b = i - num
ks[a] +=1
ks[b + 1] -= 1
a = i + 1
b = len(A) - 1
ks[a] += 1
ks[b + 1] -= 1
else:
if num > len(A) - 1:
pass
else:
a = i + 1
b = len(A) - 1 - num + i + 1
ks[a] += 1
ks[b + 1] -= 1
maxnum = 0
curnum = 0
res = 0
for k in range(len(A)):
curnum += ks[k]
if curnum > maxnum:
curnum = maxnum
res = k
return res |
828ea3 | 5f32d8 | You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Example 1:
Input: nums = [2,3,1,4,0]
Output: 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4]
Output: 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
Constraints:
1 <= nums.length <= 100000
0 <= nums[i] < nums.length
| class Solution:
def bestRotation(self, A):
n = len(A)
yes = [0] * n
no = [0] * n
for i, num in enumerate(A):
if num <= i: # current yes
if i - num + 1 < n:
no[i - num + 1] += 1
else:
if num - 1 - i > 0:
no[n - (num - 1 - i)] += 1
if i + 1 < n:
yes[i + 1] += 1
highscore = score = sum(num <= i for i, num in enumerate(A))
pos = 0
for i in range(1, n):
score += yes[i] - no[i]
if score > highscore:
highscore = score
pos = i
return pos
|
335d68 | cbe436 | You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.
A set x is a subset of a set y if all elements of x are also elements of y.
Example 1:
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
Example 2:
Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0", "1"}, so the answer is 2.
Constraints:
1 <= strs.length <= 600
1 <= strs[i].length <= 100
strs[i] consists only of digits '0' and '1'.
1 <= m, n <= 100
| class Solution(object):
def findMaxForm(self, s, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
k = len(s)
if k == 0: return 0
a = [0] * (k+1)
b = [0] * (k+1)
for i in range(k):
a[i+1] = s[i].count('0')
b[i+1] = s[i].count('1')
f = [[0]*(n+1) for i in range(m+1)]
for t in range(1, k+1):
g = [[0]*(n+1) for i in range(m+1)]
for i in range(m+1):
for j in range(n+1):
g[i][j] = f[i][j]
if i >= a[t] and j >= b[t] and g[i][j] < f[i-a[t]][j-b[t]] + 1:
g[i][j] = f[i-a[t]][j-b[t]] + 1
f = g
return f[m][n]
|
b1817e | eae354 | You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white.
You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.
Return the maximum number of white tiles that can be covered by the carpet.
Example 1:
Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
Output: 9
Explanation: Place the carpet starting on tile 10.
It covers 9 white tiles, so we return 9.
Note that there may be other places where the carpet covers 9 white tiles.
It can be shown that the carpet cannot cover more than 9 white tiles.
Example 2:
Input: tiles = [[10,11],[1,1]], carpetLen = 2
Output: 2
Explanation: Place the carpet starting on tile 10.
It covers 2 white tiles, so we return 2.
Constraints:
1 <= tiles.length <= 5 * 10000
tiles[i].length == 2
1 <= li <= ri <= 10^9
1 <= carpetLen <= 10^9
The tiles are non-overlapping.
| class Solution:
def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:
tiles.sort()
res = 0
n = len(tiles)
j = 0
pc = 0
pp = 0
for i in range(n):
start = tiles[i][0]
pp -= pc
end = start + carpetLen - 1
cur = 0
while j < n and end >= tiles[j][1]:
pp += tiles[j][1] - tiles[j][0] + 1
j += 1
if j < n and end >= tiles[j][0]:
cur += end - tiles[j][0] + 1
cur += pp
res = max(res, cur)
pc = tiles[i][1] - tiles[i][0] + 1
return res
|
9c1157 | eae354 | You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white.
You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.
Return the maximum number of white tiles that can be covered by the carpet.
Example 1:
Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
Output: 9
Explanation: Place the carpet starting on tile 10.
It covers 9 white tiles, so we return 9.
Note that there may be other places where the carpet covers 9 white tiles.
It can be shown that the carpet cannot cover more than 9 white tiles.
Example 2:
Input: tiles = [[10,11],[1,1]], carpetLen = 2
Output: 2
Explanation: Place the carpet starting on tile 10.
It covers 2 white tiles, so we return 2.
Constraints:
1 <= tiles.length <= 5 * 10000
tiles[i].length == 2
1 <= li <= ri <= 10^9
1 <= carpetLen <= 10^9
The tiles are non-overlapping.
| class Solution(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
s = sorted(tiles)
rc = 0
i, n = 0, len(s)
ss = [0]*(n+1)
while i<n:
ss[i+1]=ss[i]+s[i][1]-s[i][0]+1
i+=1
i=0
while i<n:
l, r = s[i]
e=l+carpetLen
j, d = i, n-i
while d:
while True:
nj=j+d
if nj>=n: break
if e<=s[nj][0]: break
j=nj
d>>=1
c=ss[j]-ss[i]
c+=(min(e, s[j][1]+1)-s[j][0])
rc = max(rc, c)
i+=1
return rc |
a57831 | 94ad5b | The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
Explanation:
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1
1 [3 -1 -3] 5 3 6 7 -1
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6
Example 2:
Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
Constraints:
1 <= k <= nums.length <= 100000
-2^31 <= nums[i] <= 2^31 - 1
| import bisect
class Solution(object):
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
if not nums: return []
if k == 1: return map(float, nums)
res = []
window = []
for i in range(len(nums)):
bisect.insort(window, nums[i])
if i >= k - 1:
res.append(1.0 * (window[k / 2] + window[(k - 1) / 2]) / 2.0)
window.remove(nums[i - k + 1])
return res |
0f6269 | 1dba09 | You are given a 0-indexed array nums comprising of n non-negative integers.
In one operation, you must:
Choose an integer i such that 1 <= i < n and nums[i] > 0.
Decrease nums[i] by 1.
Increase nums[i - 1] by 1.
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length
2 <= n <= 100000
0 <= nums[i] <= 10^9
| class Solution(object):
def minimizeArrayValue(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s, r = 0, 0
for i in range(len(nums)):
s, r = s + nums[i], max((s + nums[i] + i) / (i + 1), r) if r < nums[i] else r
return r |
7482fa | 1dba09 | You are given a 0-indexed array nums comprising of n non-negative integers.
In one operation, you must:
Choose an integer i such that 1 <= i < n and nums[i] > 0.
Decrease nums[i] by 1.
Increase nums[i - 1] by 1.
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length
2 <= n <= 100000
0 <= nums[i] <= 10^9
| class Solution:
def minimizeArrayValue(self, nums: List[int]) -> int:
l,r = -int(1e10),int(1e10)
def check(target):
if nums[0] > target:
return False
owe = target - nums[0]
for i in nums[1:]:
if i > target:
diff = i - target
if owe < diff:
return False
owe-=diff
else:
owe += target - i
return True
while l<r:
mid = (l+r)//2
if check(mid):
r = mid
else:
l = mid+1
return l
|
d683a0 | 9ed587 | You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.
You are restricted with the following rules:
The division operator '/' represents real division, not integer division.
For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator.
For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed.
You cannot concatenate numbers together
For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid.
Return true if you can get such expression that evaluates to 24, and false otherwise.
Example 1:
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: cards = [1,2,1,2]
Output: false
Constraints:
cards.length == 4
1 <= cards[i] <= 9
| from fractions import Fraction
from operator import *
def dfs(a):
if len(a) == 1:
return a[0] == 24
op = [add, sub, mul, div]
n = len(a)
for i in xrange(n):
for j in xrange(n):
if i == j:
continue
for o in op:
if o == div and a[j] == 0:
continue
b = [a[k] for k in xrange(n) if k not in [i, j]]
b.append(o(a[i], a[j]))
if dfs(b):
return True
return False
class Solution(object):
def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
a = map(lambda x: Fraction(x, 1), nums)
return dfs(a)
|
67aac1 | 9ed587 | You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.
You are restricted with the following rules:
The division operator '/' represents real division, not integer division.
For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator.
For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed.
You cannot concatenate numbers together
For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid.
Return true if you can get such expression that evaluates to 24, and false otherwise.
Example 1:
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: cards = [1,2,1,2]
Output: false
Constraints:
cards.length == 4
1 <= cards[i] <= 9
| class Solution:
def judgePoint24(self, nums):
for index1 in range (0,4):
one=nums[index1]
for index2 in range (0,4):
if index1==index2:
continue
two=nums[index2]
for result1 in [one*two, one/two, one+two, one-two]:
for index3 in range (0,4):
if index1==index3 or index2==index3:
continue
three=nums[index3]
possible2=[result1*three,result1+three,result1-three,three-result1]
if(three!=0 and result1!=0):
possible2.append(result1/three)
possible2.append(three/result1)
for result2 in possible2:
for index4 in range (0,4):
if index1==index4 or index2==index4 or index3==index4:
continue
four=nums[index4]
possible3=[result2*four,result2+four,result2-four,four-result2]
if(four!=0 and result2!=0):
possible3.append(result2/four)
possible3.append(four/result2)
for result3 in possible3:
if(result3==24):
return True
for index3 in range (0,4):
if index1==index3 or index2==index3:
continue
three=nums[index3]
for index4 in range (0,4):
if index1==index4 or index2==index4 or index3==index4:
continue
four=nums[index4]
possible4=[three*four,three+four,three-four]
if(four!=0):
possible4.append(three/four)
for result2 in possible4:
if(result1*result2==24):
return True
return False |
51feae | eeadc8 | A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]
Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
Constraints:
1 <= s.length <= 100000
s consists of only digits and does not contain leading zeros.
1 <= k <= 10^9
| class Solution(object):
def numberOfArrays(self, s, K):
A = map(int, s)
N = len(A)
MOD = 10**9 + 7
AK = map(int, str(K))
dp = [0] * (N+1)
dp[N] = 1
for i in xrange(N-1, -1, -1):
if s[i] == '0': continue
for take in xrange(1, len(AK) + 1):
if i+take > N: break
d = int(s[i:i+take])
if 1 <= d <= K:
dp[i] += dp[i+take]
dp[i] %= MOD
return dp[0] |
91ff03 | eeadc8 | A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]
Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
Constraints:
1 <= s.length <= 100000
s consists of only digits and does not contain leading zeros.
1 <= k <= 10^9
| class Solution:
def numberOfArrays(self, s: str, k: int) -> int:
s = '0' + s
n = len(s)
mod = int(1e9 + 7)
f = [0] * n
f[0] = 1
for i in range(0, n - 1):
if s[i + 1] == '0':
continue
for j in range(10):
if i + 1 + j >= n:
break
if int(s[(i + 1):(i + j + 2)]) <= k:
f[i + j + 1] += f[i]
if f[i + j + 1] >= mod:
f[i + j + 1] -= mod
return f[-1] |
4da8d7 | 7740e7 | Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.
Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 10^9 + 7.
Example 1:
Input: n = 4, k = 2
Output: 5
Explanation: The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
Example 2:
Input: n = 3, k = 1
Output: 3
Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
Example 3:
Input: n = 30, k = 7
Output: 796297179
Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 10^9 + 7 gives us 796297179.
Constraints:
2 <= n <= 1000
1 <= k <= n-1
| class Solution(object):
def numberOfSets(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
dp = [[0]*(k+1) for i in range(n+1)]
psum = [[0]*(k+1) for i in range(n+1)]
for K in range(k+1):
for N in range(n):
if K == 0:
dp[N][K] = 1
psum[N][K] = N+1
continue
if N == 0:
continue
dp[N][K] = dp[N-1][K] + psum[N-1][K-1]
psum[N][K] = psum[N-1][K] + dp[N][K]
return dp[n-1][k]%1000000007
|
40c598 | 7740e7 | Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.
Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 10^9 + 7.
Example 1:
Input: n = 4, k = 2
Output: 5
Explanation: The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
Example 2:
Input: n = 3, k = 1
Output: 3
Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
Example 3:
Input: n = 30, k = 7
Output: 796297179
Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 10^9 + 7 gives us 796297179.
Constraints:
2 <= n <= 1000
1 <= k <= n-1
| class Solution:
def numberOfSets(self, n: int, k: int) -> int:
dp=[[1], [1,1], [1,2,1]]
while len(dp)<=n+k:
nn=len(dp[-1])
L=[1]
for i in range(nn-1):
L.append((dp[-1][i]+dp[-1][i+1])%(10**9+7))
L.append(1)
dp.append(L)
return dp[n+k-1][2*k] |
1d7e5e | d36527 | You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
0 <= num <= 10^8
| class Solution(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
ret = num
l = len(str(num))
for i in xrange(l):
for j in xrange(l):
a = list(str(num))
a[i], a[j] = a[j], a[i]
ret = max(ret, int(''.join(a)))
return ret
|
890bc1 | d36527 | You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
0 <= num <= 10^8
| class Solution:
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:
return 0
N = []
temp_num = num
while temp_num > 0:
N = [temp_num%10] + N
temp_num //= 10
S = sorted(N, reverse=True)
# print(S)
l = len(N)
for i in range(l):
if N[i] != S[i]:
break
# print(i)
if i == l-1:
return num
else:
# S[i] > N[i]
pointer = i
for j in range(i, l):
if N[j] == S[i]:
pointer = j
# final N
# print(i, pointer)
temp = N[i]
N[i] = N[pointer]
N[pointer] = temp
result = 0
for n in N:
result *= 10
result += n
return result
|
333849 | 6af6ee | You are given two positive integer arrays nums and target, of the same length.
In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:
set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the same.
Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.
Example 1:
Input: nums = [8,12,6], target = [2,14,10]
Output: 2
Explanation: It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = [10,12,4].
- Choose i = 1 and j = 2, nums = [10,14,2].
It can be shown that 2 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,5], target = [4,1,3]
Output: 1
Explanation: We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = [1,4,3].
Example 3:
Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0
Explanation: The array nums is already similiar to target.
Constraints:
n == nums.length == target.length
1 <= n <= 100000
1 <= nums[i], target[i] <= 1000000
It is possible to make nums similar to target.
| class Solution:
def makeSimilar(self, nums1: List[int], nums2: List[int]) -> int:
nums1_odd = sorted(i for i in nums1 if i % 2)
nums1_even = sorted(i for i in nums1 if i % 2 == 0)
nums2_odd = sorted(i for i in nums2 if i % 2)
nums2_even = sorted(i for i in nums2 if i % 2 == 0)
return (
sum(max(0, i - j) for i, j in zip(nums1_odd, nums2_odd))
+ sum(max(0, i - j) for i, j in zip(nums1_even, nums2_even))
) // 2 |
9944d1 | 6af6ee | You are given two positive integer arrays nums and target, of the same length.
In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:
set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the same.
Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.
Example 1:
Input: nums = [8,12,6], target = [2,14,10]
Output: 2
Explanation: It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = [10,12,4].
- Choose i = 1 and j = 2, nums = [10,14,2].
It can be shown that 2 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,5], target = [4,1,3]
Output: 1
Explanation: We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = [1,4,3].
Example 3:
Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0
Explanation: The array nums is already similiar to target.
Constraints:
n == nums.length == target.length
1 <= n <= 100000
1 <= nums[i], target[i] <= 1000000
It is possible to make nums similar to target.
| class Solution(object):
def makeSimilar(self, nums, target):
"""
:type nums: List[int]
:type target: List[int]
:rtype: int
"""
nums.sort()
target.sort()
e, o, f, p, r = [], [], [], [], 0
for n in nums:
o.append(n) if n % 2 else e.append(n)
for n in target:
p.append(n) if n % 2 else f.append(n)
for i in range(len(e)):
r += (e[i] - f[i]) / 2 if e[i] > f[i] else 0
for i in range(len(o)):
r += (o[i] - p[i]) / 2 if o[i] > p[i] else 0
return r |
103021 | 405795 | You are given two positive integer arrays nums1 and nums2, both of length n.
The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 10^9 + 7.
|x| is defined as:
x if x >= 0, or
-x if x < 0.
Example 1:
Input: nums1 = [1,7,5], nums2 = [2,3,5]
Output: 3
Explanation: There are two possible optimal solutions:
- Replace the second element with the first: [1,7,5] => [1,1,5], or
- Replace the second element with the third: [1,7,5] => [1,5,5].
Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
Example 2:
Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
Output: 0
Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
Example 3:
Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
Output: 20
Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 100000
1 <= nums1[i], nums2[i] <= 100000
| class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
total = sum(abs(x - y) for x, y in zip(nums1, nums2))
a = sorted(nums1)
best = 0
for x, y in zip(nums1, nums2):
cur = abs(x - y)
idx = bisect.bisect_left(a, y)
if idx < n:
best = max(best, cur - (a[idx] - y))
if idx > 0:
best = max(best, cur - (y - a[idx - 1]))
return (total - best) % (10**9 + 7) |
033574 | 415448 | In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ai < bi <= edges.length
ai != bi
There are no repeated edges.
The given graph is connected.
| class Solution(object):
class UnionFind(object):
def __init__(self, keys):
self.size = len(keys)
self.parent = {}
self.rank = {}
for n in keys:
self.parent[n] = n
self.rank[n] = 0
def find(self, i):
if self.parent[i] != self.parent[self.parent[i]]:
self.parent[i] = self.find(self.parent[i])
return self.parent[i]
def union(self, i, j):
i_root = self.find(i)
j_root = self.find(j)
if i_root == j_root:
return
if self.rank[i_root] > self.rank[j_root]:
self.parent[j_root] = i_root
elif self.rank[i_root] < self.rank[j_root]:
self.parent[i_root] = j_root
else:
self.parent[i_root] = j_root
self.rank[j_root] += 1
def count(self):
return len(set(self.find(i) for i in range(self.size)))
def findRedundantConnection(self, edges):
to_remove = []
all_node = set()
for e in edges:
all_node.add(e[0])
all_node.add(e[1])
uf = self.UnionFind(all_node)
for e in edges:
start = e[0]
end = e[1]
if uf.find(start) != uf.find(end):
uf.union(start, end)
else:
to_remove.append(e)
return to_remove[-1] |
91e0a6 | 415448 | In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ai < bi <= edges.length
ai != bi
There are no repeated edges.
The given graph is connected.
| def find(a,n):
while a[n]!=n:
n=a[n]
return n
class Solution:
def findRedundantConnection(self, edges):
a=[]
for i in range(2001):
a.append(i)
for edge in edges:
s1=find(a,edge[0])
s2=find(a,edge[1])
if s1==s2:
return edge
else:
a[s2]=s1
"""
:type edges: List[List[int]]
:rtype: List[int]
""" |
0c9779 | 3cf653 | You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].
For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
You may choose to apply the mentioned operation once or not do anything.
The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr.
Return the maximum possible score.
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Example 1:
Input: nums1 = [60,60,60], nums2 = [10,90,10]
Output: 210
Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].
The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.
Example 2:
Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]
Output: 220
Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].
The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.
Example 3:
Input: nums1 = [7,11,13], nums2 = [1,1,1]
Output: 31
Explanation: We choose not to swap any subarray.
The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 100000
1 <= nums1[i], nums2[i] <= 10000
| class Solution:
def maximumsSplicedArray(self, a: List[int], b: List[int]) -> int:
n = len(a)
def gao(a, b):
t = sum(a)
c = [b[i] - a[i] for i in range(n)]
z = 0
f = 0
for i in c:
f = max(f, 0) + i
z = max(z, f)
z += t
return z
return max(gao(a, b), gao(b, a)) |
912b18 | 3cf653 | You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].
For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
You may choose to apply the mentioned operation once or not do anything.
The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr.
Return the maximum possible score.
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Example 1:
Input: nums1 = [60,60,60], nums2 = [10,90,10]
Output: 210
Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].
The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.
Example 2:
Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]
Output: 220
Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].
The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.
Example 3:
Input: nums1 = [7,11,13], nums2 = [1,1,1]
Output: 31
Explanation: We choose not to swap any subarray.
The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 100000
1 <= nums1[i], nums2[i] <= 10000
| class Solution(object):
def maximumsSplicedArray(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
def m(n, o):
s, p, c = 0, -float('inf'), 0
for i in range(len(n)):
s, p, c = s + n[i], max(p, c + o[i] - n[i]), max(c + o[i] - n[i], 0)
return s + p
return max(m(nums1, nums2), m(nums2, nums1)) |
1ff91b | 2a1d74 | There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
Example 1:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation: The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Example 2:
Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Explanation: Increasing the height of any building will result in the skyline changing.
Constraints:
n == grid.length
n == grid[r].length
2 <= n <= 50
0 <= grid[r][c] <= 100
| class Solution(object):
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
lst1 = [0 for _ in range(len(grid))]
lst2 = [0 for _ in range(len(grid[0]))]
for i in range(len(grid)):
for j in range(len(grid[0])):
lst1[i] = max(lst1[i], grid[i][j])
lst2[j] = max(lst2[j], grid[i][j])
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
res += min(lst1[i], lst2[j]) - grid[i][j]
return res |
284828 | 2a1d74 | There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
Example 1:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation: The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Example 2:
Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Explanation: Increasing the height of any building will result in the skyline changing.
Constraints:
n == grid.length
n == grid[r].length
2 <= n <= 50
0 <= grid[r][c] <= 100
| class Solution:
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n=len(grid)
m=len(grid[0])
row=[0]*n
col=[0]*m
for i in range(n):
for j in range(m):
row[i]=max(row[i],grid[i][j])
col[j]=max(col[j],grid[i][j])
ans=0
for i in range(n):
for j in range(m):
ans+=min(row[i],col[j])-grid[i][j]
return ans |
50bf92 | 861a8b | You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:
Input: nums = [3,9,7,3]
Output: 2
Explanation: One optimal partition is: [3,9] and [7,3].
The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36]
Output: 72
Explanation: One optimal partition is: [-36] and [36].
The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:
Input: nums = [2,-1,0,4,-2,-9]
Output: 0
Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15
nums.length == 2 * n
-10^7 <= nums[i] <= 10^7
| class Solution:
def minimumDifference(self, nums: List[int]) -> int:
def popcnt(a):
return bin(a).count("1")
def allsum(aa):
n = len(aa)
res = [[] for _ in range(n+1)]
res[0].append(0)
ss = [0]*(1 << n)
for s in range(1, 1 << n):
i = s.bit_length()-1
ss[s] = ss[s ^ 1 << i]+aa[i]
c = popcnt(s)
res[c].append(ss[s])
return res
n = len(nums)//2
s = sum(nums)
pre = allsum(nums[:n])
pos = allsum(nums[n:])
ans = 10**9
for i, aa in enumerate(pre):
bb = pos[n-i]
aa.sort()
bb.sort()
j = len(bb)-1
for a in aa:
while j >= 0 and (a+bb[j])*2 > s: j -= 1
if j < 0: break
cur = s-(a+bb[j])*2
if cur < ans: ans = cur
return ans
|
01138d | 861a8b | You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:
Input: nums = [3,9,7,3]
Output: 2
Explanation: One optimal partition is: [3,9] and [7,3].
The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36]
Output: 72
Explanation: One optimal partition is: [-36] and [36].
The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:
Input: nums = [2,-1,0,4,-2,-9]
Output: 0
Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15
nums.length == 2 * n
-10^7 <= nums[i] <= 10^7
| class Solution(object):
def minimumDifference(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
t = sum(nums)
arr = [2 * v for v in nums]
n = len(arr) // 2
m = 1 << n
pc = [0] * m
for i in xrange(1, m):
pc[i] = 1 + pc[i&(i-1)]
def compute_sums(arr):
s = [0]
for v in arr:
for i in xrange(len(s)):
s.append(s[i] + v)
f = [set() for _ in xrange(n+1)]
for i in xrange(m):
f[pc[i]].add(s[i])
return map(sorted, f)
lhs_sums = compute_sums(arr[:n])
rhs_sums = compute_sums(arr[n:])
best = float('inf')
for lhs, rhs in zip(lhs_sums, reversed(rhs_sums)):
i = 0
j = len(rhs) - 1
while best > 0 and i < len(lhs) and j >= 0:
c = lhs[i] + rhs[j] - t
best = min(best, abs(c))
if c > 0:
j -= 1
else:
i += 1
return best |
c87333 | f92df4 | Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is either:
'H', meaning move horizontally (go right), or
'V', meaning move vertically (go down).
Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.
Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.
Example 1:
Input: destination = [2,3], k = 1
Output: "HHHVV"
Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:
["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
Example 2:
Input: destination = [2,3], k = 2
Output: "HHVHV"
Example 3:
Input: destination = [2,3], k = 3
Output: "HHVVH"
Constraints:
destination.length == 2
1 <= row, column <= 15
1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.
| class Solution(object):
def comb(self, n, k):
return self.fact[n] / (self.fact[k] * self.fact[n - k])
def kthSmallestPath(self, destination, k):
"""
:type destination: List[int]
:type k: int
:rtype: str
"""
"""
col 个 H row 个 V 组成的第K个
"""
self.fact = [1] * 50
for i in range(1, 50):
self.fact[i] = self.fact[i - 1] * i
# Decide each digit one by one.
row, col = destination
ans = ''
while row and col:
# What is count of ways starting with H?
# (col - 1, row)
cnt = self.comb(row + col - 1, row)
if k <= cnt:
ans += 'H'
col -= 1
else:
k -= cnt
ans += 'V'
row -= 1
while row:
ans += 'V'
row -= 1
while col:
ans += 'H'
col -= 1
return ans
|
089550 | f92df4 | Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is either:
'H', meaning move horizontally (go right), or
'V', meaning move vertically (go down).
Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.
Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.
Example 1:
Input: destination = [2,3], k = 1
Output: "HHHVV"
Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:
["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
Example 2:
Input: destination = [2,3], k = 2
Output: "HHVHV"
Example 3:
Input: destination = [2,3], k = 3
Output: "HHVVH"
Constraints:
destination.length == 2
1 <= row, column <= 15
1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.
| class Solution:
def kthSmallestPath(self, destination: List[int], k: int) -> str:
v, h = destination
ans = list()
for i in range(h + v):
if h > 0:
check = math.comb(h + v - 1, h - 1)
if k > check:
k -= check
ans.append("V")
v -= 1
else:
ans.append("H")
h -= 1
else:
ans.append("V")
v -= 1
return "".join(ans) |
20190b | 6b51fb | Given a matrix and a target, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.
Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.
Example 1:
Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.
Example 2:
Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Example 3:
Input: matrix = [[904]], target = 0
Output: 0
Constraints:
1 <= matrix.length <= 100
1 <= matrix[0].length <= 100
-1000 <= matrix[i] <= 1000
-10^8 <= target <= 10^8
| class Solution(object):
def numSubmatrixSumTarget(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: int
"""
# dp[i][j] stores the sum of A[0][j], A[1][j], ..., A[i][j].
m = len(matrix)
n = len(matrix[0])
dp = [[0 for j in range(n)] for i in range(m)]
for j in range(n):
for i in range(m):
if i == 0: dp[i][j] = matrix[0][j]
else: dp[i][j] = dp[i - 1][j] + matrix[i][j]
rtn = 0
# enumerate r1, r2.
for r1 in range(m):
for r2 in range(r1, m):
# A[r1...r2][c...d] = target
index = {0: 1}
curr = 0
for c in range(n):
curr += dp[r2][c]
if r1: curr -= dp[r1 - 1][c]
if curr - target in index:
rtn += index[curr - target]
if curr not in index: index[curr] = 1
else: index[curr] += 1
return rtn |
3e5bae | 6b51fb | Given a matrix and a target, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.
Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.
Example 1:
Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.
Example 2:
Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Example 3:
Input: matrix = [[904]], target = 0
Output: 0
Constraints:
1 <= matrix.length <= 100
1 <= matrix[0].length <= 100
-1000 <= matrix[i] <= 1000
-10^8 <= target <= 10^8
| from collections import defaultdict, Counter
class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
ans = 0
for row1 in range(len(matrix)):
cumSum = [0]*len(matrix[0])
for row2 in range(row1, len(matrix)):
d = defaultdict(int)
d[0] = 1
curSum = 0
for c in range(len(matrix[0])):
cumSum[c] += matrix[row2][c]
curSum += cumSum[c]
ans += d[curSum - target]
d[curSum] += 1
return ans
|
3334e1 | 1fd102 | You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:
Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
Swap the two characters at indices i - 1 and j.
Reverse the suffix starting at index i.
Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "cba"
Output: 5
Explanation: The simulation goes as follows:
Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
Example 2:
Input: s = "aabaa"
Output: 2
Explanation: The simulation goes as follows:
Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
Constraints:
1 <= s.length <= 3000
s consists only of lowercase English letters.
| mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
class Solution:
def makeStringSorted(self, s: str) -> int:
mod=int(1e9)+7
ifact(3000,mod)
c=Counter(s)
n=len(s)
ans=0
for i in range(n-1):
cur=ord(s[i])-97
rem=n-i-1
mul=fact(rem,mod)
for k in c:
mul=mul*ifa[c[k]]%mod
#print(i,rem,mul,c)
for j in range(cur):
if c[chr(j+97)]:
ans+=mul*c[chr(j+97)]%mod
ans%=mod
c[s[i]]-=1
if c[s[i]]==0:
del c[s[i]]
#print(i,ans)
return ans |
d25c49 | 1fd102 | You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:
Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
Swap the two characters at indices i - 1 and j.
Reverse the suffix starting at index i.
Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "cba"
Output: 5
Explanation: The simulation goes as follows:
Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
Example 2:
Input: s = "aabaa"
Output: 2
Explanation: The simulation goes as follows:
Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
Constraints:
1 <= s.length <= 3000
s consists only of lowercase English letters.
| mod = 10**9 + 7
fa = [1]
rev = [1]
for i in xrange(1,3005):
fa.append( (i * fa[-1])%mod)
rev.append(pow(fa[i],mod-2,mod))
def ncr(n,r):
num = fa[n]
den= (fa[r] * fa[n-r])%mod
den = pow(den, mod-2, mod)
return (num * den)%mod
class Solution(object):
def makeStringSorted(self, s):
cnt = [0] * 26
ans = 0
for i in s:
x = ord(i) - ord('a')
cnt[x] += 1
nn = len(s) - 1
for i in s:
x = ord(i) - ord('a')
num = fa[sum(cnt)-1]
for j in xrange(x):
if cnt[j] > 0:
cnt[j]-=1
mul = 1
for xx in cnt:
mul = (mul * rev[xx])%mod
ans += (num * mul)%mod
if ans >=mod:
ans-=mod
cnt[j]+=1
cnt[x]-=1
nn-=1
return ans%mod
|
f80c3f | e57435 | You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. We turn on exactly one bulb every day until all bulbs are on after n days.
You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day, we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.
Given an integer k, return the minimum day number such that there exists two turned on bulbs that have exactly k bulbs between them that are all turned off. If there isn't such day, return -1.
Example 1:
Input: bulbs = [1,3,2], k = 1
Output: 2
Explanation:
On the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]
On the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]
On the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]
We return 2 because on the second day, there were two on bulbs with one off bulb between them.
Example 2:
Input: bulbs = [1,2,3], k = 1
Output: -1
Constraints:
n == bulbs.length
1 <= n <= 2 * 10000
1 <= bulbs[i] <= n
bulbs is a permutation of numbers from 1 to n.
0 <= k <= 2 * 10000
| from bisect import bisect_left, insort
class Solution(object):
def kEmptySlots(self, flowers, k):
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
positions = []
for i in range(len(flowers)):
pos = bisect_left(positions, flowers[i])
if pos > 0:
if abs(positions[pos-1] - flowers[i]) == k+1:
return i+1
if pos < len(positions):
if abs(positions[pos] - flowers[i]) == k+1:
return i+1
insort(positions, flowers[i])
return -1
#print(positions) |
c71ee8 | e57435 | You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. We turn on exactly one bulb every day until all bulbs are on after n days.
You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day, we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.
Given an integer k, return the minimum day number such that there exists two turned on bulbs that have exactly k bulbs between them that are all turned off. If there isn't such day, return -1.
Example 1:
Input: bulbs = [1,3,2], k = 1
Output: 2
Explanation:
On the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]
On the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]
On the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]
We return 2 because on the second day, there were two on bulbs with one off bulb between them.
Example 2:
Input: bulbs = [1,2,3], k = 1
Output: -1
Constraints:
n == bulbs.length
1 <= n <= 2 * 10000
1 <= bulbs[i] <= n
bulbs is a permutation of numbers from 1 to n.
0 <= k <= 2 * 10000
| class Solution:
def kEmptySlots(self, flowers, k):
h=[0 for i in range(len(flowers)+1)]
h[flowers[0]]=1
for i in range(1,len(flowers)):
t=flowers[i]
h[t]=1
try:
if h[t-k-1]==1:
bz=True
for j in range(k):
if t-j-1==0 or h[t-j-1]==1:
bz=False
break
if bz:return i+1
except:
pass
try:
if h[t+k+1]==1:
bz=True
for j in range(k):
if h[t+j+1]==1:
bz=False
break
if bz:return i+1
except:
pass
return -1
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
|
d32dac | b54298 | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values:
The strength of the weakest wizard in the group.
The total of all the individual strengths of the wizards in the group.
Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 10^9 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: strength = [1,3,1,2]
Output: 44
Explanation: The following are all the contiguous groups of wizards:
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4
- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4
- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4
- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3
- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5
- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6
- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7
The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.
Example 2:
Input: strength = [5,4,6]
Output: 213
Explanation: The following are all the contiguous groups of wizards:
- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25
- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16
- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36
- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36
- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40
- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60
The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.
Constraints:
1 <= strength.length <= 100000
1 <= strength[i] <= 10^9
| class Solution(object):
def totalStrength(self, strength):
"""
:type strength: List[int]
:rtype: int
"""
d, i, p, v, w, s, t, q, n, r, u, x, y = [], [], [], len(strength) + 1, 2, 0, 0, 0, [len(strength)] * len(strength), [-1] * len(strength), [], [], 0
for j in strength:
s, q, v = (s + v * j) % 1000000007, (q + j) % 1000000007, v - 1
d.append([s, v + 1])
p.append(q)
for j in strength:
t, w = (t + w * j) % 1000000007, w + 1
i.append([t, w - 1])
for j in range(len(strength)):
while u and strength[u[-1]] > strength[j]:
n[u[-1]] = j
u.pop()
u.append(j)
for j in range(len(strength) - 1, -1, -1):
while x and strength[x[-1]] >= strength[j]:
r[x[-1]] = j
x.pop()
x.append(j)
for j in range(len(strength)):
y = (y + (((i[j][0] - (0 if r[j] < 0 else i[r[j]][0]) + 1000000007) % 1000000007 - (p[j] - (0 if r[j] < 0 else p[r[j]]) + 1000000007) % 1000000007 * (1 if r[j] < 0 else i[r[j]][1]) % 1000000007 + 1000000007) % 1000000007 + ((d[n[j] - 1][0] - (0 if j < 0 else d[j][0]) + 1000000007) % 1000000007 - (p[n[j] - 1] - (0 if j < 0 else p[j]) + 1000000007) % 1000000007 * (1 if n[j] == len(strength) else d[n[j]][1]) % 1000000007 + 1000000007) % 1000000007 * (j - r[j]) + ((i[j][0] - (0 if r[j] < 0 else i[r[j]][0]) + 1000000007) % 1000000007 - (p[j] - (0 if r[j] < 0 else p[r[j]]) + 1000000007) % 1000000007 * (1 if r[j] < 0 else i[r[j]][1]) % 1000000007 + 1000000007) % 1000000007 * (n[j] - j - 1)) % 1000000007 * strength[j]) % 1000000007
return y |
381a6f | b54298 | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values:
The strength of the weakest wizard in the group.
The total of all the individual strengths of the wizards in the group.
Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 10^9 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: strength = [1,3,1,2]
Output: 44
Explanation: The following are all the contiguous groups of wizards:
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9
- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4
- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4
- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4
- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3
- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5
- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6
- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7
The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.
Example 2:
Input: strength = [5,4,6]
Output: 213
Explanation: The following are all the contiguous groups of wizards:
- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25
- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16
- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36
- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36
- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40
- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60
The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.
Constraints:
1 <= strength.length <= 100000
1 <= strength[i] <= 10^9
| class Solution:
def totalStrength(self, s: List[int]) -> int:
mod = 10 ** 9 + 7
n = len(s)
l1 = [0] * (n+1)
l2 = [0] * (n+1)
for i in range(n):
l1[i] = l1[i-1] + s[i]
l2[i] = l2[i-1] + l1[i]
r1 = [0] * (n+1)
r2 = [0] * (n+1)
for i in range(n-1, -1, -1):
r1[i] = r1[i+1] + s[i]
r2[i] = r2[i+1] + r1[i]
st = [[-1, -inf]]
ans = 0
for i, a in enumerate(s + [-inf]):
while st and st[-1][1] > a:
l = st[-2][0] + 1
m = st[-1][0]
r = i - 1
lhs = r2[l] - r2[m+1] - (m+1-l) * r1[m+1]
cnt = lhs * (r-m+1)
rhs = l2[r] - l2[m] - (r-m) * l1[m]
cnt += rhs * (m-l+1)
cnt *= st[-1][1]
ans = (ans + cnt) % mod
# print(l, m, r, lhs, rhs, cnt, ans)
st.pop()
st.append([i, a])
return ans |
74a1b4 | 33ebbc | HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
Quotation Mark: the entity is " and symbol character is ".
Single Quote Mark: the entity is ' and symbol character is '.
Ampersand: the entity is & and symbol character is &.
Greater Than Sign: the entity is > and symbol character is >.
Less Than Sign: the entity is < and symbol character is <.
Slash: the entity is ⁄ and symbol character is /.
Given the input text string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
Example 1:
Input: text = "& is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the & entity by &
Example 2:
Input: text = "and I quote: "...""
Output: "and I quote: \"...\""
Constraints:
1 <= text.length <= 100000
The string may contain any possible characters out of all the 256 ASCII characters.
| class Solution(object):
def entityParser(self, text):
ans = []
i = 0
"""
Quotation Mark: the entity is " and symbol character is ".
Single Quote Mark: the entity is ' and symbol character is '.
Ampersand: the entity is & and symbol character is &.
Greater Than Sign: the entity is > and symbol character is >.
Less Than Sign: the entity is < and symbol character is <.
Slash: the entity is ⁄ and symbol character is /.
"""
while i < len(text):
if text[i] != '&':
ans.append(text[i])
i += 1
continue
else:
if text[i+1:i+6] == 'quot;':
ans.append('"')
i += 6
elif text[i+1:i+6] == 'apos;':
ans.append("'")
i += 6
elif text[i+1:i+5] == 'amp;':
ans.append('&')
i += 5
elif text[i+1:i+4] == 'gt;':
ans.append('>')
i += 4
elif text[i+1:i+4] == 'lt;':
ans.append('<')
i += 4
elif text[i+1:i+7] == 'frasl;':
ans.append('/')
i += 7
else:
ans.append(text[i])
i += 1
return "".join(ans) |
e2889f | 33ebbc | HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
Quotation Mark: the entity is " and symbol character is ".
Single Quote Mark: the entity is ' and symbol character is '.
Ampersand: the entity is & and symbol character is &.
Greater Than Sign: the entity is > and symbol character is >.
Less Than Sign: the entity is < and symbol character is <.
Slash: the entity is ⁄ and symbol character is /.
Given the input text string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
Example 1:
Input: text = "& is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the & entity by &
Example 2:
Input: text = "and I quote: "...""
Output: "and I quote: \"...\""
Constraints:
1 <= text.length <= 100000
The string may contain any possible characters out of all the 256 ASCII characters.
| class Solution:
def entityParser(self, text: str) -> str:
ans = text.replace('"', '"')
ans = ans.replace(''', "'")
ans = ans.replace('&', "&")
ans = ans.replace('>', ">")
ans = ans.replace('<', "<")
ans = ans.replace('⁄', "/")
return ans |
af1022 | 48e80c | There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the ith query.
Example 1:
Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:
Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
Constraints:
3 <= s.length <= 100000
s consists of '*' and '|' characters.
1 <= queries.length <= 100000
queries[i].length == 2
0 <= lefti <= righti < s.length
| class Solution(object):
def platesBetweenCandles(self, s, queries):
n = len(s)
pre = [0]
A = []
for i,c in enumerate(s):
pre.append(pre[-1] + (c == '*'))
if c == '|':
A.append(i)
res = []
for a,b in queries:
i = bisect.bisect_left(A, a)
j = bisect.bisect(A, b) - 1
if j < 0 or i == len(A):
res.append(0)
else:
res.append(max(pre[A[j]] - pre[A[i]], 0))
return res
|
260e5a | 48e80c | There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the ith query.
Example 1:
Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:
Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
Constraints:
3 <= s.length <= 100000
s consists of '*' and '|' characters.
1 <= queries.length <= 100000
queries[i].length == 2
0 <= lefti <= righti < s.length
| class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
n = len(s)
res = []
shangzuo, shangyou = -1,-1
presum = [0] * (1 + n)
leftcandle = [-1] * n
rightcandle = [-1] * n
leftplate = -1
rightplate = -1
#leftcandle = -1
#rightcandle = -1
for idx in range(len(s)):
plates = s[idx]
if plates == '*':
presum[idx + 1] = presum[idx] + 1
else:
presum[idx + 1] = presum[idx]
shangzuo = idx
leftcandle[idx] = shangzuo
for idx in range(n - 1, -1, -1):
if s[idx] == '|':
shangyou = idx
rightcandle[idx] = shangyou
for a, b in queries:
f = rightcandle[a]
if f == -1 or f > b:
res.append(0)
continue
l = leftcandle[b]
res.append(presum[l] - presum[f])
return res
|
b53924 | c67c09 | Given an empty set of intervals, implement a data structure that can:
Add an interval to the set of intervals.
Count the number of integers that are present in at least one interval.
Implement the CountIntervals class:
CountIntervals() Initializes the object with an empty set of intervals.
void add(int left, int right) Adds the interval [left, right] to the set of intervals.
int count() Returns the number of integers that are present in at least one interval.
Note that an interval [left, right] denotes all the integers x where left <= x <= right.
Example 1:
Input
["CountIntervals", "add", "add", "count", "add", "count"]
[[], [2, 3], [7, 10], [], [5, 8], []]
Output
[null, null, null, 6, null, 8]
Explanation
CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals.
countIntervals.add(2, 3); // add [2, 3] to the set of intervals.
countIntervals.add(7, 10); // add [7, 10] to the set of intervals.
countIntervals.count(); // return 6
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 7, 8, 9, and 10 are present in the interval [7, 10].
countIntervals.add(5, 8); // add [5, 8] to the set of intervals.
countIntervals.count(); // return 8
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 5 and 6 are present in the interval [5, 8].
// the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].
// the integers 9 and 10 are present in the interval [7, 10].
Constraints:
1 <= left <= right <= 10^9
At most 100000 calls in total will be made to add and count.
At least one call will be made to count.
| from sortedcontainers import SortedDict
class CountIntervals(object):
def __init__(self):
self.m, self.c = SortedDict(), 0
def add(self, left, right):
"""
:type left: int
:type right: int
:rtype: None
"""
k, r, e = self.m.keys()[self.m.bisect_left(left) - 1] if self.m.bisect_left(left) > 0 else None, [], right
if k == None or self.m[k] < left - 1:
k = self.m.keys()[self.m.bisect_right(left - 1)] if self.m.bisect_right(left - 1) < len(self.m) else None
self.c += 0 if k == None or k > right else k - left
self.c += right - left + 1 if k == None or k > right else 0
while k != None and k <= right:
r.append(k)
v, left, e, k = self.m[k], min(left, k), max(self.m[k], e), self.m.keys()[self.m.bisect_right(self.m[k])] if self.m.bisect_right(self.m[k]) < len(self.m) else None
self.c += max(0, right - v if k == None or right < k else k - v - 1)
for n in r:
del self.m[n]
self.m[left] = e
def count(self):
"""
:rtype: int
"""
return self.c
# Your CountIntervals object will be instantiated and called as such:
# obj = CountIntervals()
# obj.add(left,right)
# param_2 = obj.count() |
e9931d | c67c09 | Given an empty set of intervals, implement a data structure that can:
Add an interval to the set of intervals.
Count the number of integers that are present in at least one interval.
Implement the CountIntervals class:
CountIntervals() Initializes the object with an empty set of intervals.
void add(int left, int right) Adds the interval [left, right] to the set of intervals.
int count() Returns the number of integers that are present in at least one interval.
Note that an interval [left, right] denotes all the integers x where left <= x <= right.
Example 1:
Input
["CountIntervals", "add", "add", "count", "add", "count"]
[[], [2, 3], [7, 10], [], [5, 8], []]
Output
[null, null, null, 6, null, 8]
Explanation
CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals.
countIntervals.add(2, 3); // add [2, 3] to the set of intervals.
countIntervals.add(7, 10); // add [7, 10] to the set of intervals.
countIntervals.count(); // return 6
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 7, 8, 9, and 10 are present in the interval [7, 10].
countIntervals.add(5, 8); // add [5, 8] to the set of intervals.
countIntervals.count(); // return 8
// the integers 2 and 3 are present in the interval [2, 3].
// the integers 5 and 6 are present in the interval [5, 8].
// the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].
// the integers 9 and 10 are present in the interval [7, 10].
Constraints:
1 <= left <= right <= 10^9
At most 100000 calls in total will be made to add and count.
At least one call will be made to count.
| from sortedcontainers import SortedList
class CountIntervals:
def __init__(self):
self.a = SortedList()
self.c = 0
def overlap(self, i1, i2):
return max(i1[0], i2[0]) <= min(i1[1], i2[1])
def merge(self, i1, i2):
return [min(i1[0], i2[0]), max(i1[1], i2[1])]
def add(self, left: int, right: int) -> None:
current = [left, right]
idx = self.a.bisect_left(current)
kill = []
for i in range(idx, len(self.a)):
if not self.overlap(self.a[i], current):
break
else:
kill.append(i)
current = self.merge(self.a[i], current)
for i in range(idx - 1, -1, -1):
if not self.overlap(self.a[i], current):
break
else:
kill.append(i)
current = self.merge(self.a[i], current)
kill.sort(reverse=True)
for i in kill:
r = self.a.pop(i)
self.c -= r[1] - r[0] + 1
self.c += current[1] - current[0] + 1
self.a.add(current)
def count(self) -> int:
return self.c
# Your CountIntervals object will be instantiated and called as such:
# obj = CountIntervals()
# obj.add(left,right)
# param_2 = obj.count() |
682980 | 4e64bb | In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Constraints:
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case letters.
1 <= sentence.length <= 1000000
sentence consists of only lower-case letters and spaces.
The number of words in sentence is in the range [1, 1000]
The length of each word in sentence is in the range [1, 1000]
Every two consecutive words in sentence will be separated by exactly one space.
sentence does not have leading or trailing spaces.
| class Solution(object):
def replaceWords(self, dict, sentence):
dict = set(dict)
res = []
def add(word):
for i in range(1, len(word)):
if word[:i] in dict:
res.append(word[:i])
return
res.append(word)
words = sentence.split(" ")
for word in words:
add(word);
return " ".join(res) |
d9daa3 | 4e64bb | In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Constraints:
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case letters.
1 <= sentence.length <= 1000000
sentence consists of only lower-case letters and spaces.
The number of words in sentence is in the range [1, 1000]
The length of each word in sentence is in the range [1, 1000]
Every two consecutive words in sentence will be separated by exactly one space.
sentence does not have leading or trailing spaces.
| class Solution:
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
words = sentence.split(' ')
dict = set(dict)
# print(words)
ans = []
for w in words:
for i in range(len(w)):
if w[:i] in dict:
ans.append(w[:i])
break
else:
ans.append(w)
res = " ".join(ans)
return res
|
a3f86d | f59cb4 | We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 10000
1 <= startTime[i] < endTime[i] <= 10^9
1 <= profit[i] <= 10000
| class Solution(object):
def jobScheduling(self, startTime, endTime, profit):
times = set(startTime)
for t in endTime:
times.add(t)
timemap = {t: i for i, t in enumerate(sorted(times))}
W = len(timemap)
graph = [[] for _ in xrange(W)]
for i in xrange(len(startTime)):
s = startTime[i]
si = timemap[s]
e = endTime[i]
ei = timemap[e]
graph[ei].append((si, i))
NINF = -(1 << 50)
dist = [NINF for _ in xrange(W + 1)]
dist[W-1] = 0
for ei in xrange(W-1, -1, -1):
if dist[ei + 1] > dist[ei]:
dist[ei ] =dist[ei+1]
for si, i in graph[ei]:
cand = dist[ei] + profit[i]
if cand > dist[si]:
dist[si] = cand
return dist[0] |
d02cd1 | f59cb4 | We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 10000
1 <= startTime[i] < endTime[i] <= 10^9
1 <= profit[i] <= 10000
| class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
##sort by end time
jobs=[]
for i in range(len(startTime)):
jobs+=[(startTime[i],endTime[i],profit[i])]
jobs=sorted(jobs,key=lambda x:x[1])
dp={}
right_end=[]
import bisect
MAX=0
for i in range(len(jobs)):
L,R,P=jobs[i]
if right_end==[]:
dp[R]=P
right_end+=[R]
else:
at_most=L
pos=bisect.bisect_right(right_end,at_most)
if pos==0:
dp[R]=max(dp[right_end[-1]],P)
right_end+=[R]
else:
dp[R]=max(dp[right_end[-1]],P+dp[right_end[pos-1]])
right_end+=[R]
MAX=max(MAX,dp[R])
#print(dp)
return MAX
|
aef00a | 19c409 | You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].
You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.
Example 1:
Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]
Output: 7
Explanation: One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid[2][3] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
Example 2:
Input: grid = [[0,2,4],[3,2,1],[1,0,4]]
Output: -1
Explanation: There is no path from the top left to the bottom-right cell.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 100000
0 <= grid[i][j] <= 100000
grid[0][0] == 0
| class Solution(object):
def minimumTime(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if grid[0][1] < 2 or grid[1][0] < 2:
p, d = [[0, 0, 0]], [[float('inf')] * len(grid[0]) for _ in grid]
d[0][0] = 0
while p:
x, i, j = heappop(p)
if i == len(grid) - 1 and j == len(grid[0]) - 1:
return x
for k in range(4):
if 0 <= i + [-1, 0, 1, 0, -1][k] and i + [-1, 0, 1, 0, -1][k] < len(grid) and 0 <= j + [-1, 0, 1, 0, -1][k + 1] and j + [-1, 0, 1, 0, -1][k + 1] < len(grid[0]) and d[i + [-1, 0, 1, 0, -1][k]][j + [-1, 0, 1, 0, -1][k + 1]] > x + 1 + max(0, (grid[i + [-1, 0, 1, 0, -1][k]][j + [-1, 0, 1, 0, -1][k + 1]] - x) / 2 * 2):
heappush(p, [x + 1 + max(0, (grid[i + [-1, 0, 1, 0, -1][k]][j + [-1, 0, 1, 0, -1][k + 1]] - x) / 2 * 2), i + [-1, 0, 1, 0, -1][k], j + [-1, 0, 1, 0, -1][k + 1]])
d[i + [-1, 0, 1, 0, -1][k]][j + [-1, 0, 1, 0, -1][k + 1]] = x + 1 + max(0, (grid[i + [-1, 0, 1, 0, -1][k]][j + [-1, 0, 1, 0, -1][k + 1]] - x) / 2 * 2)
return -1 |
464054 | 19c409 | You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].
You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.
Example 1:
Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]
Output: 7
Explanation: One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid[2][3] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
Example 2:
Input: grid = [[0,2,4],[3,2,1],[1,0,4]]
Output: -1
Explanation: There is no path from the top left to the bottom-right cell.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 100000
0 <= grid[i][j] <= 100000
grid[0][0] == 0
| class Solution:
def minimumTime(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
if grid[0][1] > 1 and grid[1][0] > 1: return -1
ans = [[inf] * m for _ in range(n)]
ans[0][0] = 0
hpq = [[0, [0, 0]]]
dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while hpq:
dist, (x, y) = heappop(hpq)
for dx, dy in dirs:
if 0 <= x + dx < n and 0 <= y + dy < m:
new_dist = dist + 1
v = grid[x + dx][y + dy]
if new_dist < v:
if (new_dist - v) % 2: new_dist = v + 1
else: new_dist = v
if new_dist < ans[x + dx][y + dy]:
ans[x + dx][y + dy] = new_dist
heappush(hpq, [new_dist, [x + dx, y + dy]])
return ans[-1][-1] |
d7ca46 | c1d66b | You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:
0 represents an empty cell,
1 represents an obstacle that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).
Example 1:
Input: grid = [[0,1,1],[1,1,0],[1,1,0]]
Output: 2
Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).
It can be shown that we need to remove at least 2 obstacles, so we return 2.
Note that there may be other ways to remove 2 obstacles to create a path.
Example 2:
Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]
Output: 0
Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100000
2 <= m * n <= 100000
grid[i][j] is either 0 or 1.
grid[0][0] == grid[m - 1][n - 1] == 0
| class Solution(object):
def minimumObstacles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
q, v = [[0, 0, 0]], [[False] * len(grid[0]) for _ in grid]
v[0][0] = True
while q:
c = heapq.heappop(q)
if c[1] == len(grid) - 1 and c[2] == len(grid[0]) - 1:
return c[0]
for d in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
if d[0] + c[1] >= 0 and d[1] + c[2] >= 0 and d[0] + c[1] < len(grid) and d[1] + c[2] < len(grid[0]) and not v[d[0] + c[1]][d[1] + c[2]]:
v[d[0] + c[1]][d[1] + c[2]] = True
heapq.heappush(q, [c[0] + grid[d[0] + c[1]][d[1] + c[2]], d[0] + c[1], d[1] + c[2]]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.