sol_id
stringlengths 6
6
| problem_id
stringlengths 6
6
| problem_text
stringlengths 322
4.55k
| solution_text
stringlengths 137
5.74k
|
---|---|---|---|
5fe418 | 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:
def minimumObstacles(self, g: List[List[int]]) -> int:
q = deque()
n = len(g)
m = len(g[0])
d = [[1000000 for j in range(m)]for i in range(n)]
d[0][0] = 0
q.append((0, 0))
def nei(x, y):
return 0 <= x < n and 0 <= y < m
while q:
x, y = q.popleft()
for nx, ny in (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1):
if nei(nx, ny):
if d[nx][ny] > d[x][y] + g[nx][ny]:
d[nx][ny] = d[x][y] + g[nx][ny]
if g[nx][ny]:
q.append((nx, ny))
else:
q.appendleft((nx, ny))
return d[n-1][m-1] |
ff8f43 | f7e16b | You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:
Compute multiplication, reading from left to right; Then,
Compute addition, reading from left to right.
You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:
If an answer equals the correct answer of the expression, this student will be rewarded 5 points;
Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;
Otherwise, this student will be rewarded 0 points.
Return the sum of the points of the students.
Example 1:
Input: s = "7+3*1*2", answers = [20,13,42]
Output: 7
Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]
A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]
The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.
Example 2:
Input: s = "3+5*2", answers = [13,0,10,13,13,16,16]
Output: 19
Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]
A student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]
The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.
Example 3:
Input: s = "6+0*1", answers = [12,9,6,4,8,6]
Output: 10
Explanation: The correct answer of the expression is 6.
If a student had incorrectly done (6+0)*1, the answer would also be 6.
By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.
The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.
Constraints:
3 <= s.length <= 31
s represents a valid expression that contains only digits 0-9, '+', and '*' only.
All the integer operands in the expression are in the inclusive range [0, 9].
1 <= The count of all operators ('+' and '*') in the math expression <= 15
Test data are generated such that the correct answer of the expression is in the range of [0, 1000].
n == answers.length
1 <= n <= 10000
0 <= answers[i] <= 1000
| class Solution(object):
def scoreOfStudents(self, s, answers):
"""
:type s: str
:type answers: List[int]
:rtype: int
"""
a = []
b = []
for ch in s:
if ch.isdigit():
a.append(int(ch))
else:
b.append(ch)
n = len(a)
f = [[set() for _ in xrange(n+1)] for _ in xrange(n)]
ops = {
'+': (lambda a, b: a + b),
'*': (lambda a, b: a * b),
}
ub = max(answers)
for i in xrange(n-1, -1, -1):
f[i][i+1].add(a[i])
for j in xrange(i+2, n+1):
for k in xrange(i+1, j):
op = ops[b[k-1]]
for lhs in f[i][k]:
for rhs in f[k][j]:
f[i][j].add(min(op(lhs, rhs), ub+1))
correct = eval(s)
possible = f[0][n]
def grade(answer):
if answer == correct:
return 5
if answer in possible:
return 2
return 0
return sum(grade(answer) for answer in answers) |
ab20d6 | f7e16b | You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:
Compute multiplication, reading from left to right; Then,
Compute addition, reading from left to right.
You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:
If an answer equals the correct answer of the expression, this student will be rewarded 5 points;
Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;
Otherwise, this student will be rewarded 0 points.
Return the sum of the points of the students.
Example 1:
Input: s = "7+3*1*2", answers = [20,13,42]
Output: 7
Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]
A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]
The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.
Example 2:
Input: s = "3+5*2", answers = [13,0,10,13,13,16,16]
Output: 19
Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]
A student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]
The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.
Example 3:
Input: s = "6+0*1", answers = [12,9,6,4,8,6]
Output: 10
Explanation: The correct answer of the expression is 6.
If a student had incorrectly done (6+0)*1, the answer would also be 6.
By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.
The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.
Constraints:
3 <= s.length <= 31
s represents a valid expression that contains only digits 0-9, '+', and '*' only.
All the integer operands in the expression are in the inclusive range [0, 9].
1 <= The count of all operators ('+' and '*') in the math expression <= 15
Test data are generated such that the correct answer of the expression is in the range of [0, 1000].
n == answers.length
1 <= n <= 10000
0 <= answers[i] <= 1000
| class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
gold = eval(s)
@functools.lru_cache(None)
def get_all_poss(p0=0, p1=len(s)-1) :
if p0 == p1 :
return set([int(s[p0])])
to_ret = set()
for p_sign in range(p0+1, p1, 2) :
v1 = get_all_poss(p0, p_sign-1)
v2 = get_all_poss(p_sign+1, p1)
for a in v1 :
for b in v2 :
to_add = a+b if s[p_sign] == '+' else a*b
if to_add <= 1000 :
to_ret.add(to_add)
# print(p0, p1, to_ret)
return to_ret
pos = get_all_poss()
to_ret = 0
for at in answers :
if at == gold :
to_ret += 5
elif at in pos :
to_ret += 2
return to_ret |
cb4873 | 3b1a38 | The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
Example 1:
Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0
Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
Example 2:
Input: arr1 = [12], arr2 = [4]
Output: 4
Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
Constraints:
1 <= arr1.length, arr2.length <= 100000
0 <= arr1[i], arr2[j] <= 10^9
| class Solution:
def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:
s = 0
for num in arr2:
s ^= num
ans = 0
for num in arr1:
ans ^= (num & s)
return ans |
f87388 | 3b1a38 | The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
Example 1:
Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0
Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
Example 2:
Input: arr1 = [12], arr2 = [4]
Output: 4
Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
Constraints:
1 <= arr1.length, arr2.length <= 100000
0 <= arr1[i], arr2[j] <= 10^9
| class Solution(object):
def getXORSum(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: int
"""
m = max(max(arr1), max(arr2)).bit_length()
c1 = [sum((v>>i)&1 for v in arr1)&1 for i in xrange(m)]
c2 = [sum((v>>i)&1 for v in arr2)&1 for i in xrange(m)]
return sum(1<<i for i in xrange(m) if c1[i]&c2[i]) |
ab5e5d | 134361 | Given an integer array nums, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j) where:
0 <= i < j < nums.length and
nums[i] > 2 * nums[j].
Example 1:
Input: nums = [1,3,2,3,1]
Output: 2
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
Example 2:
Input: nums = [2,4,3,5,1]
Output: 3
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
Constraints:
1 <= nums.length <= 5 * 10000
-2^31 <= nums[i] <= 2^31 - 1
| class Solution(object):
def reversePairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l <= 1:
return 0
from bisect import *
cnt = 0
bag = []
for i in range(l):
n = nums[i]
jdx = bisect_right(bag, 2*n)
if jdx < len(bag):
cnt += len(bag)-jdx
#
jdx = bisect_right(bag, n)
bag.insert(jdx, n)
return cnt
|
5d5794 | d7f052 | Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns n should be equal to 2height+1 - 1.
Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
Continue this process until all the nodes in the tree have been placed.
Any empty cells should contain the empty string "".
Return the constructed matrix res.
Example 1:
Input: root = [1,2]
Output:
[["","1",""],
["2","",""]]
Example 2:
Input: root = [1,2,3,null,4]
Output:
[["","","","1","","",""],
["","2","","","","3",""],
["","","4","","","",""]]
Constraints:
The number of nodes in the tree is in the range [1, 210].
-99 <= Node.val <= 99
The depth of the tree will be in the range [1, 10].
| # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def ht(self, root):
if root is None:
return 0
return 1 + max(self.ht(root.left), self.ht(root.right))
def helper(self, root, level, start, end):
if root is None:
return
mid = (end + start) / 2
self.res[level][mid] = str(root.val)
self.helper(root.left, level+1, start, mid-1)
self.helper(root.right, level+1, mid+1, end)
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
h = self.ht(root)
w = 1
for i in range(1, h):
w = (w * 2 + 1)
self.res = [['' for _ in range(w)] for _ in range(h)]
self.helper(root, 0, 0, w-1)
return self.res
|
ae37a9 | d7f052 | Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns n should be equal to 2height+1 - 1.
Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
Continue this process until all the nodes in the tree have been placed.
Any empty cells should contain the empty string "".
Return the constructed matrix res.
Example 1:
Input: root = [1,2]
Output:
[["","1",""],
["2","",""]]
Example 2:
Input: root = [1,2,3,null,4]
Output:
[["","","","1","","",""],
["","2","","","","3",""],
["","","4","","","",""]]
Constraints:
The number of nodes in the tree is in the range [1, 210].
-99 <= Node.val <= 99
The depth of the tree will be in the range [1, 10].
| class Solution:
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def h(root):
if not root: return 0
return 1 + max(h(root.left), h(root.right))
COL = 2 ** h(root) - 1
r, q = [], [(0, COL // 2, COL, root)]
while True:
q2 = []
last = [''] * COL
for a, b, c, node in q:
if node:
last[b] = str(node.val)
q2.append((a, (a + b) // 2, b, node.left))
q2.append((b, (b + c) // 2, c, node.right))
q = q2
if q:
r.append(last)
else:
break
return r
|
444ee9 | 2f7517 | We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Given a string s, return the number of unique non-empty substrings of s are present in base.
Example 1:
Input: s = "a"
Output: 1
Explanation: Only the substring "a" of s is in base.
Example 2:
Input: s = "cac"
Output: 2
Explanation: There are two substrings ("a", "c") of s in base.
Example 3:
Input: s = "zab"
Output: 6
Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
Constraints:
1 <= s.length <= 100000
s consists of lowercase English letters.
| class Solution(object):
def findSubstringInWraproundString(self, p):
if not p:
return 0
L = [0] * 26
i = 0
while i < len(p):
j = i
while j+1 < len(p) and (ord(p[j+1])-ord(p[j]) == 1 or (p[j+1] == 'a' and p[j] == 'z')):
j += 1
for k in range(i, j+1):
L[ord(p[k]) - ord('a')] = max(L[ord(p[k]) - ord('a')], j-k+1)
i = j+1
res = 0
for x in L:
res += x
return res
"""
:type p: str
:rtype: int
"""
|
153364 | 50d730 | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
Input: order = "cbafg", s = "abcd"
Output: "cbad"
Constraints:
1 <= order.length <= 26
1 <= s.length <= 200
order and s consist of lowercase English letters.
All the characters of order are unique.
| class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
mydic={}
for c in T:
mydic[c]=mydic.get(c,0)+1
res=""
for s in S:
if mydic.has_key(s):
for i in range(mydic[s]):
res+=s
del mydic[s]
for s in mydic.keys():
for i in range(mydic[s]):
res+=s
return res |
73f79b | 50d730 | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
Input: order = "cbafg", s = "abcd"
Output: "cbad"
Constraints:
1 <= order.length <= 26
1 <= s.length <= 200
order and s consist of lowercase English letters.
All the characters of order are unique.
| class Solution:
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
m = {}
for i, c in enumerate(S):
m[c] = i
def get_val(c):
if c in m:
return m[c]
return -1
return "".join(sorted(T, key=get_val)) |
fbcd37 | 8754a7 | You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
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.
A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".
Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Example 1:
Input: s = "letsleetcode", k = 2
Output: "let"
Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
"let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2
Output: "b"
Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2
Output: ""
Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s consists of lowercase English letters.
| import itertools
from collections import Counter
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
candidate = []
for letter, cnt in Counter(s).items():
for i in range(cnt // k):
candidate.append(letter)
if not candidate:
return ''
choice = set()
n = len(candidate)
for i in range(2, n + 1):
for j in itertools.permutations(candidate, i):
choice.add(''.join(j))
choose = list((len(c), c) for c in choice)
choose.sort(reverse=True)
length = len(s)
for m, ans in choose:
tmp = k
idx = 0
for i, c in enumerate(s):
if length - i + idx < m * tmp:
break
if c == ans[idx]:
idx += 1
if idx == m:
idx = 0
tmp -= 1
if tmp == 0:
return ans
return max(candidate) |
f73bb9 | 8754a7 | You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
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.
A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".
Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Example 1:
Input: s = "letsleetcode", k = 2
Output: "let"
Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
"let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2
Output: "b"
Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2
Output: ""
Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s consists of lowercase English letters.
| from collections import Counter
class Solution(object):
def longestSubsequenceRepeatedK(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
avail = {ch : v//k for ch, v in Counter(s).iteritems() if v >= k}
s = ''.join(ch for ch in s if ch in avail)
n = len(s)
cand = sorted(avail, reverse=True)
avail = [avail[ch] for ch in cand]
idx = {ch : i for i, ch in enumerate(cand)}
m = len(cand)
jmp = [[-1]*m for _ in xrange(n+1)]
for i in xrange(n-1, -1, -1):
jmp[i] = jmp[i+1][:]
jmp[i][idx[s[i]]] = i+1
selected = []
def _check_selected():
pos = 0
for _ in xrange(k):
for i in selected:
pos = jmp[pos][i]
if pos < 0:
return False
return True
def _dfs():
if not _check_selected():
return ''
best = ''.join(cand[i] for i in selected)
for j in xrange(m):
if avail[j] > 0:
avail[j] -= 1
selected.append(j)
curr = _dfs()
if len(curr) > len(best):
best = curr
avail[j] += 1
selected.pop()
return best
return _dfs() |
54eb54 | b2b553 | There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
Example 1:
Input: positions = [[1,2],[2,3],[6,1]]
Output: [2,5,5]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of [2, 5, 5].
Example 2:
Input: positions = [[100,100],[200,100]]
Output: [100,100]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of [100, 100].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
Constraints:
1 <= positions.length <= 1000
1 <= lefti <= 10^8
1 <= sideLengthi <= 1000000
| class Solution(object):
def fallingSquares(self, p):
"""
:type positions: List[List[int]]
:rtype: List[int]
"""
n = len(p)
h = [0] * n
h[0] = p[0][1]
maxH = h[0]
res = [maxH]
for i in range(1,n):
for j in range(i):
if p[i][0]>=p[j][0]+p[j][1] or p[i][0]+p[i][1]<=p[j][0]:
continue
h[i] = max(h[i], h[j])
h[i] += p[i][1]
maxH = max(maxH, h[i])
res.append(maxH)
return res |
b9831d | b2b553 | There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
Example 1:
Input: positions = [[1,2],[2,3],[6,1]]
Output: [2,5,5]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of [2, 5, 5].
Example 2:
Input: positions = [[100,100],[200,100]]
Output: [100,100]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of [100, 100].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
Constraints:
1 <= positions.length <= 1000
1 <= lefti <= 10^8
1 <= sideLengthi <= 1000000
| class Solution:
def is_overlap(self,n1,n2,m1,m2):
if n1>=m1 and n1<=m2:
return True
if n2>=m1 and n2<=m2:
return True
if m1>=n1 and m1<=n2:
return True
if m2>=n1 and m2<=n2:
return True
return False
def fallingSquares(self, positions):
"""
:type positions: List[List[int]]
:rtype: List[int]
"""
n = len(positions)
heights = []
max_height = []
mh = 0
for i in range(n):
pi = positions[i]
li = pi[0]
ri = pi[0] + pi[1] - 1
hi = pi[1]
for lk,rk,hk in heights:
if self.is_overlap(li,ri,lk,rk):
hi = max(hi,hk+pi[1])
heights.append((li,ri,hi))
mh = max(hi,mh)
max_height.append(mh)
return max_height
|
937d13 | bfce30 | You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.
A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.
The time cost of spliting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.
Output the minimum time needed to build all blocks.
Initially, there is only one worker.
Example 1:
Input: blocks = [1], split = 1
Output: 1
Explanation: We use 1 worker to build 1 block in 1 time unit.
Example 2:
Input: blocks = [1,2], split = 5
Output: 7
Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.
Example 3:
Input: blocks = [1,2,3], split = 1
Output: 4
Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
Then, use the two unassigned workers to build the first two blocks.
The cost is 1 + max(3, 1 + max(1, 2)) = 4.
Constraints:
1 <= blocks.length <= 1000
1 <= blocks[i] <= 10^5
1 <= split <= 100
| class Solution(object):
def minBuildTime(self, blocks, split):
N = len(blocks)
blocks.sort(reverse = True)
times = [0]
while len(times) < N:
times.sort()
# find weakest candidate
i = min(xrange(len(times)), key = lambda t: blocks[t] + times[t])
# split candidate
times[i] += split
times.append(times[i])
return max(b + times[i] for i,b in enumerate(blocks))
|
52b3b5 | bfce30 | You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.
A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.
The time cost of spliting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.
Output the minimum time needed to build all blocks.
Initially, there is only one worker.
Example 1:
Input: blocks = [1], split = 1
Output: 1
Explanation: We use 1 worker to build 1 block in 1 time unit.
Example 2:
Input: blocks = [1,2], split = 5
Output: 7
Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.
Example 3:
Input: blocks = [1,2,3], split = 1
Output: 4
Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
Then, use the two unassigned workers to build the first two blocks.
The cost is 1 + max(3, 1 + max(1, 2)) = 4.
Constraints:
1 <= blocks.length <= 1000
1 <= blocks[i] <= 10^5
1 <= split <= 100
| class Solution:
def minBuildTime(self, blocks: List[int], split: int) -> int:
def cal(pos, cur_split, split):
return blocks[pos] + cur_split * split
blocks.sort()
n = len(blocks)
pos = n-1
cur_split = 0
q = [(cal(pos, cur_split, split), pos, cur_split)]
for i in range(len(blocks)-2, -1, -1):
_, pos, cur_split = heapq.heappop(q)
pos_1 = pos
pos_2 = i
cur_split += 1
heapq.heappush(q, (cal(pos_1, cur_split, split), pos_1, cur_split))
heapq.heappush(q, (cal(pos_2, cur_split, split), pos_2, cur_split))
res = -float('inf')
while q:
cur_val = heapq.heappop(q)
# print(cur_val)
res = max(res, cur_val[0])
return res
|
e3a602 | 369d0c | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].
Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.
Constraints:
n == satisfaction.length
1 <= n <= 500
-1000 <= satisfaction[i] <= 1000
| class Solution:
def maxSatisfaction(self, a: List[int]) -> int:
ret = 0
n = len(a)
a.sort()
tot = 0
s = 0
for i in range(n - 1, -1, -1):
tot += a[i]
s += tot
ret = max(ret, s)
return ret |
1568cb | 369d0c | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].
Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.
Constraints:
n == satisfaction.length
1 <= n <= 500
-1000 <= satisfaction[i] <= 1000
| class Solution(object):
def maxSatisfaction(self, satisfaction):
"""
:type satisfaction: List[int]
:rtype: int
"""
satisfaction.sort()
n = len(satisfaction)
inf = 1000000000
dp = [[-inf for i in range(n + 1)] for i in range(n + 1)]
dp[0][0] = 0
for i in range(n):
for j in range(n):
if dp[i][j] == -inf:
continue
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + (j + 1)*satisfaction[i])
return max(dp[n]) |
f8b851 | 5f7d05 | You are given an m x n integer matrix grid.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)
Example 3:
Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 100000
| class Solution:
def getBiggestThree(self, grid: List[List[int]]) -> List[int]:
n, m = len(grid), len(grid[0])
def good(a, b):
return 0<=a<n and 0<=b<m
s = set()
for i in range(n):
for j in range(m):
s.add(grid[i][j])
for k in range(1, min(n, m)):
try:
cur = 0
x, y = i, j
for z in range(k):
x += 1
y += 1
if x<0 or y<0:
bad = 1/0
cur += grid[x][y]
for z in range(k):
x += 1
y -= 1
if x<0 or y<0:
bad = 1/0
cur += grid[x][y]
for z in range(k):
x -= 1
y -= 1
if x<0 or y<0:
bad = 1/0
cur += grid[x][y]
for z in range(k):
x -= 1
y += 1
if x<0 or y<0:
bad = 1/0
cur += grid[x][y]
#print(i, j, k, cur)
s.add(cur)
except:
continue
l = list(s)
l.sort(reverse=True)
return l[:3] |
8d8270 | 5f7d05 | You are given an m x n integer matrix grid.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)
Example 3:
Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 100000
| class Solution(object):
def getBiggestThree(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[int]
"""
n=len(grid)
m=len(grid[0])
d={}
for i in range(n):
for j in range(m):
d[grid[i][j]]=0
for k in range(2,100,2):
x1,y1=i,j
x2,y2=i+k,j
x3,y3=i+k/2,j-k/2
x4,y4=i+k/2,j+k/2
if x2>=n or y3<0 or y4>=m:
break
summ=-grid[x1][y1]-grid[x2][y2]-grid[x3][y3]-grid[x4][y4]
for c in range(k/2+1):
summ+=grid[i+c][j+c]
summ+=grid[i+c][j-c]
summ+=grid[i+k-c][j+c]
summ+=grid[i+k-c][j-c]
d[summ]=0
arr=d.keys()
arr.sort()
arr=arr[::-1]
if len(arr)<3:
return arr
return arr[:3]
|
6d732f | b54337 | You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1
Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
| class Solution(object):
def findTargetSumWays(self, A, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
Cleft = collections.Counter()
Cright = collections.Counter()
N = len(A)
left = A[:N/2]
right = A[N/2:]
for cand in itertools.product(*[[-x,x] for x in left]):
Cleft[sum(cand)] += 1
for cand in itertools.product(*[[-x,x] for x in right]):
Cright[sum(cand)] += 1
ans = 0
for k,u in Cleft.iteritems():
if S-k in Cright:
ans += u * Cright[S-k]
return ans |
18df92 | cf776c | You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.
Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.
Return the minimum maximum difference among all p pairs.
Example 1:
Input: nums = [10,1,2,7,1,3], p = 2
Output: 1
Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
Example 2:
Input: nums = [4,2,1,2], p = 1
Output: 0
Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9
0 <= p <= (nums.length)/2
| class Solution(object):
def minimizeMax(self, nums, p):
"""
:type nums: List[int]
:type p: int
:rtype: int
"""
def q(m, p):
i = 0
while i < len(nums) - 1 and p > 0:
p, i = p if nums[i + 1] - nums[i] > m else p - 1, i + 1 if nums[i + 1] - nums[i] > m else i + 2
return p == 0
nums.sort()
s, e, a = 0, nums[-1] - nums[0], nums[-1] - nums[0]
while s <= e:
a, e, s = s + (e - s) / 2 if q(s + (e - s) / 2, p) else a, s + (e - s) / 2 - 1 if q(s + (e - s) / 2, p) else e, s if q(s + (e - s) / 2, p) else s + (e - s) / 2 + 1
return a |
337de7 | cf776c | You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.
Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.
Return the minimum maximum difference among all p pairs.
Example 1:
Input: nums = [10,1,2,7,1,3], p = 2
Output: 1
Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
Example 2:
Input: nums = [4,2,1,2], p = 1
Output: 0
Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9
0 <= p <= (nums.length)/2
| class Solution:
def minimizeMax(self, nums: List[int], p: int) -> int:
nums.sort()
n = len(nums)
x, y = 0, nums[-1] - nums[0]
res = y
while x <= y:
z = (x + y) >> 1
i = 0
cnt = 0
while i < n - 1 and cnt < p:
if nums[i+1] - nums[i] <= z:
cnt += 1
i += 2
else:
i += 1
if cnt >= p:
res = z
y = z - 1
else:
x = z + 1
return res |
911e12 | ca770d | You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"].
After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 10000
All the strings of products are unique.
products[i] consists of lowercase English letters.
1 <= searchWord.length <= 1000
searchWord consists of lowercase English letters.
| class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
prods=[p for p in products if p[0]==searchWord[0]]
can=[True]*len(prods)
prods.sort()
cur=prods[:3]
st_idx=0
ans=[cur]
for i in range(1,len(searchWord)):
l=searchWord[i]
if len(cur)<3 and len(prods)>=3:
prods=cur
can=[True]*len(prods)
st_idx=0
nxt=[]
start=False
for idx in range(st_idx,len(prods)):
valid=False
if can[idx]:
if i<len(prods[idx]) and prods[idx][i]==l:
valid=True
if valid:
start=True
if len(nxt)<3:
nxt.append(prods[idx])
else:
if not start:
st_idx+=1
can[idx]=False
cur=nxt
ans.append(cur)
return ans
|
dc34e7 | ca770d | You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"].
After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 10000
All the strings of products are unique.
products[i] consists of lowercase English letters.
1 <= searchWord.length <= 1000
searchWord consists of lowercase English letters.
| class Solution(object):
def suggestedProducts(self, products, searchWord):
"""
:type products: List[str]
:type searchWord: str
:rtype: List[List[str]]
"""
products.sort()
N = len(searchWord)
Ans = []
for i in range(N):
cnt = 0
M = len(products)
new_products = []
for j in range(M):
v = products[j]
l = len(v)
if l >= i+1 and v[i] == searchWord[i]:
new_products.append(v)
Ans.append(new_products[:3])
products = new_products
return Ans |
6d781e | 8de83b | You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: nums = [9,1,2,3,9], k = 3
Output: 20.00000
Explanation:
The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Example 2:
Input: nums = [1,2,3,4,5,6,7], k = 4
Output: 20.50000
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 10000
1 <= k <= nums.length
| class Solution:
def largestSumOfAverages(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: float
"""
a = A
n = len(a)
k = K
s = [0 for _ in range(n)]
s[0] = a[0]
for i in range(1, n):
s[i] = s[i - 1] + a[i]
f = [[None for _ in range(k + 1)] for _ in range(n)]
for i in range(n):
for j in range(1, k + 1):
if j > i + 1:
break
if j == 1:
f[i][j] = s[i] / (i + 1)
else:
for t in range(i):
if f[t][j - 1] is None:
continue
if f[i][j] is None or f[i][j] < f[t][j - 1] + (s[i] - s[t]) / (i - t):
f[i][j] = f[t][j - 1] + (s[i] - s[t]) / (i - t)
return f[n - 1][k]
|
7e518c | 8de83b | You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: nums = [9,1,2,3,9], k = 3
Output: 20.00000
Explanation:
The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Example 2:
Input: nums = [1,2,3,4,5,6,7], k = 4
Output: 20.50000
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 10000
1 <= k <= nums.length
| class Solution(object):
def largestSumOfAverages(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: float
"""
n=len(A)
ms=[0]*(n+1)
for i in range(n):
ms[i+1]=ms[i]+A[i]
dp=[[-float('inf')]*(K+1) for _ in range(n)]
for i in range(n):
dp[i][1]=1.0*ms[i+1]/(i+1)
for j in range(2,K+1):
for i in range(j-1,n):
for k in range(i):
dp[i][j]=max(dp[i][j],dp[k][j-1]+1.0*(ms[i+1]-ms[k+1])/(i-k))
return dp[n-1][K]
|
08b21a | d83d0c | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
You must find the minimum number of months needed to complete all the courses following these rules:
You may start taking a course at any time if the prerequisites are met.
Any number of courses can be taken at the same time.
Return the minimum number of months needed to complete all the courses.
Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
Example 1:
Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Explanation: The figure above represents the given graph and the time required to complete each course.
We start course 1 and course 2 simultaneously at month 0.
Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.
Example 2:
Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
Output: 12
Explanation: The figure above represents the given graph and the time required to complete each course.
You can start courses 1, 2, and 3 at month 0.
You can complete them after 1, 2, and 3 months respectively.
Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.
Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.
Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.
Constraints:
1 <= n <= 5 * 10000
0 <= relations.length <= min(n * (n - 1) / 2, 5 * 10000)
relations[j].length == 2
1 <= prevCoursej, nextCoursej <= n
prevCoursej != nextCoursej
All the pairs [prevCoursej, nextCoursej] are unique.
time.length == n
1 <= time[i] <= 10000
The given graph is a directed acyclic graph.
| class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
setrecursionlimit(1000000)
p = [[] for i in range(n)]
for i, j in relations:
p[j-1].append(i-1)
@cache
def ans(x):
res = 0
for i in p[x]:
res = max(res, ans(i))
return res+time[x]
r = 0
for i in range(n):
r = max(r, ans(i))
return r
|
370c28 | d83d0c | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
You must find the minimum number of months needed to complete all the courses following these rules:
You may start taking a course at any time if the prerequisites are met.
Any number of courses can be taken at the same time.
Return the minimum number of months needed to complete all the courses.
Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
Example 1:
Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Explanation: The figure above represents the given graph and the time required to complete each course.
We start course 1 and course 2 simultaneously at month 0.
Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.
Example 2:
Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
Output: 12
Explanation: The figure above represents the given graph and the time required to complete each course.
You can start courses 1, 2, and 3 at month 0.
You can complete them after 1, 2, and 3 months respectively.
Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.
Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.
Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.
Constraints:
1 <= n <= 5 * 10000
0 <= relations.length <= min(n * (n - 1) / 2, 5 * 10000)
relations[j].length == 2
1 <= prevCoursej, nextCoursej <= n
prevCoursej != nextCoursej
All the pairs [prevCoursej, nextCoursej] are unique.
time.length == n
1 <= time[i] <= 10000
The given graph is a directed acyclic graph.
| class Solution(object):
def minimumTime(self, n, relations, time):
"""
:type n: int
:type relations: List[List[int]]
:type time: List[int]
:rtype: int
"""
h = []
nei = {}
ind = [0]*(n+1)
for a, b in relations:
if a not in nei: nei[a]=set()
if b not in nei[a]:
ind[b]+=1
nei[a].add(b)
for i in range(1, n+1):
if ind[i]==0:
heappush(h, (time[i-1], i))
while h:
t, a = heappop(h)
if a in nei:
for b in nei[a]:
ind[b]-=1
if ind[b]==0:
heappush(h, (t+time[b-1], b))
return t |
be2e35 | eff9bf | You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:
0 represents grass,
1 represents fire,
2 represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.
Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 10^9.
Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.
A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Example 1:
Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]
Output: 3
Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.
You will still be able to safely reach the safehouse.
Staying for more than 3 minutes will not allow you to safely reach the safehouse.
Example 2:
Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
Output: -1
Explanation: The figure above shows the scenario where you immediately move towards the safehouse.
Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse.
Thus, -1 is returned.
Example 3:
Input: grid = [[0,0,0],[2,2,0],[1,2,0]]
Output: 1000000000
Explanation: The figure above shows the initial grid.
Notice that the fire is contained by walls and you will always be able to safely reach the safehouse.
Thus, 10^9 is returned.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 300
4 <= m * n <= 2 * 10000
grid[i][j] is either 0, 1, or 2.
grid[0][0] == grid[m - 1][n - 1] == 0
| class Solution:
def maximumMinutes(self, grid: List[List[int]]) -> int:
left = 0
right = 1000000000
R = len(grid)
C = len(grid[0])
INF = 10 ** 20
q = collections.deque()
dist = [[INF] * C for _ in range(R)]
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for i in range(R):
for j in range(C):
if grid[i][j] == 1:
dist[i][j] = 0
q.append((0, i, j))
while len(q) > 0:
d, x, y = q.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < R and 0 <= ny < C and dist[nx][ny] == INF and grid[nx][ny] != 2:
dist[nx][ny] = d + 1
q.append((d + 1, nx, ny))
def good(target):
q = collections.deque()
d2 = [[INF] * C for _ in range(R)]
if dist[0][0] <= target:
return False
q.append((target, 0, 0))
while len(q) > 0:
d, x, y = q.popleft()
#print(target, x, y, d)
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < R and 0 <= ny < C and grid[nx][ny] != 2 and d2[nx][ny] == INF and d + 1 < dist[nx][ny]:
d2[nx][ny] = d + 1
q.append((d + 1, nx, ny))
if nx == R - 1 and ny == C - 1:
return True
if nx == R - 1 and ny == C - 1 and grid[nx][ny] != 2 and d2[nx][ny] == INF and d + 1 <= dist[nx][ny]:
return True
return False
while left < right:
mid = (left + right + 1) // 2
if good(mid):
left = mid
else:
right = mid - 1
if left == 0:
if good(0):
return 0
else:
return -1
return left
|
5ef3d6 | eff9bf | You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:
0 represents grass,
1 represents fire,
2 represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.
Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 10^9.
Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.
A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Example 1:
Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]
Output: 3
Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.
You will still be able to safely reach the safehouse.
Staying for more than 3 minutes will not allow you to safely reach the safehouse.
Example 2:
Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
Output: -1
Explanation: The figure above shows the scenario where you immediately move towards the safehouse.
Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse.
Thus, -1 is returned.
Example 3:
Input: grid = [[0,0,0],[2,2,0],[1,2,0]]
Output: 1000000000
Explanation: The figure above shows the initial grid.
Notice that the fire is contained by walls and you will always be able to safely reach the safehouse.
Thus, 10^9 is returned.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 300
4 <= m * n <= 2 * 10000
grid[i][j] is either 0, 1, or 2.
grid[0][0] == grid[m - 1][n - 1] == 0
| class Solution(object):
def maximumMinutes(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m=len(grid)
n=len(grid[0])
time=[[float('inf')]*n for i in range(m)]
now=[]
for i in range(m):
for j in range(n):
if grid[i][j]==1:
now.append([i,j])
time[i][j]=0
next=[]
t=1
while now!=[]:
for k in now:
i=k[0]
j=k[1]
if i<m-1 and grid[i+1][j]!=2 and time[i+1][j]==float('inf'):
next.append([i+1,j])
time[i+1][j]=t
if i>0 and grid[i-1][j]!=2 and time[i-1][j]==float('inf'):
next.append([i-1,j])
time[i-1][j]=t
if j<n-1 and grid[i][j+1]!=2 and time[i][j+1]==float('inf'):
next.append([i,j+1])
time[i][j+1]=t
if j>0 and grid[i][j-1]!=2 and time[i][j-1]==float('inf'):
next.append([i,j-1])
time[i][j-1]=t
now=next[:]
next=[]
t+=1
step=1
max_wait=-1
now=[[0,0,float('inf')]]
check=[[0]*n for i in range(m)]
check[0][0]=1
while now!=[]:
for k in now:
i=k[0]
j=k[1]
wait=k[2]
if i<m-1 and grid[i+1][j]!=2 and check[i+1][j]==0:
if i+1==m-1 and j==n-1:
wait=min(wait,time[i+1][j]-step)
max_wait=max(max_wait,wait)
else:
check[i+1][j]=1
wait=min(wait,time[i+1][j]-1-step)
if wait>=0:
next.append([i+1,j,wait])
wait=k[2]
if i>0 and grid[i-1][j]!=2 and check[i-1][j]==0:
check[i-1][j]=1
wait=min(wait,time[i-1][j]-1-step)
if wait>=0:
next.append([i-1,j,wait])
wait=k[2]
if j<n-1 and grid[i][j+1]!=2 and check[i][j+1]==0:
if i==m-1 and j+1==n-1:
wait=min(wait,time[i][j+1]-step)
max_wait=max(max_wait,wait)
else:
check[i][j+1]=1
wait=min(wait,time[i][j+1]-1-step)
if wait>=0:
next.append([i,j+1,wait])
wait=k[2]
if j>0 and grid[i][j-1]!=2 and check[i][j-1]==0:
check[i][j-1]=1
wait=min(wait,time[i][j-1]-1-step)
if wait>=0:
next.append([i,j-1,wait])
now=next[:]
next=[]
step+=1
print(check)
if max_wait==float('inf'):
return 1000000000
else:
return max_wait |
3c9b19 | 9d60b5 | Given two strings s and t, transform string s into string t using the following operation any number of times:
Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
For example, applying the operation on the underlined substring in "14234" results in "12344".
Return true if it is possible to transform s into t. Otherwise, return false.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "84532", t = "34852"
Output: true
Explanation: You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -> "84352"
"84352" (from index 0 to 2) -> "34852"
Example 2:
Input: s = "34521", t = "23415"
Output: true
Explanation: You can transform s into t using the following sort operations:
"34521" -> "23451"
"23451" -> "23415"
Example 3:
Input: s = "12345", t = "12435"
Output: false
Constraints:
s.length == t.length
1 <= s.length <= 100000
s and t consist of only digits.
| class Solution:
def isTransformable(self, s: str, t: str) -> bool:
counter_s = collections.Counter(s)
counter_t = collections.Counter(t)
for i in '0123456789' :
if not counter_s[i] == counter_t[i] :
return False
rcounters_s = collections.defaultdict(lambda:0)
rcounters_t = collections.defaultdict(lambda:0)
counters0 = collections.Counter()
for c in s :
ic = int(c)
for i in range(ic+1, 10) :
rcounters_s[(ic, i)] += counters0[i]
counters0[ic] += 1
counters0 = collections.Counter()
for c in t :
ic = int(c)
for i in range(ic+1, 10) :
rcounters_t[(ic, i)] += counters0[i]
counters0[ic] += 1
# print({t:rcounters_s[t] for t in rcounters_s if not rcounters_s[t]==0})
# print({t:rcounters_t[t] for t in rcounters_t if not rcounters_t[t]==0})
for t in rcounters_t :
if rcounters_t[t] > rcounters_s[t] :
return False
return True
|
e854ca | 9d60b5 | Given two strings s and t, transform string s into string t using the following operation any number of times:
Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
For example, applying the operation on the underlined substring in "14234" results in "12344".
Return true if it is possible to transform s into t. Otherwise, return false.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "84532", t = "34852"
Output: true
Explanation: You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -> "84352"
"84352" (from index 0 to 2) -> "34852"
Example 2:
Input: s = "34521", t = "23415"
Output: true
Explanation: You can transform s into t using the following sort operations:
"34521" -> "23451"
"23451" -> "23415"
Example 3:
Input: s = "12345", t = "12435"
Output: false
Constraints:
s.length == t.length
1 <= s.length <= 100000
s and t consist of only digits.
| class Solution(object):
def isTransformable(self, S, T):
A = map(int, S)
B = map(int, T)
prev = -1
count = [0] * 10
anchor = 0
for i, x in enumerate(B):
count[x] += 1
if i == len(B) - 1 or not(B[i + 1] >= B[i]):
# catchup A[anchor..i]
# print("catch", anchor, i)
countA = [0] * 10
countA2 = [0] * 10
first_loss = None
for j in xrange(anchor, i + 1):
y = A[j]
if countA[y] + 1 <= count[y]:
countA[y] += 1
else:
countA2[y] += 1
if first_loss is None:
first_loss = j
# print("FL", first_loss)
if first_loss is not None:
# continue to catch up
todo = sum(countA[k] < count[k] for k in xrange(10))
for j in xrange(i + 1, len(A)):
y = A[j]
countA[y] += 1
if countA[y] == count[y]:
todo -= 1
if todo == 0:
# know we have to sort first_loss to j
vals = sorted(A[k] for k in xrange(first_loss, j + 1))
for k, v in enumerate(vals):
A[first_loss + k] = v
# now count again
countA = [0] * 10
for k in xrange(anchor, i + 1):
y = A[k]
countA[y] += 1
if countA != count:
return False
break
else:
return False
anchor = i + 1
for k in xrange(10): count[k] = 0
if anchor != len(A):
# catch up anchor..len(A) - 1
i = len(A) - 1
# catchup A[anchor..i]
# print("catch", anchor, i)
countA = [0] * 10
countA2 = [0] * 10
first_loss = None
for j in xrange(anchor, i + 1):
y = A[j]
if countA[y] + 1 <= count[y]:
countA[y] += 1
else:
countA2[y] += 1
if first_loss is None:
first_loss = j
# print("FL", first_loss)
if first_loss is not None:
# continue to catch up
todo = sum(countA[k] < count[k] for k in xrange(10))
for j in xrange(i + 1, len(A)):
y = A[j]
countA[y] += 1
if countA[y] == count[y]:
todo -= 1
if todo == 0:
# know we have to sort first_loss to j
vals = sorted(A[k] for k in xrange(first_loss, j + 1))
for k, v in enumerate(vals):
A[first_loss + k] = v
# now count again
countA = [0] * 10
for k in xrange(anchor, i + 1):
y = A[k]
countA[y] += 1
if countA != count:
return False
break
else:
return False
return True |
e68756 | 6a0dc6 | You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr has exactly n integers.
1 <= arr[i] <= m where (0 <= i < n).
After applying the mentioned algorithm to arr, the value search_cost is equal to k.
Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: n = 2, m = 3, k = 1
Output: 6
Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
Example 2:
Input: n = 5, m = 2, k = 3
Output: 0
Explanation: There are no possible arrays that satisify the mentioned conditions.
Example 3:
Input: n = 9, m = 1, k = 1
Output: 1
Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n
| class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
@lru_cache(None)
def f(i, mx, cmp):
if i == n:
if cmp == 0:
return 1
else:
return 0
elif cmp < 0:
return 0
else:
ret = 0
for mm in range(1, m + 1):
if mm > mx:
ret += f(i + 1, mm, cmp - 1)
else:
ret += f(i + 1, mx, cmp)
ret %= 1000000007
return ret
return f(0, -1, k) |
c7a12b | 6a0dc6 | You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr has exactly n integers.
1 <= arr[i] <= m where (0 <= i < n).
After applying the mentioned algorithm to arr, the value search_cost is equal to k.
Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: n = 2, m = 3, k = 1
Output: 6
Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
Example 2:
Input: n = 5, m = 2, k = 3
Output: 0
Explanation: There are no possible arrays that satisify the mentioned conditions.
Example 3:
Input: n = 9, m = 1, k = 1
Output: 1
Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n
| class Solution(object):
def numOfArrays(self, n, m, k):
"""
:type n: int
:type m: int
:type k: int
:rtype: int
"""
M = 10**9+7
f = [[0]*m for _ in xrange(k)]
f[0] = [1]*m
for _ in xrange(n-1):
for i in xrange(k-1, -1, -1):
s = 0
for j in xrange(m):
f[i][j] = (f[i][j]*(j+1) + s) % M
if i: s += f[i-1][j]
return sum(f[-1]) % M |
5b3ba0 | 013189 | A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.
For example, 321 is a stepping number while 421 is not.
Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].
Example 1:
Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]
Example 2:
Input: low = 10, high = 15
Output: [10,12]
Constraints:
0 <= low <= high <= 2 * 10^9
| class Solution(object):
def countSteppingNumbers(self, low, high):
ans = set()
def search(x):
if x > high: return
if x >= low: ans.add(x)
last = x % 10
for d in (last-1, last+1):
if 0 <= d < 10:
search(10 * x + d)
for d in range(10): search(d)
return sorted(ans) |
efa5da | 013189 | A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.
For example, 321 is a stepping number while 421 is not.
Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].
Example 1:
Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]
Example 2:
Input: low = 10, high = 15
Output: [10,12]
Constraints:
0 <= low <= high <= 2 * 10^9
| from typing import List
class Solution:
def countSteppingNumbers(self, low: int, high: int) -> List[int]:
ans = []
def helper(num):
if low <= num <= high:
ans.append(num)
if num == 0:
return
if num > high:
return
last = num % 10
next_1 = num * 10 + last - 1
next_2 = num * 10 + last + 1
if last == 0:
helper(next_2)
elif last == 9:
helper(next_1)
else:
helper(next_1)
helper(next_2)
for i in range(10):
helper(i)
ans.sort()
return ans
|
19dc46 | 967e02 | Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
Example 1:
Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: nums = [-1,3,2,0]
Output: true
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
Constraints:
n == nums.length
1 <= n <= 2 * 100000
-10^9 <= nums[i] <= 10^9
| class Solution(object):
def find132pattern(self, nums):
if not nums:
return False
maxafter = []
minbefore = [0] * len(nums)
for i in range(len(nums)):
while maxafter and nums[maxafter[-1]] <= nums[i]:
maxafter.pop(-1)
if maxafter and minbefore[maxafter[-1]] < nums[i]:
return True
maxafter.append(i)
if i==0 or minbefore[i-1] > nums[i]:
minbefore[i] = nums[i]
else:
minbefore[i] = minbefore[i-1]
return False
"""
:type nums: List[int]
:rtype: bool
"""
|
eee60a | e58820 | There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
Input: s = "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
| class Solution(object):
def strangePrinter(self, s):
"""
:type s: str
:rtype: int
"""
if s=='': return 0
while True:
flag = True
for i in range(len(s)-1):
if s[i] == s[i+1]:
s = s[:i] + s[i+1:]
flag = False
break
if flag: break
n = len(s)
dp = [ [200]* n for i in range(n) ]
for l in range(0,n):
for start in range(n-l):
if l==0:
dp[start][start] = 1
else:
for k in range(start,start+l):
dp[start][start+l] = min(dp[start][start+l], dp[start][k]+dp[k+1][start+l])
if s[start] == s[start+l]:
dp[start][start+l] -=1
return dp[0][n-1]
|
62f6f9 | e58820 | There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
Input: s = "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
| class Solution:
def strangePrinter(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
L = len(s)
dp = [[0 for i in range(L)] for j in range(L)]
for i in range(L):
dp[i][i] = 1
for d in range(1, L):
for i in range(L - d):
# try to get dp[i][i+d]
dp[i][i+d] = 1 + dp[i+1][i+d]
if s[i] == s[i+1]:
dp[i][i+d] = dp[i+1][i+d]
else:
for j in range(2, d+1):
if s[i] == s[i+j]:
dp[i][i+d] = min(dp[i][i+d], dp[i+1][i+j-1] + dp[i+j][i+d])
return dp[0][L-1] |
605294 | 7abede | There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.
You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.
For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.
The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.
For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.
Note: There will be no obstacles on points 0 and n.
Example 1:
Input: obstacles = [0,1,2,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
Example 2:
Input: obstacles = [0,1,1,3,3,0]
Output: 0
Explanation: There are no obstacles on lane 2. No side jumps are required.
Example 3:
Input: obstacles = [0,2,1,0,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.
Constraints:
obstacles.length == n + 1
1 <= n <= 5 * 100000
0 <= obstacles[i] <= 3
obstacles[0] == obstacles[n] == 0
| class Solution:
def minSideJumps(self, obstacles: List[int]) -> int:
get_key = lambda x, y: x*3+y-1
visited = set([get_key(0, 2)])
heap = [(0, 0, 2)]
while len(heap) > 0 :
ct, px, py = heapq.heappop(heap)
if px == len(obstacles)-1 :
return ct
to_visit = []
if not obstacles[px+1] == py :
to_visit.append([ct, px+1, py])
for tt in [1,2,3] :
if not obstacles[px] == tt :
to_visit.append([ct+1, px, tt])
for nct, nx, ny in to_visit :
kt = get_key(nx, ny)
if kt in visited :
continue
visited.add(kt)
heapq.heappush(heap, (nct, nx, ny))
|
85fe64 | 7abede | There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.
You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.
For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.
The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.
For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.
Note: There will be no obstacles on points 0 and n.
Example 1:
Input: obstacles = [0,1,2,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
Example 2:
Input: obstacles = [0,1,1,3,3,0]
Output: 0
Explanation: There are no obstacles on lane 2. No side jumps are required.
Example 3:
Input: obstacles = [0,2,1,0,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.
Constraints:
obstacles.length == n + 1
1 <= n <= 5 * 100000
0 <= obstacles[i] <= 3
obstacles[0] == obstacles[n] == 0
| class Solution(object):
def minSideJumps(self, obstacles):
"""
:type obstacles: List[int]
:rtype: int
"""
n = len(obstacles)
memo = [[[None] * 2 for _lane in xrange(3)] for _pos in xrange(n)]
for lane in xrange(3):
memo[-1][lane][0] = 0
memo[-1][lane][1] = 0
if obstacles[-1] != 0:
memo[-1][obstacles[-1]-1][0] = float('inf')
memo[-1][obstacles[-1]-1][1] = float('inf')
for i in xrange(n-2,-1,-1):
for lane in xrange(3):
memo[i][lane][0] = memo[i+1][lane][1]
if obstacles[i] != 0:
memo[i][obstacles[i]-1][0] = float('inf')
for lane in xrange(3):
memo[i][lane][1] = min(memo[i][lane][0], 1 + memo[i][(lane+1)%3][0], 1 + memo[i][(lane+2)%3][0])
if obstacles[i] != 0:
memo[i][obstacles[i]-1][1] = float('inf')
return memo[0][1][1] |
3fb9e5 | 469fb4 | Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
Example 1:
Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:
Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
n == colors.length == neededTime.length
1 <= n <= 100000
1 <= neededTime[i] <= 10000
colors contains only lowercase English letters.
| class Solution(object):
def minCost(self, S, cost):
ans = i = 0
for k, grp in itertools.groupby(S):
A = list(grp)
W = len(A)
if len(A) == 1:
i += W
continue
m = max(cost[i+j] for j in xrange(W))
s = sum(cost[i+j] for j in xrange(W))
s -= m
ans += s
i += W
return ans |
ec7481 | 469fb4 | Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
Example 1:
Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:
Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
n == colors.length == neededTime.length
1 <= n <= 100000
1 <= neededTime[i] <= 10000
colors contains only lowercase English letters.
| class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
index = 0
c = 0
for k, g in groupby(s):
x = len(list(g))
c += sum(cost[index:index+x]) - max(cost[index:index+x])
index += x
return c |
41ff6e | 3b0130 | You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.
Return the number of unoccupied cells that are not guarded.
Example 1:
Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
Example 2:
Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]
Output: 4
Explanation: The unguarded cells are shown in green in the above diagram.
There are a total of 4 unguarded cells, so we return 4.
Constraints:
1 <= m, n <= 100000
2 <= m * n <= 100000
1 <= guards.length, walls.length <= 5 * 10000
2 <= guards.length + walls.length <= m * n
guards[i].length == walls[j].length == 2
0 <= rowi, rowj < m
0 <= coli, colj < n
All the positions in guards and walls are unique.
| class Solution:
def countUnguarded(self, R: int, C: int, guards: List[List[int]], walls: List[List[int]]) -> int:
state = [[0] * C for _ in range(R)]
GUARD = 1
WALL = 2
USED = 3
for x, y in guards:
state[x][y] = GUARD
for x, y in walls:
state[x][y] = WALL
for i in range(R):
current = 0
for j in range(C):
if state[i][j] == GUARD:
current = USED
elif state[i][j] == WALL:
current = 0
elif state[i][j] == 0:
if current == USED:
state[i][j] = USED
for i in range(R):
current = 0
for j in range(C - 1, -1, -1):
if state[i][j] == GUARD:
current = USED
elif state[i][j] == WALL:
current = 0
elif state[i][j] == 0:
if current == USED:
state[i][j] = USED
for j in range(C):
current = 0
for i in range(R):
if state[i][j] == GUARD:
current = USED
elif state[i][j] == WALL:
current = 0
elif state[i][j] == 0:
if current == USED:
state[i][j] = USED
for j in range(C):
current = 0
for i in range(R - 1, -1, -1):
if state[i][j] == GUARD:
current = USED
elif state[i][j] == WALL:
current = 0
elif state[i][j] == 0:
if current == USED:
state[i][j] = USED
count = 0
for i in range(R):
for j in range(C):
if state[i][j] == 0:
count += 1
return count
|
57d442 | 3b0130 | You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.
Return the number of unoccupied cells that are not guarded.
Example 1:
Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
Example 2:
Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]
Output: 4
Explanation: The unguarded cells are shown in green in the above diagram.
There are a total of 4 unguarded cells, so we return 4.
Constraints:
1 <= m, n <= 100000
2 <= m * n <= 100000
1 <= guards.length, walls.length <= 5 * 10000
2 <= guards.length + walls.length <= m * n
guards[i].length == walls[j].length == 2
0 <= rowi, rowj < m
0 <= coli, colj < n
All the positions in guards and walls are unique.
| class Solution(object):
def countUnguarded(self, m, n, guards, walls):
"""
:type m: int
:type n: int
:type guards: List[List[int]]
:type walls: List[List[int]]
:rtype: int
"""
grid=[[0]*n for i in range(m)]
for k in walls:
grid[k[0]][k[1]]=1
for k in guards:
grid[k[0]][k[1]]=2
for i in range(m):
flag=0
for j in range(n):
if grid[i][j]==2:
flag=3
elif grid[i][j]==1:
flag=0
else:
grid[i][j]=flag
flag=0
for j in range(n-1,-1,-1):
if grid[i][j]==2:
flag=3
elif grid[i][j]==1:
flag=0
elif grid[i][j]==3:
continue
else:
grid[i][j]=flag
count=0
for j in range(n):
flag=0
for i in range(m):
if grid[i][j]==2:
flag=3
elif grid[i][j]==1:
flag=0
elif grid[i][j]==3:
continue
else:
grid[i][j]=flag
flag=0
for i in range(m-1,-1,-1):
if grid[i][j]==2:
flag=3
elif grid[i][j]==1:
flag=0
elif grid[i][j]==0:
grid[i][j]=flag
if grid[i][j]==0:
count+=1
return count |
658f32 | 3f5a6b | Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When you get an instruction 'R', your car does the following:
If your speed is positive then speed = -1
otherwise speed = 1
Your position stays the same.
For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.
Given a target position target, return the length of the shortest sequence of instructions to get there.
Example 1:
Input: target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0 --> 1 --> 3.
Example 2:
Input: target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
Constraints:
1 <= target <= 10000
| class Solution(object):
def racecar(self, target):
"""
:type target: int
:rtype: int
"""
curset=set([])
curset.add((0,1))
allset=set([])
allset.add((0,1))
t=0
while curset:
t+=1
nextset=set([])
for (p,v) in curset:
np=p+v
if abs(np)<=target*3:
if np==target: return t
nv=v*2
if (np,nv) in allset: continue
allset.add((np,nv))
nextset.add((np,nv))
np=p
if v>0: nv=-1
else: nv=1
if (np,nv) in allset: continue
allset.add((np,nv))
nextset.add((np,nv))
curset=nextset
return -1
|
d7d84a | 3f5a6b | Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When you get an instruction 'R', your car does the following:
If your speed is positive then speed = -1
otherwise speed = 1
Your position stays the same.
For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.
Given a target position target, return the length of the shortest sequence of instructions to get there.
Example 1:
Input: target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0 --> 1 --> 3.
Example 2:
Input: target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
Constraints:
1 <= target <= 10000
| class Solution:
def racecar(self, target):
"""
:type target: int
:rtype: int
"""
dic = {}
q = [(0, 1, 0)]
dic[(0, 1)] = True
while q:
cur = q.pop(0)
if cur[0] == target:
return cur[2]
rs = -1 if cur[1] > 0 else 1
if (cur[0], rs) not in dic:
q.append((cur[0], rs, cur[2] + 1))
dic[(cur[0], rs)] = True
np = cur[0] + cur[1]
ns = cur[1] * 2
if np > 0 and np < 20000 and (np, ns) not in dic:
q.append((np, ns, cur[2] + 1))
dic[(np, ns)] = True
|
ea1949 | 8ba73f | A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.
Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.
Notes:
You can go through any vertex any number of times, including 1 and n.
You can assume that when the journey starts, all signals have just turned green.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input: n = 2, edges = [[1,2]], time = 3, change = 2
Output: 11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 10000
n - 1 <= edges.length <= min(2 * 10000, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 103
| class Solution:
def secondMinimum(self, n: int, adj: List[List[int]], time: int, change: int) -> int:
edges = [[] for i in range(n)]
for i, j in adj:
edges[i-1].append(j-1)
edges[j-1].append(i-1)
dist = [-1]*n
dist2 = [-1]*n
q = deque()
q.append(0)
dist[0] = 0
while len(q):
cur = q.popleft()
for i in edges[cur]:
if dist[i] == -1:
dist[i] = dist[cur]+1
q.append(i)
q = deque()
q.append(n-1)
dist2[n-1] = 0
while len(q):
cur = q.popleft()
for i in edges[cur]:
if dist2[i] == -1:
dist2[i] = dist2[cur]+1
q.append(i)
res = 10**18
for i, j in adj:
x, y = i-1, j-1
if dist[x]+dist2[y]+1 > dist[n-1]:
res = min(res, dist[x]+dist2[y]+1)
if dist2[x]+dist[y]+1 > dist[n-1]:
res = min(res, dist2[x]+dist[y]+1)
cur = 0
for i in range(res):
if cur%(2*change) >= change:
cur = (cur//(2*change)+1)*(2*change)
cur += time
return cur
|
f5f780 | 8ba73f | A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.
Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.
Notes:
You can go through any vertex any number of times, including 1 and n.
You can assume that when the journey starts, all signals have just turned green.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input: n = 2, edges = [[1,2]], time = 3, change = 2
Output: 11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 10000
n - 1 <= edges.length <= min(2 * 10000, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 103
| from collections import deque
class Solution(object):
def secondMinimum(self, n, edges, time, change):
"""
:type n: int
:type edges: List[List[int]]
:type time: int
:type change: int
:rtype: int
"""
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
dst = [[float('inf')]*n, [float('inf')]*n]
q = deque()
def _consider(u, du):
if dst[du&1][u] <= du:
return
dst[du&1][u] = du
q.append((u, du))
_consider(0, 0)
while q:
u, du = q.popleft()
if dst[du&1][u] < du:
continue
for v in adj[u]:
_consider(v, du+1)
d0, d1 = sorted([dst[0][n-1], dst[1][n-1]])
d = min(d0+2, d1) if d1 < float('inf') else d0 + 2
t = 0
for i in xrange(d):
if (t // change) & 1:
t += change - (t % change)
t += time
return t |
2f1f77 | f0bde1 | You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Example 1:
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].
Example 2:
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].
Constraints:
n == nums.length
m == operations.length
1 <= n, m <= 100000
All the values of nums are distinct.
operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 1000000
operations[i][0] will exist in nums when applying the ith operation.
operations[i][1] will not exist in nums when applying the ith operation.
| class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
pos = {}
n = len(nums)
for i in range(n):
pos[nums[i]] = i
for i, j in operations:
pos[j] = pos[i]
del pos[i]
res = [0] * n
for i, j in pos.items():
res[j] = i
return res |
a0ae95 | f0bde1 | You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Example 1:
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].
Example 2:
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].
Constraints:
n == nums.length
m == operations.length
1 <= n, m <= 100000
All the values of nums are distinct.
operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 1000000
operations[i][0] will exist in nums when applying the ith operation.
operations[i][1] will not exist in nums when applying the ith operation.
| class Solution(object):
def arrayChange(self, nums, operations):
"""
:type nums: List[int]
:type operations: List[List[int]]
:rtype: List[int]
"""
s = {}
for i in range(0, len(nums)):
s[nums[i]] = i
for o, p in operations:
nums[s[o]], s[p] = p, s[o]
return nums |
fd7edc | 2cfc67 | You are given an array nums consisting of positive integers.
You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:
Increase or decrease an element of the array by 1.
Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].
Note that after each query the array is reset to its original state.
Example 1:
Input: nums = [3,1,6,8], queries = [1,5]
Output: [14,10]
Explanation: For the first query we can do the following operations:
- Decrease nums[0] 2 times, so that nums = [1,1,6,8].
- Decrease nums[2] 5 times, so that nums = [1,1,1,8].
- Decrease nums[3] 7 times, so that nums = [1,1,1,1].
So the total number of operations for the first query is 2 + 5 + 7 = 14.
For the second query we can do the following operations:
- Increase nums[0] 2 times, so that nums = [5,1,6,8].
- Increase nums[1] 4 times, so that nums = [5,5,6,8].
- Decrease nums[2] 1 time, so that nums = [5,5,5,8].
- Decrease nums[3] 3 times, so that nums = [5,5,5,5].
So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10.
Example 2:
Input: nums = [2,9,6,3], queries = [10]
Output: [20]
Explanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.
Constraints:
n == nums.length
m == queries.length
1 <= n, m <= 100000
1 <= nums[i], queries[i] <= 10^9
| class Solution:
def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:
nums = sorted(nums)
n = len(nums)
pre_sum = [0]
for t in nums :
pre_sum.append(pre_sum[-1]+t)
to_ret = []
for t in queries :
pt = bisect.bisect(nums, t+.1)
part_1 = t * pt - pre_sum[pt]
part_2 = (pre_sum[-1]-pre_sum[pt]) - t * (n-pt)
to_ret.append(part_1+part_2)
return to_ret |
926449 | 2cfc67 | You are given an array nums consisting of positive integers.
You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:
Increase or decrease an element of the array by 1.
Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].
Note that after each query the array is reset to its original state.
Example 1:
Input: nums = [3,1,6,8], queries = [1,5]
Output: [14,10]
Explanation: For the first query we can do the following operations:
- Decrease nums[0] 2 times, so that nums = [1,1,6,8].
- Decrease nums[2] 5 times, so that nums = [1,1,1,8].
- Decrease nums[3] 7 times, so that nums = [1,1,1,1].
So the total number of operations for the first query is 2 + 5 + 7 = 14.
For the second query we can do the following operations:
- Increase nums[0] 2 times, so that nums = [5,1,6,8].
- Increase nums[1] 4 times, so that nums = [5,5,6,8].
- Decrease nums[2] 1 time, so that nums = [5,5,5,8].
- Decrease nums[3] 3 times, so that nums = [5,5,5,5].
So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10.
Example 2:
Input: nums = [2,9,6,3], queries = [10]
Output: [20]
Explanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.
Constraints:
n == nums.length
m == queries.length
1 <= n, m <= 100000
1 <= nums[i], queries[i] <= 10^9
| class Solution(object):
def minOperations(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[int]
:rtype: List[int]
"""
nums.sort()
p, a = [0] * (len(nums) + 1), []
for i in range(len(nums)):
p[i + 1] = p[i] + nums[i]
for i in range(len(queries)):
s, e, j = 0, len(nums) - 1, 0
while s <= e:
j, s, e = s + (e - s) / 2 if nums[s + (e - s) / 2] > queries[i] else s + (e - s) / 2 + 1, s if nums[s + (e - s) / 2] > queries[i] else s + (e - s) / 2 + 1, s + (e - s) / 2 - 1 if nums[s + (e - s) / 2] > queries[i] else e
a.append(1 * queries[i] * j - p[s] + p[len(nums)] - p[j] - queries[i] * (len(nums) - j))
return a |
90d41d | 32f9bf | Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.
Example 1:
Input: root = [5,10,10,null,null,2,3]
Output: true
Example 2:
Input: root = [1,2,10,null,null,2,20]
Output: false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
Constraints:
The number of nodes in the tree is in the range [1, 10000].
-100000 <= Node.val <= 100000
| # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def dfs(self, r):
if r is None:
return 0
return r.val + self.dfs(r.left) + self.dfs(r.right)
def f(self, r):
if r is None:
return 0
v = r.val + self.f(r.left) + self.f(r.right)
if v == self.target:
self.ans = True
return v
def checkEqualTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
s = self.dfs(root)
if s % 2 != 0:
return False
self.target = s / 2
self.ans = False
self.f(root.left)
self.f(root.right)
return self.ans
|
b165fc | 32f9bf | Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.
Example 1:
Input: root = [5,10,10,null,null,2,3]
Output: true
Example 2:
Input: root = [1,2,10,null,null,2,20]
Output: false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
Constraints:
The number of nodes in the tree is in the range [1, 10000].
-100000 <= Node.val <= 100000
| class Solution:
def checkEqualTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
my_set = set()
def calculate_sum(root):
if root is None:
return 0
else:
l = calculate_sum(root.left)
r = calculate_sum(root.right)
s = l + r + root.val
my_set.add(s)
return s
l = calculate_sum(root.left)
r = calculate_sum(root.right)
total = l + r + root.val
if total/2.0 in my_set:
return True
else:
return False |
2f1c61 | 7c99c6 | Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
Example 1:
Input: k = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
Example 2:
Input: k = 5
Output: 0
Explanation: There is no x such that x! ends in k = 5 zeroes.
Example 3:
Input: k = 3
Output: 5
Constraints:
0 <= k <= 10^9
|
class Solution:
def chk(self, v):
ans = 0
while v > 0:
ans += int(v / 5)
v = int(v / 5)
return ans
def fnd(self, k):
l = 0
r = k * 1000
while l < r:
mid = int((l + r) / 2)
if self.chk(mid) < k:
l = mid + 1
else:
r = mid
return l
def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
"""
return self.fnd(K + 1) - self.fnd(K)
|
a8e183 | 7c99c6 | Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
Example 1:
Input: k = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
Example 2:
Input: k = 5
Output: 0
Explanation: There is no x such that x! ends in k = 5 zeroes.
Example 3:
Input: k = 3
Output: 5
Constraints:
0 <= k <= 10^9
| class Solution(object):
def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
"""
if self.check(K): return 5
return 0
def check(self, K):
left=0
right=1000000000
while left<=right:
mid=left+(right-left)/2
x=mid
base=5
while mid>=base:
x+=mid/base
base*=5
if x==K: return True
if x<K: left=mid+1
else: right=mid-1
return False |
eed2bd | bb9e11 | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner (0, cols - 1).
Return the maximum number of cherries collection using both robots by following the rules below:
From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
When both robots stay in the same cell, only one takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in grid.
Example 1:
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100
| class Solution:
def cherryPickup(self, A):
R, C=len(A), len(A[0])
from functools import lru_cache
@lru_cache(None)
def dp(r,c1,c2):
if r == R: return 0
ans = 0
for d1 in (-1, 0, 1):
c1new = c1 + d1
if 0 <= c1new < C:
for d2 in (-1, 0, 1):
c2new = c2 + d2
if 0 <= c2new < C:
ans = max(ans, dp(r+1, c1new, c2new))
base = A[r][c1]
if c1 != c2:
base += A[r][c2]
return ans + base
return dp(0,0,C-1) |
da3a6a | bb9e11 | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner (0, cols - 1).
Return the maximum number of cherries collection using both robots by following the rules below:
From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
When both robots stay in the same cell, only one takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in grid.
Example 1:
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100
| class Solution(object):
def cherryPickup(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
dp = {}
n, m = len(grid), len(grid[0])
if n==0: return 0;
def dfs(i, j, d, n, m):
if d==n-1: return 0
k = (i, j, d)
if k in dp: return dp[k]
r = 0
for s1 in range(-1, 2, 1):
ni = i+s1
if ni<0 or ni>=m: continue
for s2 in range(-1, 2, 1):
nj = j+s2
if nj<0 or nj>=m: continue
vc = grid[d+1][ni]
if ni!=nj: vc+=grid[d+1][nj]
t = vc+dfs(ni, nj, d+1, n, m)
if r<t: r=t
dp[k]=r
return r
v=grid[0][0];
if m>1: v+=grid[0][m-1]
v += dfs(0, m-1, 0, n, m)
return v
|
690483 | 326167 | You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 100000
1 <= nums1[i], nums2[i] <= 6
| class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1)
s2 = sum(nums2)
if s1 == s2:
return 0
if s1 > s2:
return self.minOperations(nums2, nums1)
c1 = Counter(nums1)
c2 = Counter(nums2)
# s1 < s2 holds
need = 0
diff = s2 - s1
# print(c1, c2, diff)
for delta in range(1, 5 + 1):
if delta in c1:
for _ in range(c1[delta]):
need += 1
diff -= 6 - delta
# print(diff)
if diff <= 0:
break
if diff <= 0:
break
if 7 - delta in c2:
for _ in range(c2[7 - delta]):
need += 1
diff -= 6 - delta
# print(diff)
if diff <= 0:
break
if diff <= 0:
break
return -1 if diff > 0 else need |
474b15 | 326167 | You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 100000
1 <= nums1[i], nums2[i] <= 6
| class Solution(object):
def minOperations(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
d = sum(nums1) - sum(nums2)
if d < 0:
nums1, nums2 = nums2, nums1
d = -d
if len(nums1)*1 > len(nums2)*6:
return -1
p = [0] * 6
for x in nums1: p[x-1] += 1
for x in nums2: p[6-x] += 1
r = 0
for i in xrange(5, 0, -1):
v = min(p[i], (d+i-1)//i)
d -= i * v
r += v
if d < 0: break
return r |
f6460a | b2dd1c | You are given an integer array nums, and you can perform the following operation any number of times on nums:
Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j].
Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Example 1:
Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]
Example 2:
Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.
Example 3:
Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]
Constraints:
1 <= nums.length <= 3 * 10000
2 <= nums[i] <= 100000
| P = []
N = 10 ** 5 + 5
# N = 32
seen = [0] * N
for i in range(2, N):
if not seen[i]:
P.append(i)
seen[i] = 1
for j in range(i * i, N, i):
seen[j] = 1
class DSU:
def __init__(self, n):
self.uf = {i: i for i in range(n)}
self.rank = {i: 1 for i in range(n)}
def find(self, x):
if self.uf[x] != x:
self.uf[x] = self.find(self.uf[x])
return self.uf[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px != py:
if self.rank[px] > self.rank[py]:
px, py = py, px
self.rank[py] += self.rank[px]
self.uf[px] = py
return True
return False
class Solution:
def gcdSort(self, nums: List[int]) -> bool:
n = len(nums)
dsu = DSU(n)
dic = defaultdict(list)
def fac(x):
ans = []
if not x % 2:
ans.append(2)
while not x % 2: x //= 2
for i in range(3, int(math.sqrt(x)) + 1, 2):
if not x % i:
ans.append(i)
while not x % i: x //= i
if x > 1: ans.append(x)
return ans
for i, a in enumerate(nums):
cur = fac(a)
for p in cur:
dic[p].append(i)
for k, v in dic.items():
for a, b in zip(v, v[1:]):
dsu.union(a, b)
A = sorted(range(n), key=lambda x: nums[x])
B = list(range(n))
for i in range(n):
if A[i] == B[i]: continue
if dsu.find(A[i]) == dsu.find(B[i]):
B[i], A[i] = A[i], B[i]
else: return False
return True
|
e2e522 | b2dd1c | You are given an integer array nums, and you can perform the following operation any number of times on nums:
Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j].
Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Example 1:
Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]
Example 2:
Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.
Example 3:
Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]
Constraints:
1 <= nums.length <= 3 * 10000
2 <= nums[i] <= 100000
| from collections import defaultdict
class Solution(object):
def gcdSort(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
m = max(nums) + 1
fs = range(m)
for i in xrange(2, m):
if fs[i] < i:
continue
ii = i * i
if ii > m:
break
for j in xrange(ii, m, i):
if fs[j] == j:
fs[j] = i
def _pf(x):
r = []
while x > 1:
p = fs[x]
x //= p
if not r or p > r[-1]:
r.append(p)
return r
par = [-1] * m
rnk = [0] * m
def _find(u):
s = []
while par[u] >= 0:
s.append(u)
u = par[u]
for v in s:
par[v] = u
return u
def _union(u, v):
u = _find(u)
v = _find(v)
if u == v:
return
if rnk[u] > rnk[v]:
u, v = v, u
par[u] = v
if rnk[u] == rnk[v]:
rnk[v] += 1
a = nums[:]
n = len(a)
for x in a:
pf = _pf(x)
for p in pf:
_union(p, pf[0])
d = defaultdict(list)
for i, x in enumerate(a):
d[_find(fs[x])].append(i)
for gr in d.itervalues():
vals = [a[i] for i in gr]
vals.sort()
for j, i in enumerate(gr):
a[i] = vals[j]
return all(a[i] <= a[i+1] for i in xrange(n-1)) |
32c1ee | d10f59 | Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.
Example 1:
Input: num = 443
Output: true
Explanation: 172 + 271 = 443 so we return true.
Example 2:
Input: num = 63
Output: false
Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.
Example 3:
Input: num = 181
Output: true
Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.
Constraints:
0 <= num <= 100000
| from typing import List, Tuple, Optional
from collections import defaultdict, Counter
from sortedcontainers import SortedList
MOD = int(1e9 + 7)
INF = int(1e20)
# 给你一个 非负 整数 num 。如果存在某个 非负 整数 k 满足 k + reverse(k) = num ,则返回 true ;否则,返回 false 。
# reverse(k) 表示 k 反转每个数位后得到的数字。
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
for x in range(10**5 + 1):
if x + int(str(x)[::-1]) == num:
return True
return False
|
7466d3 | d10f59 | Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.
Example 1:
Input: num = 443
Output: true
Explanation: 172 + 271 = 443 so we return true.
Example 2:
Input: num = 63
Output: false
Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.
Example 3:
Input: num = 181
Output: true
Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.
Constraints:
0 <= num <= 100000
| class Solution(object):
def sumOfNumberAndReverse(self, num):
"""
:type num: int
:rtype: bool
"""
for i in range(num / 2, num + 1):
if i + int(str(i)[::-1]) == num:
return True
return False |
a7db3c | 2b7d66 | Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
Constraints:
1 <= k <= num.length <= 100000
num consists of only digits.
num does not have any leading zeros except for the zero itself.
| class Solution(object):
def removeKdigits(self, num, k):
L=[]
i=0
while i<len(num):
if k==0 or not L or L[-1]<=num[i]:
L.append(num[i])
i+=1
else:
L.pop(-1)
k-=1
while k!=0:
L.pop(-1)
k-=1
while L and L[0]=='0':
L.pop(0)
if L==[]:
return '0'
s=''
for x in L:
s+=x
return s
"""
:type num: str
:type k: int
:rtype: str
"""
|
bc7560 | eff0e3 | You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.
In the ith operation (1-indexed), you will:
Choose two elements, x and y.
Receive a score of i * gcd(x, y).
Remove x and y from nums.
Return the maximum score you can receive after performing n operations.
The function gcd(x, y) is the greatest common divisor of x and y.
Example 1:
Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1
Example 2:
Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
Example 3:
Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
Constraints:
1 <= n <= 7
nums.length == 2 * n
1 <= nums[i] <= 1000000
| class Solution:
def maxScore(self, nums: List[int]) -> int:
self.n = len(nums)
self.nums = nums
return self.dp((1<<self.n)-1, 1)
@lru_cache(None)
def dp(self, bit, i):
if bit == 0:
return 0
remain = []
for j in range(self.n):
if bit & (1<<j):
remain.append(j)
res = 0
for j in range(len(remain)):
for k in range(j+1, len(remain)):
res = max(res, i*self.gcd(self.nums[remain[j]], self.nums[remain[k]]) + \
self.dp(bit-(1<<remain[j])-(1<<remain[k]), i+1))
return res
def gcd(self, a, b):
if b == 0:
return a
return self.gcd(b, a%b)
|
7b35e8 | eff0e3 | You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.
In the ith operation (1-indexed), you will:
Choose two elements, x and y.
Receive a score of i * gcd(x, y).
Remove x and y from nums.
Return the maximum score you can receive after performing n operations.
The function gcd(x, y) is the greatest common divisor of x and y.
Example 1:
Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1
Example 2:
Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
Example 3:
Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
Constraints:
1 <= n <= 7
nums.length == 2 * n
1 <= nums[i] <= 1000000
| def conv(arr):
s="#"
for i in arr:
s+=str(i)+'#'
return s
def gcd(a,b):
while b:
a,b=b,a%b
return a
class Solution(object):
def maxScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m={}
def func(arr,idx):
s=conv(arr)
if m.get(s,-1)!=-1:
return m[s]
val=0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
brr=[]
for k in range(len(arr)):
if k==i or k==j:
continue
brr.append(arr[k])
val=max(val,func(brr,idx+1)+gcd(arr[i],arr[j])*idx)
m[s]=val
return m[s]
return func(nums,1) |
1a81d4 | 9451d2 | You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
| from collections import defaultdict
class Solution:
def dfs(self, x, path):
for t in self.to[x]:
if t not in self.visited:
path.add(t)
self.visited.add(t)
self.dfs(t, path)
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
to = defaultdict(set)
for a, b in pairs:
to[a].add(b)
to[b].add(a)
self.to = to
self.visited = set()
s = list(s)
for start in range(len(s)):
if start not in self.visited:
path = set([start])
self.visited.add(start)
self.dfs(start, path)
path = sorted(path)
cList = sorted(s[i] for i in path)
for i in range(len(cList)):
s[path[i]] = cList[i]
return "".join(s)
|
493f2d | 9451d2 | You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
| class Solution(object):
def smallestStringWithSwaps(self, S, pairs):
N = len(S)
graph = [[] for _ in xrange(N)]
for u, v in pairs:
graph[u].append(v)
graph[v].append(u)
ans = [None] * N
seen = [False] * N
for u in xrange(N):
if not seen[u]:
seen[u] = True
stack = [u]
component = []
while stack:
node = stack.pop()
component.append(node)
for nei in graph[node]:
if not seen[nei]:
seen[nei] = True
stack.append(nei)
component.sort()
letters = sorted(S[i] for i in component)
for ix, i in enumerate(component):
letter = letters[ix]
ans[i] = letter
return "".join(ans) |
eacdf2 | 7bfea9 | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)
Return the minimum number of operations to reduce the sum of nums by at least half.
Example 1:
Input: nums = [5,19,8,1]
Output: 3
Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
The following is one of the ways to reduce the sum by at least half:
Pick the number 19 and reduce it to 9.5.
Pick the number 9.5 and reduce it to 4.75.
Pick the number 8 and reduce it to 4.
The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75.
The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Example 2:
Input: nums = [3,8,20]
Output: 3
Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.
The following is one of the ways to reduce the sum by at least half:
Pick the number 20 and reduce it to 10.
Pick the number 10 and reduce it to 5.
Pick the number 3 and reduce it to 1.5.
The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5.
The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^7
| class Solution:
def halveArray(self, nums: List[int]) -> int:
pool = [1.0 * -x for x in nums]
heapify(pool)
total = 1.0 * sum(nums)
cur = 0.0
ans = 0
while pool:
ans += 1
cur_max = heappop(pool) * -1
cur += cur_max / 2.0
if 2 * cur >= total:
return ans
heappush(pool, - cur_max / 2.0)
return ans |
1d36b9 | 7bfea9 | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)
Return the minimum number of operations to reduce the sum of nums by at least half.
Example 1:
Input: nums = [5,19,8,1]
Output: 3
Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
The following is one of the ways to reduce the sum by at least half:
Pick the number 19 and reduce it to 9.5.
Pick the number 9.5 and reduce it to 4.75.
Pick the number 8 and reduce it to 4.
The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75.
The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Example 2:
Input: nums = [3,8,20]
Output: 3
Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.
The following is one of the ways to reduce the sum by at least half:
Pick the number 20 and reduce it to 10.
Pick the number 10 and reduce it to 5.
Pick the number 3 and reduce it to 1.5.
The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5.
The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^7
| class Solution(object):
def halveArray(self, A):
h = [-1.0 * a for a in A]
heapq.heapify(h)
target = sum(A) / 2.0
res = 0
while target > 0:
a = heapq.heappop(h) / 2
target += a
heapq.heappush(h, a)
res += 1
return res
|
ca40ad | 79ffcc | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 1000000
| class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
q = [(0,0,0)] # cost,i,j
seen = set()
while q:
cost,i,j=heapq.heappop(q)
if (i,j)==(len(heights)-1,len(heights[0])-1):
return cost
if (i,j) in seen:
continue
seen.add((i,j))
for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
if not 0<=ni<len(heights) or not 0<=nj<len(heights[0]):
continue
if (ni,nj) in seen:
continue
# whats the cost?
price=abs(heights[i][j]-heights[ni][nj])
heapq.heappush(q, (max(cost,price),ni,nj))
return -1 |
b03585 | 79ffcc | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 1000000
| from collections import deque
class Solution(object):
def minimumEffortPath(self, heights):
"""
:type heights: List[List[int]]
:rtype: int
"""
arr = heights
n, m = len(arr), len(arr[0])
def check(diff):
vis = [[False]*m for _ in xrange(n)]
q = []
def _consider(x,y):
if vis[x][y]: return
q.append((x, y))
vis[x][y] = True
_consider(0,0)
while q:
x, y = q.pop()
for xx, yy in (x-1, y), (x, y-1), (x+1, y), (x, y+1):
if xx < 0 or yy < 0 or xx >= n or yy >= m: continue
if abs(arr[x][y] - arr[xx][yy]) > diff: continue
_consider(xx, yy)
return vis[n-1][m-1]
a = -1 # imposs
b = max(val for row in arr for val in row) # poss
while a + 1 < b:
c = (a + b) >> 1
if check(c): b = c
else: a = c
return b |
538669 | a2bc8e | You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score after making any number of moves (including zero moves).
Example 1:
Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Example 2:
Input: grid = [[0]]
Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid[i][j] is either 0 or 1.
| class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
n,m = len(A),len(A[0])
for row in A:
if row[0] == 0:
for i in range(len(row)):
row[i] = 1 - row[i]
ans = n
for j in range(1, m):
cnt0 = len([A[i][j] for i in range(n) if A[i][j] == 0])
ans <<= 1
ans += max(cnt0, n-cnt0)
return ans
|
bfcd00 | a2bc8e | You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score after making any number of moves (including zero moves).
Example 1:
Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Example 2:
Input: grid = [[0]]
Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid[i][j] is either 0 or 1.
| class Solution(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
from collections import Counter
m, n = len(A), len(A[0])
for row in A:
if row[0] == 0:
for i in range(n):
if row[i] == 0:
row[i] = 1
else:
row[i] = 0
res = 2 ** (n-1) * m
for j in range(1,n):
col = [A[i][j] for i in range(m)]
res += max(Counter(col).values()) * 2 ** (n-j-1)
return res |
f62762 | e1295f | You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.
Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.
Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
Note:
A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
The cost of a path is the sum of costs of nodes in the path.
Example 1:
Input: n = 7, cost = [1,5,2,2,3,3,1]
Output: 6
Explanation: We can do the following increments:
- Increase the cost of node 4 one time.
- Increase the cost of node 3 three times.
- Increase the cost of node 7 two times.
Each path from the root to a leaf will have a total cost of 9.
The total increments we did is 1 + 3 + 2 = 6.
It can be shown that this is the minimum answer we can achieve.
Example 2:
Input: n = 3, cost = [5,3,3]
Output: 0
Explanation: The two paths already have equal total costs, so no increments are needed.
Constraints:
3 <= n <= 10^5
n + 1 is a power of 2
cost.length == n
1 <= cost[i] <= 10^4
| class Solution:
def minIncrements(self, n: int, cost: List[int]) -> int:
self.to_ret = 0
def visit(node=0) :
son_l = node*2+1
son_r = node*2+2
if son_l >= n :
return cost[node]
left_v = visit(son_l)
right_v = visit(son_r)
self.to_ret += abs(left_v-right_v)
return max(left_v, right_v)+cost[node]
visit()
return self.to_ret
|
e81642 | e1295f | You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.
Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.
Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
Note:
A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
The cost of a path is the sum of costs of nodes in the path.
Example 1:
Input: n = 7, cost = [1,5,2,2,3,3,1]
Output: 6
Explanation: We can do the following increments:
- Increase the cost of node 4 one time.
- Increase the cost of node 3 three times.
- Increase the cost of node 7 two times.
Each path from the root to a leaf will have a total cost of 9.
The total increments we did is 1 + 3 + 2 = 6.
It can be shown that this is the minimum answer we can achieve.
Example 2:
Input: n = 3, cost = [5,3,3]
Output: 0
Explanation: The two paths already have equal total costs, so no increments are needed.
Constraints:
3 <= n <= 10^5
n + 1 is a power of 2
cost.length == n
1 <= cost[i] <= 10^4
| class Solution(object):
def minIncrements(self, n, cost):
"""
:type n: int
:type cost: List[int]
:rtype: int
"""
def d(c):
if c >= len(cost):
return 0
l, r = d(2 * c + 1), d(2 * c + 2)
self.a += abs(r - l)
return cost[c] + max(l, r)
self.a = 0
d(0)
return self.a |
0de865 | 34e482 | You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:
nums1[i] == nums2[j], and
the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Input: nums1 = [1,4,2], nums2 = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
Constraints:
1 <= nums1.length, nums2.length <= 500
1 <= nums1[i], nums2[j] <= 2000
| class Solution(object):
def maxUncrossedLines(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
memo={}
la,lb=len(A),len(B)
def helper(i,j):
if i>=la or j>=lb:
return 0
if (i,j) in memo:
return memo[i,j]
if A[i]==B[j]:
ans=1+helper(i+1,j+1)
else:
ans=max(helper(i+1,j),helper(i,j+1))
memo[i,j]=ans
return ans
return helper(0,0) |
709571 | 34e482 | You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:
nums1[i] == nums2[j], and
the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Input: nums1 = [1,4,2], nums2 = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
Constraints:
1 <= nums1.length, nums2.length <= 500
1 <= nums1[i], nums2[j] <= 2000
| class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
n, m = len(A), len(B)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1] |
046e26 | 5ed15b | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries.
The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i].
Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.
Example 1:
Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]
Output: [3,3,4]
Explanation:
- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.
- 2nd query updates s = "bbbccc".
The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.
- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.
Thus, we return [3,3,4].
Example 2:
Input: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]
Output: [2,3]
Explanation:
- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.
- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.
Thus, we return [2,3].
Constraints:
1 <= s.length <= 100000
s consists of lowercase English letters.
k == queryCharacters.length == queryIndices.length
1 <= k <= 100000
queryCharacters consists of lowercase English letters.
0 <= queryIndices[i] < s.length
| class Node:
def __init__(self):
self.left = None
self.right = None
self.lmost = None
self.lchar = None
self.rmost = None
self.rchar = None
self.most = None
self.i = None
self.j = None
def update_stats(self):
if self.left is None:
return
if self.left.lmost == self.left.j - self.left.i and self.left.lchar == self.right.lchar:
self.lchar = self.left.lchar
self.lmost = self.left.lmost + self.right.lmost
else:
self.lchar = self.left.lchar
self.lmost = self.left.lmost
if self.right.rmost == self.right.j - self.right.i and self.right.rchar == self.left.rchar:
self.rchar = self.right.rchar
self.rmost = self.right.rmost + self.left.rmost
else:
self.rchar = self.right.rchar
self.rmost = self.right.rmost
self.most = max(self.left.most, self.right.most)
if self.left.rchar == self.right.lchar:
most2 = self.left.rmost + self.right.lmost
self.most = max(self.most, most2)
@classmethod
def create(cls, s, i, j):
node = cls()
if i + 1 == j:
node.lmost = 1
node.rmost = 1
node.lchar = s[i]
node.rchar = s[i]
node.most = 1
node.i = i
node.j = j
else:
m = (i + j) // 2
node.left = cls.create(s, i, m)
node.right = cls.create(s, m, j)
node.i = i
node.j = j
node.update_stats()
return node
def update(self, pos, char):
if self.left is None:
self.lchar = self.rchar = char
elif pos < self.left.j:
self.left.update(pos, char)
else:
self.right.update(pos, char)
self.update_stats()
class Solution:
def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:
tree = Node.create(s, 0, len(s))
ans = []
for i, c in zip(queryIndices, queryCharacters):
tree.update(i, c)
ans.append(tree.most)
return ans
|
ec82a3 | 5ed15b | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries.
The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i].
Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.
Example 1:
Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]
Output: [3,3,4]
Explanation:
- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.
- 2nd query updates s = "bbbccc".
The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.
- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.
Thus, we return [3,3,4].
Example 2:
Input: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]
Output: [2,3]
Explanation:
- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.
- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.
Thus, we return [2,3].
Constraints:
1 <= s.length <= 100000
s consists of lowercase English letters.
k == queryCharacters.length == queryIndices.length
1 <= k <= 100000
queryCharacters consists of lowercase English letters.
0 <= queryIndices[i] < s.length
| class Solution(object):
def longestRepeating(self, s, queryCharacters, queryIndices):
"""
:type s: str
:type queryCharacters: str
:type queryIndices: List[int]
:rtype: List[int]
"""
n = len(s)
mx=1
while mx<=n: mx<<=1
xx = [0]*(mx+mx)
lx = [0]*(mx+mx)
rx = [0]*(mx+mx)
ll = [0]*(mx+mx)
rr = [0]*(mx+mx)
def setc(k, d, i, c):
if d==1:
lx[k]=c
rx[k]=c
xx[k]=1
ll[k]=1
rr[k]=1
return
d>>=1
k1, k2 = k*2+1, k*2+2
if i>=d:
setc(k2, d, i-d, c)
else:
setc(k1, d, i, c)
ll[k]=ll[k1]
lx[k]=lx[k1]
rx[k]=rx[k2]
if ll[k]==d and lx[k2]==rx[k1]: ll[k]+=ll[k2]
rr[k]=rr[k2]
if rr[k]==d and lx[k2]==rx[k1]: rr[k]+=rr[k1]
xx[k]=max(xx[k1], xx[k2])
if lx[k2]==rx[k1]:
v=ll[k2]+rr[k1]
xx[k]=max(xx[k], v)
ss = list(s)
i = 0
while i<n:
setc(0, mx, i, ss[i])
i+=1
m = len(queryIndices)
rs = [0]*m
i=0
while i<m:
j = queryIndices[i]
c = queryCharacters[i]
if c!=ss[j]:
setc(0, mx, j, c)
ss[j]=c
rs[i]=xx[0]
i+=1
return rs
|
fca713 | 5ba297 | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1,null,1]
Output: 2
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 100000].
1 <= Node.val <= 9
| # 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 pseudoPalindromicPaths (self, root):
"""
:type root: TreeNode
:rtype: int
"""
r = [0]
s = set()
def toggle(elem):
if elem in s: s.remove(elem)
else: s.add(elem)
def dfs(u):
if not u: return
toggle(u.val)
if not u.left and not u.right and len(s) <= 1: r[0] += 1
if u.left: dfs(u.left)
if u.right: dfs(u.right)
toggle(u.val)
dfs(root)
return r[0] |
48e740 | 5ba297 | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1,null,1]
Output: 2
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 100000].
1 <= Node.val <= 9
| # 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 pseudoPalindromicPaths (self, root: TreeNode) -> int:
self.ans=0
d={}
d[0]=1
for i in range(10):
d[1<<i]=1
self.d=d
def solve(nd,msk):
if not nd:
return
msk^=(1<<nd.val)
if not nd.left and not nd.right:
self.ans+= msk in self.d
return
solve(nd.left,msk)
solve(nd.right,msk)
solve(root,0)
return self.ans
|
664c92 | 39b6ad | You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.
Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.
Note that you may have multiple coins of the same value.
Example 1:
Input: coins = [1,3]
Output: 2
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
You can make 2 consecutive integer values starting from 0.
Example 2:
Input: coins = [1,1,1,4]
Output: 8
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
- 2: take [1,1]
- 3: take [1,1,1]
- 4: take [4]
- 5: take [4,1]
- 6: take [4,1,1]
- 7: take [4,1,1,1]
You can make 8 consecutive integer values starting from 0.
Example 3:
Input: nums = [1,4,10,3,1]
Output: 20
Constraints:
coins.length == n
1 <= n <= 4 * 10000
1 <= coins[i] <= 4 * 10000
| class Solution:
def getMaximumConsecutive(self, coins: List[int]) -> int:
coins.sort()
s = 0
for x in coins:
if x > s+1:
return s+1
s += x
return s+1 |
34ec7f | 39b6ad | You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.
Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.
Note that you may have multiple coins of the same value.
Example 1:
Input: coins = [1,3]
Output: 2
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
You can make 2 consecutive integer values starting from 0.
Example 2:
Input: coins = [1,1,1,4]
Output: 8
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
- 2: take [1,1]
- 3: take [1,1,1]
- 4: take [4]
- 5: take [4,1]
- 6: take [4,1,1]
- 7: take [4,1,1,1]
You can make 8 consecutive integer values starting from 0.
Example 3:
Input: nums = [1,4,10,3,1]
Output: 20
Constraints:
coins.length == n
1 <= n <= 4 * 10000
1 <= coins[i] <= 4 * 10000
| class Solution(object):
def getMaximumConsecutive(self, coins):
"""
:type coins: List[int]
:rtype: int
"""
coins.sort()
s=0
for i in range(len(coins)):
if coins[i]>s+1:
return s+1
s+=coins[i]
return s+1 |
6296e1 | dda5cc | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si.
For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc.
The score of si is the length of the longest common prefix between si and sn (Note that s == sn).
Given the final string s, return the sum of the score of every si.
Example 1:
Input: s = "babab"
Output: 9
Explanation:
For s1 == "b", the longest common prefix is "b" which has a score of 1.
For s2 == "ab", there is no common prefix so the score is 0.
For s3 == "bab", the longest common prefix is "bab" which has a score of 3.
For s4 == "abab", there is no common prefix so the score is 0.
For s5 == "babab", the longest common prefix is "babab" which has a score of 5.
The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.
Example 2:
Input: s = "azbazbzaz"
Output: 14
Explanation:
For s2 == "az", the longest common prefix is "az" which has a score of 2.
For s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3.
For s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9.
For all other si, the score is 0.
The sum of the scores is 2 + 3 + 9 = 14, so we return 14.
Constraints:
1 <= s.length <= 100000
s consists of lowercase English letters.
| def z_function(S):
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/strings/z_algorithm.py
# https://cp-algorithms.com/string/z-function.html
n = len(S)
Z = [0] * n
l = r = 0
for i in range(1, n):
z = Z[i - l]
if i + z >= r:
z = max(r - i, 0)
while i + z < n and S[z] == S[i + z]:
z += 1
l, r = i, i + z
Z[i] = z
Z[0] = n
return Z
class Solution:
def sumScores(self, s: str) -> int:
lst = z_function(s)
return sum(lst)
|
f9bd58 | 14fa41 | There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
If you start a task in a work session, you must complete it in the same work session.
You can start a new task immediately after finishing the previous one.
You may complete the tasks in any order.
Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Example 1:
Input: tasks = [1,2,3], sessionTime = 3
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
Example 3:
Input: tasks = [1,2,3,4,5], sessionTime = 15
Output: 1
Explanation: You can finish all the tasks in one work session.
Constraints:
n == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15
| class Solution(object):
def minSessions(self, tasks, sessionTime):
"""
:type tasks: List[int]
:type sessionTime: int
:rtype: int
"""
s, dp = [0] * (1 << len(tasks)), [1000000000] * (1 << len(tasks))
for i in range(0, 1 << len(tasks)):
for j in range(0, len(tasks)):
if i & (1 << j) > 0:
s[i] += tasks[j]
dp[0] = 0
for i in range(1, 1 << len(tasks)):
j = i
while j > 0:
if s[j] <= sessionTime:
dp[i] = min(dp[i], dp[i - j] + 1)
j = (j - 1) & i
return dp[(1 << len(tasks)) - 1] |
b049c3 | 14fa41 | There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
If you start a task in a work session, you must complete it in the same work session.
You can start a new task immediately after finishing the previous one.
You may complete the tasks in any order.
Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Example 1:
Input: tasks = [1,2,3], sessionTime = 3
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
Example 3:
Input: tasks = [1,2,3,4,5], sessionTime = 15
Output: 1
Explanation: You can finish all the tasks in one work session.
Constraints:
n == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15
| class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
tasks.sort()
ways = set()
ways.add(tuple())
for x in tasks:
nextWays = set()
for t in ways:
temp = list(t)
nextWays.add(tuple(sorted(temp + [x])))
for i in range(len(t)):
if temp[i] + x <= sessionTime:
nextWays.add(tuple(sorted(temp[:i] + temp[i + 1:] + [ temp[i] + x])))
else:
break
ways = nextWays
return min(len(t) for t in ways)
|
40e81f | 7735ff | You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
Example 2:
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
Output: 0
Constraints:
n == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 10000
1 <= difficulty[i], profit[i], worker[i] <= 100000
| from bisect import bisect_right
class Solution(object):
def maxProfitAssignment(self, difficulty, profit, worker):
"""
:type difficulty: List[int]
:type profit: List[int]
:type worker: List[int]
:rtype: int
"""
N = len(difficulty)
M = len(worker)
jobs = sorted([(difficulty[i], -profit[i]) for i in xrange(N)])
difs = [0]
profs = [0]
for d, p in jobs:
profit = -p
if profit > profs[-1]:
profs.append(profit)
difs.append(d)
total = 0
for w in worker:
i = bisect_right(difs, w) - 1
total += profs[i]
return total
|
346867 | 7735ff | You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
Example 2:
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
Output: 0
Constraints:
n == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 10000
1 <= difficulty[i], profit[i], worker[i] <= 100000
| class Solution:
def maxProfitAssignment(self, difficulty, profit, worker):
"""
:type difficulty: List[int]
:type profit: List[int]
:type worker: List[int]
:rtype: int
"""
data = list(zip(difficulty, profit))
data.sort(key=lambda x: (x[0], -x[1]))
# print(data)
earn = []
earn.append(data[0][1])
for i in range(1, len(data)):
earn.append(max(earn[-1], data[i][1]))
ret = 0
for w in worker:
if w < data[0][0]:
ret += 0
continue
if w >= data[-1][0]:
ret += earn[-1]
continue
l = 0
r = len(data) - 1
while l != r - 1:
m = (l + r) // 2
if w >= data[m][0]:
l = m
else: # w < data[m][0]
r = m
ret += earn[l]
return ret
|
4fea33 | e98ca8 | A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "*"
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "*".
Example 2:
Input: s = "1*"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Example 3:
Input: s = "2*"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
Constraints:
1 <= s.length <= 100000
s[i] is a digit or '*'.
| class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if s[0] == '0': return 0
mm = (10**9) + 7
D = [1]
if s[0] == '*':
D.append(9)
elif s[0] == '0':
D.append(0)
else:
D.append(1)
for i in xrange(1, len(s)):
if s[i] == '0':
cur = 0
else:
cur = D[-1] * (9 if s[i] == '*' else 1)
if s[i-1] == '*' and s[i] == '*':
cur += D[-2] * (9 + 6)
elif s[i] == '*':
if s[i-1] == '1':
cur += D[-2] * 9
elif s[i-1] == '2':
cur += D[-2] * 6
else:
pass
elif s[i-1] == '*':
if ord('0') <= ord(s[i]) <= ord('6'):
cur += D[-2] * 2
else:
cur += D[-2]
elif s[i-1] == '0':
pass
elif ord('3') <= ord(s[i-1]) <= ord('9'):
pass
elif s[i-1] == '2':
if ord('7') <= ord(s[i]) <= ord('9'):
pass
else:
cur += D[-2]
elif s[i-1] == '1':
cur += D[-2]
else:
pass
cur %= mm
D.append(cur)
D.pop(0)
return D[-1]
|
f7324a | e98ca8 | A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "*"
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "*".
Example 2:
Input: s = "1*"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Example 3:
Input: s = "2*"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
Constraints:
1 <= s.length <= 100000
s[i] is a digit or '*'.
| class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
denom = pow(10, 9) + 7
leng = len(s)
p, q = 1, 1
for i in range(leng):
r = q * self.numDecodingsSingle(s[i]) % denom
if i > 0:
r = (r + p * self.numDecodingsDouble(s[i-1:i+1])) % denom
p, q = q, r
return q
def numDecodingsSingle(self, s):
if s == '*':
return 9
if s == '0':
return 0
return 1
def numDecodingsDouble(self, s):
if s[0] == '*':
if s[1] == '*':
return 15
if s[1] < '7':
return 2
return 1
if s[0] == '1':
if s[1] == '*':
return 9
return 1
if s[0] == '2':
if s[1] == '*':
return 6
if s[1] < '7':
return 1
return 0
return 0
|
0d48fb | ee60ce | Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: s = "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: s = "leetcode"
Output: "tcode"
Constraints:
1 <= s.length <= 4 * 100000
s contains only lowercase English letters.
| class Solution:
def lastSubstring(self, s: str) -> str:
mx = ""
for i in range(len(s)):
mx = max(mx, s[i:])
return mx |
1b118a | ee60ce | Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: s = "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: s = "leetcode"
Output: "tcode"
Constraints:
1 <= s.length <= 4 * 100000
s contains only lowercase English letters.
| class Solution(object):
def lastSubstring(self, s):
"""
:type s: str
:rtype: str
"""
if len(set(list(s))) == 1:
return s
maxn = 'a'
for c in s:
if c > maxn:
maxn = c
ans = s
for i in xrange(len(s)):
if s[i] == maxn:
if s[i:] > ans:
ans = s[i:]
return ans |
881b9d | ab2040 | You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer. You want to destroy the maximum number of targets in nums.
Return the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.
Example 1:
Input: nums = [3,7,8,1,1,5], space = 2
Output: 1
Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...
In this case, we would destroy 5 total targets (all except for nums[2]).
It is impossible to destroy more than 5 targets, so we return nums[3].
Example 2:
Input: nums = [1,3,5,2,4,6], space = 2
Output: 1
Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets.
It is not possible to destroy more than 3 targets.
Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.
Example 3:
Input: nums = [6,2,5], space = 100
Output: 2
Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
1 <= space <= 10^9
| class Solution:
def destroyTargets(self, nums: List[int], space: int) -> int:
tmp = defaultdict(list)
for i in nums:
tmp[i%space].append(i)
return sorted((-len(v),min(v)) for v in tmp.values())[0][1] |
d2a9db | ab2040 | You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer. You want to destroy the maximum number of targets in nums.
Return the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.
Example 1:
Input: nums = [3,7,8,1,1,5], space = 2
Output: 1
Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...
In this case, we would destroy 5 total targets (all except for nums[2]).
It is impossible to destroy more than 5 targets, so we return nums[3].
Example 2:
Input: nums = [1,3,5,2,4,6], space = 2
Output: 1
Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets.
It is not possible to destroy more than 3 targets.
Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.
Example 3:
Input: nums = [6,2,5], space = 100
Output: 2
Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].
Constraints:
1 <= nums.length <= 100000
1 <= nums[i] <= 10^9
1 <= space <= 10^9
| class Solution(object):
def destroyTargets(self, nums, space):
"""
:type nums: List[int]
:type space: int
:rtype: int
"""
vs = sorted(nums)
ix = {}
n = len(vs)
i=0
while i<n:
v=vs[i]%space
if v not in ix:
ix[v]=[0, vs[i]]
ix[v][0]+=1
i+=1
rc, rv = 0, -1
for k in ix:
c, v = ix[k]
if c>rc or (c==rc and rv>v):
rc, rv = c, v
return rv |
e60ac6 | 83e046 | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.
You start your journey from building 0 and move to the next building by possibly using bricks or ladders.
While moving from building i to building i+1 (0-indexed),
If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.
Example 1:
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 >= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
- Go to building 3 without using ladders nor bricks since 7 >= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
Example 2:
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7
Example 3:
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3
Constraints:
1 <= heights.length <= 100000
1 <= heights[i] <= 1000000
0 <= bricks <= 10^9
0 <= ladders <= heights.length
| class Solution(object):
def furthestBuilding(self, heights, bricks, ladders):
"""
:type heights: List[int]
:type bricks: int
:type ladders: int
:rtype: int
"""
n = len(heights)
lo = 0
hi = n - 1
while lo < hi:
mi = hi - (hi - lo) // 2
if self.feas(heights, bricks, ladders, mi):
lo = mi
else:
hi = mi - 1
return lo
def feas(self, heights, bricks, ladders, target):
# Get the gaps to fill.
gaps = []
for i in range(target):
if heights[i + 1] > heights[i]:
gaps.append(heights[i + 1] - heights[i])
gaps.sort()
# Handles largest gaps with ladders.
if ladders: gaps = gaps[:-ladders]
return sum(gaps) <= bricks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.