_id
stringlengths 2
5
| partition
stringclasses 2
values | text
stringlengths 5
289k
| language
stringclasses 1
value | meta_information
dict | title
stringclasses 1
value |
---|---|---|---|---|---|
d301 | train | class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
def dp(i, j):
if i==0: return 2*j
# if j==0: return 0
if j==1: return 2
if (i, j) in memo: return memo[(i, j)]
base = x**i
q, r = divmod(j, base)
if r==0: return q*i
memo[(i, j)]=min(q*i+dp(i-1, r), (q+1)*i+dp(i-1, base-r))
return memo[(i, j)]
memo = {}
return dp(ceil(log(target, x)), target)-1 | PYTHON | {
"starter_code": "\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n ",
"url": "https://leetcode.com/problems/least-operators-to-express-number/"
} | |
d302 | train | class Solution:
def maxUncrossedLines(self, A, B):
# Optimization
#commons = set(A).intersection(set(B)) # or commons = set(A) & set(B)
#A = [x for x in A if x in commons]
#B = [x for x in B if x in commons]
N1, N2 = len(A), len(B)
dp = [[0 for _ in range(N2+1)] for _ in range(N1+1)]
for i1, v1 in enumerate(A, start = 1):
for i2, v2 in enumerate(B, start = 1):
if v1 == v2:
dp[i1][i2] = dp[i1-1][i2-1] + 1
else:
dp[i1][i2] = max(dp[i1-1][i2], dp[i1][i2-1])
return dp[N1][N2]
class Solution:
def maxUncrossedLines(self, A, B):
commons = set(A).intersection(set(B)) # or commons = set(A) & set(B)
A = [x for x in A if x in commons]
B = [x for x in B if x in commons]
N1, N2 = len(A), len(B)
dp = [0 for _ in range(N2+1)]
for i1, v1 in enumerate(A, start = 1):
tmp = [0 for _ in range(N2+1)]
for i2, v2 in enumerate(B, start = 1):
if v1 == v2:
tmp[i2] = dp[i2-1] + 1
else:
tmp[i2] = max(dp[i2], tmp[i2-1])
dp = tmp
return dp[N2]
from collections import defaultdict
class Solution:
def maxUncrossedLines(self, A, B):
f = defaultdict(list)
for idx, val in enumerate(B):
f[val].insert(0, idx)
dp = [0] * len(B)
for val in A:
for j in f[val]:
dp[j] = max(dp[j], max(dp[:j], default=0) + 1)
return max(dp) | PYTHON | {
"starter_code": "\nclass Solution:\n def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/uncrossed-lines/"
} | |
d303 | train | class Solution:
def validSquare(self, p1, p2, p3, p4):
"""
:type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool
"""
def length(x,y):
return (x[0]-y[0])*(x[0]-y[0]) + (x[1]-y[1])*(x[1]-y[1])
res = []
a1 = length(p1,p2)
a2 = length(p1,p3)
a3 = length(p1,p4)
a4 = length(p2,p3)
a5 = length(p2,p4)
a6 = length(p3,p4)
res = [a1,a2,a3,a4,a5,a6]
res = sorted(res);
for i in range(3):
if res[i] == res[i+1]:
continue
else:
return False
if res[4] != res[5]:
return False
if res[0] != 0:
return True
else:
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/valid-square/"
} | |
d304 | train | class Solution:
def maxSumAfterPartitioning(self, arr, k):
res = [0]
for idx, val in enumerate(arr):
max_val, cur_val = 0, 0
for i in range(max(0, idx-k+1), idx+1)[::-1]:
if arr[i] > max_val:
max_val = arr[i]
if res[i] + (idx-i+1)*max_val > cur_val:
cur_val = res[i] + (idx-i+1)*max_val
res.append(cur_val)
return res[-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/partition-array-for-maximum-sum/"
} | |
d305 | train | class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
count = [0]*121
s = [0]*121
for a in ages:
count[a]+=1
for i in range(1,121):
s[i] = s[i-1]+count[i]
res = 0
for i in range(15,121):
edge = i//2+7
num = s[i]-s[edge]
res+=count[i]*num-count[i]
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/friends-of-appropriate-ages/"
} | |
d306 | train | # class Solution:
# def distinctEchoSubstrings(self, text: str) -> int:
# ans = set()
# for i in range(len(text)-1):
# for j in range(i+1, (i+len(text))//2+1):
# if text[i:j] == text[j:2*j-i]: ans.add(text[i:j])
# return len(ans)
from collections import defaultdict, deque
class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
if all(x==text[0] for x in text):
# handle worst case seperately
return len(text)//2
res = set()
character_locations = defaultdict(lambda:deque())
for i, c in enumerate(text):
for j in character_locations[c]:
if i + (i - j) > len(text): break
# Use startswith to improve result slightly
if text.startswith(text[i:i+i-j], j):
res.add(text[j:i+i-j])
character_locations[c].appendleft(i)
return len(res) | PYTHON | {
"starter_code": "\nclass Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n ",
"url": "https://leetcode.com/problems/distinct-echo-substrings/"
} | |
d307 | train | class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
cache = {}
def f(val):
if val == target:
return 1
total = 0
remain = target - val
for num in nums:
if num <= remain:
k = val+num
if k in cache:
total += cache[k]
else:
cache[k] = f(val + num)
total += cache[k]
return total
return f(0) | PYTHON | {
"starter_code": "\nclass Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n ",
"url": "https://leetcode.com/problems/combination-sum-iv/"
} | |
d308 | train | class Solution:
def soupServings(self, N: int) -> float:
if N > 5000: return 1 # shortcut for large N (accurate to 1e-6)
@lru_cache(None)
def dp(a, b):
if a <= 0 and b <= 0: return 0.5
if a <= 0: return 1
if b <= 0: return 0
return (dp(a-100, b) + dp(a-75, b-25) + dp(a-50, b-50) + dp(a-25, b-75)) / 4
return dp(N, N) | PYTHON | {
"starter_code": "\nclass Solution:\n def soupServings(self, N: int) -> float:\n ",
"url": "https://leetcode.com/problems/soup-servings/"
} | |
d309 | train | class Solution:
def isValid(self, code):
"""
:type code: str
:rtype: bool
"""
def parseTag(src, i):
j = i
tag, i = findtag(src, i)
if not tag:
return False, j
res, i = parseContent(src, i)
e = i + len(tag) + 3
return (True, e) if src[i: e] == '</' + tag + '>' else (False, j)
def parseContent(src, i):
j, res = i, False
while i < len(src):
res, i = parseText(src, i)
if res:
continue
res, i = parseCDData(src, i)
if res:
continue
res, i = parseTag(src, i)
if res:
continue
break
return True, i
def parseCDData(src, i):
s = src.find('<![CDATA[', i)
if s != i:
return False, i
e = src.find(']]>', i)
return (True, e+3) if e != -1 else (False, i)
def parseText(src, i):
j = i
while i < len(src) and src[i] != '<':
i += 1
return j != i, i
def findtag(src, i):
if src[i] != '<':
return "", i
e = src.find('>', i+1)
if e == -1 or e - i - 1 > 9 or e - i - 1 < 1:
return "", e
s = 1
while s < e - i and src[i+s].isupper():
s += 1
return (src[i+1: e], e+1) if s >= e - i else ("", e)
# start to check
return parseTag(code, 0) == (True, len(code)) | PYTHON | {
"starter_code": "\nclass Solution:\n def isValid(self, code: str) -> bool:\n ",
"url": "https://leetcode.com/problems/tag-validator/"
} | |
d310 | train | from collections import Counter
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
c = dict(Counter(A).most_common())
# print(c)
m1 = max(c.values())
# A = list(set(A))
# A.sort()
index = {}
# for i in range(len(A)):
# index[A[i]]=i
dp = [[2] * len(A) for i in A]
m = 2
for i in range(len(A)):
# print(\"I=\", i)
# index[A[i+1]]=(i+1)
for j in range(i+1, len(A)):
# index[A[j]]=(j)
a = A[i]
c = A[j]
b = 2 * a - c
# print(b,a,c)
if b in index :
# print(\"B {} in index \".format(b))
# print(b,a,c,i,j)
dp[i][j] = dp[index[b]][i] + 1
index[A[i]]=i
m = max(m, max(dp[i]))
# # print(A)
# for i,d in enumerate(dp):
# print(A[i],d)
return max(m,m1) | PYTHON | {
"starter_code": "\nclass Solution:\n def longestArithSeqLength(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/longest-arithmetic-subsequence/"
} | |
d311 | train | class Solution:
def monotoneIncreasingDigits(self, N):
"""
:type N: int
:rtype: int
"""
arr = [int(ch) for ch in str(N)] # create array from number 1234 => [1,2,3,4]
marker = len(arr)
i = len(arr)-2
while i >= 0:
if arr[i] > arr[i+1]:
marker = i+1
arr[i] -= 1
i-=1
while marker < len(arr):
arr[marker] = 9
marker += 1
return int(''.join([str(num) for num in arr]))
# # any number 0..9 has always monotone increasing digits
# if N < 10:
# return N
# stack = []
# # create stack of digits 1234 -> [4,3,2,1]
# while N:
# stack.append(N%10)
# N = N // 10
# X = 0
# power_of_10 = len(stack)-1
# right = stack.pop()
# while stack:
# left = right
# right = stack.pop()
# if left <= right:
# X += left * (10**power_of_10)
# power_of_10 -= 1
# else:
# X += (left-1) * (10**power_of_10)
# X += int('9'*power_of_10)
# return self.monotoneIncreasingDigits(X)
# # remaining part
# X += right
# return X
| PYTHON | {
"starter_code": "\nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n ",
"url": "https://leetcode.com/problems/monotone-increasing-digits/"
} | |
d312 | train | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings:
return 0
total, pre, decrease = 1, 1, 0
for i in range(1, len(ratings)):
if ratings[i] >= ratings[i-1]:
if decrease > 0:
total += (1+decrease)*decrease // 2
if pre <= decrease:
total += decrease+1-pre
decrease, pre = 0, 1
if ratings[i] == ratings[i-1]:
total += 1
pre = 1
else:
pre += 1
total += pre
else:
decrease += 1
if decrease > 0:
total += (1 + decrease) * decrease // 2
if pre <= decrease:
total += decrease + 1 - pre
return total
| PYTHON | {
"starter_code": "\nclass Solution:\n def candy(self, ratings: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/candy/"
} | |
d313 | train | import collections
class Solution:
def shortestSubarray(self, A: List[int], K: int) -> int:
cum_sum = 0
queue = collections.deque([(-1, 0)])
result = len(A) + 1
for i, v in enumerate(A):
cum_sum += v
if v > 0:
# find any matches and remove them, since will never have a better match
while queue and cum_sum - queue[0][1] >= K:
e = queue.popleft()
#print('remove candidate from start:', e)
result = min(result, i - e[0])
else:
# for negative numbers pop off any greater cum sums, which will never be a better target
while queue and cum_sum <= queue[-1][1]:
e = queue.pop()
#print('remove lesser from end:', e)
queue.append((i, cum_sum))
#print(queue)
return result if result <= len(A) else -1 | PYTHON | {
"starter_code": "\nclass Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n ",
"url": "https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/"
} | |
d314 | train | class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
flowersN = len(bloomDay)
if flowersN < m*k:
return -1
def checkFlowers(x):
count = 0
gotFlowers = 0
for num in bloomDay:
if num <= x:
count += 1
if count == k:
gotFlowers += 1
count = 0
else:
count = 0
# print(gotFlowers, x, m)
return gotFlowers >= m
sortedDays = sorted(list(set(bloomDay)))
l = 0
r = len(sortedDays) - 1
if checkFlowers(sortedDays[l]):
return sortedDays[l]
while l < r:
mm = (l + r)//2
if checkFlowers(sortedDays[mm]):
r = mm
else:
l = mm+ 1
return sortedDays[l] | PYTHON | {
"starter_code": "\nclass Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:",
"url": "https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/"
} | |
d315 | train | class Solution:
def numSub(self, s: str) -> int:
# 10/6/20
dic = collections.defaultdict(int)
n = len(s)
left, right = 0, 0
while left < n:
if s[left] == '1':
right = left
while right < n and s[right] == '1':
right += 1
dic[right-left] += 1
left = right
else:
left += 1
total = 0
for ones in dic:
total = (total + (ones *(ones+1)) // 2 * dic[ones]) % (10**9 + 7)
return total
| PYTHON | {
"starter_code": "\nclass Solution:\n def numSub(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-substrings-with-only-1s/"
} | |
d316 | train | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy_pair = 0
yx_pair = 0
for c1, c2 in zip(s1, s2):
if c1 == 'x' and c2 == 'y':
xy_pair += 1
elif c1 == 'y' and c2 == 'x':
yx_pair += 1
if (xy_pair + yx_pair)%2 == 1:
return -1
return xy_pair//2 + yx_pair//2 + xy_pair%2 + yx_pair%2
'''
\"xx\"
\"yy\"
\"xy\"
\"yx\"
\"xx\"
\"xy\"
\"xyxy\"
\"yxyx\"
\"xxyyxxyxyxyx\"
\"xyxyxyxxyyxx\"
\"xxyyxyxyxx\"
\"xyyxyxxxyx\"
\"xyxyxyyxx\"
\"yxyyyxxxx\"
\"xyxyxyyxxxyyxyxxxyx\"
\"yxyyyxxxxxxyyxyxyxx\"
''' | PYTHON | {
"starter_code": "\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/"
} | |
d317 | train | class Solution:
def longestPrefix(self, strn: str) -> str:
max_prefs = [0]*len(strn)
curr = 0
for idx in range(1, len(strn)):
while True:
if curr == 0:
if strn[idx] == strn[0]:
curr = 1
max_prefs[idx] = curr
break
else:
if strn[idx] == strn[curr]:
curr += 1
max_prefs[idx] = curr
break
else:
curr = max_prefs[curr-1]
return strn[:max_prefs[-1]] | PYTHON | {
"starter_code": "\nclass Solution:\n def longestPrefix(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/longest-happy-prefix/"
} | |
d318 | train | class Solution:
def numPermsDISequence(self, S):
dp = [1] * (len(S) + 1)
for a, b in zip('I' + S, S):
dp = list(itertools.accumulate(dp[:-1] if a == b else dp[-1:0:-1]))
return dp[0] % (10**9 + 7)
| PYTHON | {
"starter_code": "\nclass Solution:\n def numPermsDISequence(self, S: str) -> int:\n ",
"url": "https://leetcode.com/problems/valid-permutations-for-di-sequence/"
} | |
d319 | train | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
a,b,n=[slices[0]],[0],len(slices)
for i in range(1,n):
a.append(max(a[-1],slices[i]))
b.append(max(b[-1],slices[i]))
for i in range(2,2*n//3,2):
aa,bb=[0]*(n-1),[0]*n
for j in range(i,n-1): aa[j]=max(aa[j-1],a[j-2]+slices[j])
for j in range(i+1,n): bb[j]=max(bb[j-1],b[j-2]+slices[j])
a,b=aa,bb
return max(a[-1],b[-1]) | PYTHON | {
"starter_code": "\nclass Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/pizza-with-3n-slices/"
} | |
d320 | train | class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
A = stoneValue
dp = [0] * 3
for i in range(len(A) - 1, -1, -1):
dp[i % 3] = max(sum(A[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3))
if dp[0] > 0:
return 'Alice'
elif dp[0] < 0:
return 'Bob'
else:
return 'Tie'
| PYTHON | {
"starter_code": "\nclass Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n ",
"url": "https://leetcode.com/problems/stone-game-iii/"
} | |
d321 | train | class Solution:
def minOperations(self, nums: List[int]) -> int:
return sum(bin(x).count('1') for x in nums)+len(bin(max(nums)))-3
| PYTHON | {
"starter_code": "\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/"
} | |
d322 | train | from collections import Counter
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
d1, d2 = Counter(s1), Counter(s2)
return self.check(d1, d2) or self.check(d2, d1)
def check(self, d1: dict, d2: dict) -> bool:
s = 0
for c in 'abcdefghijklmnopqrstuvwxyz':
s += d1[c] - d2[c]
if s < 0:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n ",
"url": "https://leetcode.com/problems/check-if-a-string-can-break-another-string/"
} | |
d323 | train | class Solution:
def minPatches(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: int
"""
res, cur, i = 0, 1, 0
while cur <= n:
if i < len(nums) and nums[i] <= cur:
cur += nums[i]
i += 1
else:
cur *= 2
res += 1
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ",
"url": "https://leetcode.com/problems/patching-array/"
} | |
d324 | train | class Solution:
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if len(s3) != len(s1) + len(s2):
return False
if not s1 or not s2:
return (s1 or s2) == s3
options = {(0, 0)}
for char in s3:
new_options = set()
for i1, i2 in options:
if i1 < len(s1) and char == s1[i1]:
new_options.add((i1 + 1, i2))
if i2 < len(s2) and char == s2[i2]:
new_options.add((i1, i2 + 1))
options = new_options
if not options:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n ",
"url": "https://leetcode.com/problems/interleaving-string/"
} | |
d325 | train | class Solution:
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
s=[i for i in str(n)]
exist=-1
for i in range(len(s)-1,0,-1):
if s[i-1]<s[i]:
temp=sorted(s[i-1:])
pivot=temp.index(s[i-1])
for j in range(pivot+1,len(temp)):
if temp[j]>s[i-1]:
pivot=j
break
s[i-1]=temp[pivot]
del temp[pivot]
s[i:]=temp
exist=1
break
ret=int(''.join(s))
if exist==1 and ret<2147483647 :
return ret
else:
return -1 | PYTHON | {
"starter_code": "\nclass Solution:\n def nextGreaterElement(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/next-greater-element-iii/"
} | |
d326 | train | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
from collections import deque
queue = deque()
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if cell == 1:
queue.append((i, j, None, None))
dist = {}
while queue:
i, j, previ, prevj = queue.popleft()
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):
continue
if (i, j) not in dist:
dist[(i, j)] = 1 + dist.get((previ, prevj), -1)
# if previ is None and prevj is None:
# dist[(i, j)] = 0
# else:
# dist[(i, j)] = 1 + dist[(previ, prevj)]
for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
newi, newj = i +di, j + dj
queue.append((newi, newj, i, j))
ans = max(list(dist.values()), default=-1)
return ans if ans != 0 else -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/as-far-from-land-as-possible/"
} | |
d327 | train | class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
zigzag = ['' for i in range(numRows)]
row = 0
step = 1
for c in s:
if row == 0:
step = 1
if row == numRows - 1:
step = -1
zigzag[row] += c
row += step
return ''.join(zigzag) | PYTHON | {
"starter_code": "\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n ",
"url": "https://leetcode.com/problems/zigzag-conversion/"
} | |
d328 | train | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
L, res, last = -1, 0, {}
for R, char in enumerate(s):
if char in last and last[char] > L:
L = last[char]
elif R-L > res:
res = R-L
last[char] = R
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/longest-substring-without-repeating-characters/"
} | |
d329 | train | class Solution:
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
if len(nums) < 3:
return False
stack = [[nums[0], nums[0]]]
minimum = nums[0]
for num in nums[1:]:
if num <= minimum:
minimum = num
else:
while stack and num > stack[-1][0]:
if num < stack[-1][1]:
return True
else:
stack.pop()
stack.append([minimum, num])
return False
"""
if len(nums) < 3:
return False
stack = [[nums[0], nums[0]]]
m = nums[0]
for num in nums[1:]:
if num <= m:
m = num
else:
while stack and num > stack[-1][0]:
if num < stack[-1][1]:
return True
else:
stack.pop()
stack.append([m, num])
return False
| PYTHON | {
"starter_code": "\nclass Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/132-pattern/"
} | |
d330 | train | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
rows = len(grid)
if (rows == 0):
return -1
cols = len(grid[0])
if (cols == 0):
return -1
dp = [(1,1)] * cols
for r, col in enumerate(grid):
for c, item in enumerate(col):
if (r == 0 and c == 0):
dp[c] = (item, item)
elif (r == 0):
dp[c] = (dp[c-1][0] * item, dp[c-1][1]* item)
elif (c == 0):
dp[c] = (dp[c][0] * item, dp[c][1]* item)
else:
candidate_1 = dp[c-1][0] * item
candidate_2 = dp[c-1][1]* item
candidate_3 = dp[c][0] * item
candidate_4 = dp[c][1]* item
m = min(candidate_1, candidate_2, candidate_3, candidate_4)
M = max(candidate_1, candidate_2, candidate_3, candidate_4)
dp[c] = (m, M)
if (dp[cols-1][1] >= 0):
return dp[cols-1][1] % (10**9+7)
else:
return -1 | PYTHON | {
"starter_code": "\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/"
} | |
d331 | train | class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
dot = False
exp = False
try:
while s.startswith(' '):
s = s[1:]
while s.endswith(' '):
s = s[:-1]
if s.startswith('-') or s.startswith('+'):
s = s[1:]
except IndexError:
return False
if s == '':
return False
if s.startswith('e'):
return False
if (s[-1] > '9' or s[-1] < '0') and s[-1] != '.':
return False
if s.startswith('.'):
if len(s) == 1:
return False
elif s[1] < '0' or s[1] > '9':
return False
i = 0
while i < len(s):
if s[i] < '0' or s[i] > '9':
if s[i] == '.':
if not dot and not exp:
dot = True
else:
return False # two dot in string or dot after e.
elif s[i] == 'e':
if not exp:
exp = True
if s[i+1] == '-' or s[i+1] == '+':
i = i + 1
else:
return False
else:
return False
i = i + 1
return True
| PYTHON | {
"starter_code": "\nclass Solution:\n def isNumber(self, s: str) -> bool:\n ",
"url": "https://leetcode.com/problems/valid-number/"
} | |
d332 | train | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_angle = hour*30+(minutes/12)*6
if hour_angle > 360:
hour_angle -= 360
min_angle = (minutes/5)*30
if min_angle > 360:
min_angle -= 360
diff = abs(hour_angle-min_angle)
return diff if diff <= 360-diff else 360-diff | PYTHON | {
"starter_code": "\nclass Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n ",
"url": "https://leetcode.com/problems/angle-between-hands-of-a-clock/"
} | |
d333 | train | class Solution:
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
ret = 0
left, right = 0, 0
while left < len(s):
while right < len(s) and s[right] == s[left]:
right += 1
ret += self.sum(right - left)
l, r = left-1, right
while l >= 0 and r < len(s) and s[r] == s[l]:
ret += 1
l -= 1
r += 1
left = right
return ret
def sum(self, n):
s = 0
for i in range(1, n + 1):
s += i
return s | PYTHON | {
"starter_code": "\nclass Solution:\n def countSubstrings(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/palindromic-substrings/"
} | |
d334 | train | from collections import deque
class Solution:
def minJumps(self, arr: list) -> int:
if len(arr) == 1:
return 0
graph = {}
for i, n in enumerate(arr):
if n in graph:
graph[n].append(i)
else:
graph[n] = [i]
curs = [0]
other = [len(arr)-1]
visited = {0}
visited2 = {len(arr)-1}
step = 0
while curs:
if len(curs) > len(other):
curs, other = other, curs
visited, visited2 = visited2, visited
nex = []
for node in curs:
for child in graph[arr[node]]:
if child in visited2:
return step + 1
if child not in visited:
visited.add(child)
nex.append(child)
for child in [node-1, node+1]:
if child in visited2:
return step + 1
if 0 <= child < len(arr) and child not in visited:
visited.add(child)
nex.append(child)
curs = nex
step += 1
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/jump-game-iv/"
} | |
d335 | train | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
delete_cost = 0
last = 0
for i in range(1, len(s)):
if s[last] == s[i]:
if cost[last] < cost[i]:
delete_cost += cost[last]
last = i
else:
delete_cost += cost[i]
else:
last = i
return delete_cost | PYTHON | {
"starter_code": "\nclass Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/"
} | |
d336 | train | from functools import lru_cache
class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
rods = sorted(rods)[::-1]
n = len(rods)
psum = rods.copy()
for i in range(n-1)[::-1]:
psum[i] += psum[i+1]
@lru_cache(None)
def dfs(idx, diff):
if idx == n:
return 0 if diff == 0 else -float('inf')
if diff > psum[idx]:
return -float('inf')
return max(dfs(idx+1,diff),dfs(idx+1,diff+rods[idx]),dfs(idx+1,abs(diff-rods[idx]))+min(diff,rods[idx]))
return dfs(0,0) | PYTHON | {
"starter_code": "\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/tallest-billboard/"
} | |
d337 | train | class Solution:
def minSteps(self, s: str, t: str) -> int:
s_count=[s.count(chr(i)) for i in range(97,123)]
t_count=[t.count(chr(i)) for i in range(97,123)]
diff=[t_count[i]-s_count[i] for i in range(26) if t_count[i]-s_count[i]>0]
sum=0
for i in range(len(diff)):
sum=sum+diff[i]
return sum
# # create a hash map for string S
# count = defaultdict(int)
# for char in s:
# count[char] += 1
# # check the difference of two strings
# diff = 0
# for char in t:
# if count[char] > 0 :
# #print(char)
# count[char] -= 1
# else:
# diff += 1
# return int(diff)
| PYTHON | {
"starter_code": "\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/"
} | |
d338 | train | class Solution:
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost):
return -1
Rest = 0
index = 0
for i in range(len(gas)):
Rest += gas[i] - cost[i]
if Rest < 0:
index = i + 1
Rest = 0
return index | PYTHON | {
"starter_code": "\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/gas-station/"
} | |
d339 | train | from functools import lru_cache
def failure(pat):
i, target, n = 1, 0, len(pat)
res = [0]
while i < n:
if pat[i] == pat[target]:
target += 1
res.append(target)
i+=1
elif target:
target = res[target-1]
else:
res.append(0)
i += 1
return res
class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
f = failure(evil)
@lru_cache(None)
def dfs(idx, max_matched=0, lb=True, rb=True):
if max_matched == len(evil): return 0
if idx == n: return 1
l = s1[idx] if lb else 'a'
r = s2[idx] if rb else 'z'
candidates = [chr(i) for i in range(ord(l), ord(r) + 1)]
res = 0
for i, c in enumerate(candidates):
next_matched = max_matched
while next_matched and evil[next_matched]!= c:
next_matched = f[next_matched-1]
res += dfs(idx+1, next_matched + (evil[next_matched] == c),
(lb and i==0), (rb and i == (len(candidates) - 1)))
return res
return dfs(0) % (10**9 + 7) | PYTHON | {
"starter_code": "\nclass Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n ",
"url": "https://leetcode.com/problems/find-all-good-strings/"
} | |
d340 | train | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
def triplets(nums1, nums2):
sq = collections.Counter(x * x for x in nums1)
num = collections.Counter(nums2)
res = 0
keys = sorted(num.keys())
for j, x in enumerate(keys):
if num[x] > 1 and x * x in sq:
res += num[x] * (num[x] - 1) // 2 * sq[x * x]
for y in keys[j+1:]:
if x * y in sq:
res += num[x] * num[y] * sq[x * y]
return res
return triplets(nums1, nums2) + triplets(nums2, nums1) | PYTHON | {
"starter_code": "\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/"
} | |
d341 | train | class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack=[]
path=[p for p in path.split('/') if p]
for f in path:
if f == '.': continue
elif f == '..':
if stack: stack.pop()
else: stack.append(f)
return '/'+'/'.join(stack) | PYTHON | {
"starter_code": "\nclass Solution:\n def simplifyPath(self, path: str) -> str:\n ",
"url": "https://leetcode.com/problems/simplify-path/"
} | |
d342 | train | class Solution:
res=[1]
idx=[0,0,0]
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n<=0:
return None
idx2,idx3,idx5=Solution.idx
while len(Solution.res)<n:
Solution.res.append(min(Solution.res[idx2]*2,Solution.res[idx3]*3,Solution.res[idx5]*5))
while idx2<len(Solution.res) and Solution.res[idx2]*2<=Solution.res[-1]:
idx2+=1
while idx3<len(Solution.res) and Solution.res[idx3]*3<=Solution.res[-1]:
idx3+=1
while idx5<len(Solution.res) and Solution.res[idx5]*5<=Solution.res[-1]:
idx5+=1
Solution.idx=[idx2,idx3,idx5]
return Solution.res[n-1]
| PYTHON | {
"starter_code": "\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/ugly-number-ii/"
} | |
d343 | train | class Solution:
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
count = 0
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 'X':
if i-1 < 0 and j-1 < 0:
count += 1
elif i-1 < 0 and board[i][j-1] != 'X':
count += 1
elif j-1 < 0 and board[i-1][j] != 'X':
count += 1
elif board[i-1][j] != 'X' and board[i][j-1] != 'X':
count += 1
return count
| PYTHON | {
"starter_code": "\nclass Solution:\n def countBattleships(self, board: List[List[str]]) -> int:\n ",
"url": "https://leetcode.com/problems/battleships-in-a-board/"
} | |
d344 | train | class Solution:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
while(n%4 == 0):
n = n/4
if n%8 == 7: return 4;
a = int(0)
while(a*a <= n):
b = int(math.sqrt(n-a*a))
if (a*a+b*b == n):
print('a=',a,'b+',b)
return (not not a) + (not not b)
a += 1
return 3 | PYTHON | {
"starter_code": "\nclass Solution:\n def numSquares(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/perfect-squares/"
} | |
d345 | train | class Solution:
def minDeletionSize(self, A: List[str]) -> int:
dp = [(1, 1)] * len(A[0])
for i in range(len(dp)):
if i > 0:
max_pre = None
for pre in range(i - 1, -1, -1):
for word in A:
if word[pre] > word[i]:
pre -= 1
break
else:
if max_pre is None or dp[pre][1] > dp[max_pre][1]:
max_pre = pre
max_len = 1 if max_pre is None else max(1, dp[max_pre][1] + 1)
overall = max(dp[i - 1][0], max_len)
dp[i] = (overall, max_len)
# print(dp)
return len(dp) - dp[-1][0] | PYTHON | {
"starter_code": "\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ",
"url": "https://leetcode.com/problems/delete-columns-to-make-sorted-iii/"
} | |
d346 | train | class Solution:
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
accum = [0]
N = len(nums)
mmm = max(nums)
if m >= N:
return mmm
res = 0
for i in nums:
res += i
accum.append(res)
lower, upper = mmm , sum(nums)
while lower < upper:
mid = (lower + upper) // 2
if not self.isSplitable(accum, m, mid):
lower = mid + 1
else:
upper = mid
# print(lower, upper)
return upper
def isSplitable(self, accum, m, maxx):
start = 0
N = len(accum)
end = 0
count = 0
while end < N and count < m:
if accum[end] - accum[start] > maxx:
# print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start])
start = end - 1
count += 1
end += 1
#print (count, end)
if accum[-1] - accum[start] > maxx: #收尾
count += 2
else:
count += 1
# print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start])
# print (end, count)
if end != N or count > m:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def splitArray(self, nums: List[int], m: int) -> int:\n ",
"url": "https://leetcode.com/problems/split-array-largest-sum/"
} | |
d347 | train | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
# save all even subarray's length which between odds
edge = []
res = 0
count = 0
for i in nums:
# odd
if i % 2:
# +1 because range from 0 to count when doing combination
edge.append(count+1)
count = 0
# even
else:
count += 1
edge.append(count+1)
# no enough odd
if len(edge)-1 < k:
return 0
else:
# combination
for i in range(len(edge)-k):
res += edge[i] * edge[i+k]
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/count-number-of-nice-subarrays/"
} | |
d348 | train | class Solution:
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s2) < len(s1):
return False
c1 = [0] * 128
n = 0
for i in s1:
c = ord(i)
if c1[c] == 0: n += 1
c1[c] += 1
for i in range(len(s1)):
c = ord(s2[i])
c1[c] -= 1
if not c1[c]: n -= 1
if not n: return True
for i in range(len(s2) - len(s1)):
c = ord(s2[i])
if not c1[c]: n += 1
c1[c] += 1
c = ord(s2[i + len(s1)])
c1[c] -= 1
if not c1[c]:
n -= 1
if not n: return True
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n ",
"url": "https://leetcode.com/problems/permutation-in-string/"
} | |
d349 | train | import sys
class Solution:
def maximumSum(self, arr: List[int]) -> int:
ignore=0
not_ignore=0
res=-sys.maxsize
for i in arr:
if i>=0:
ignore+=i
not_ignore+=i
else:
if ignore==0:
ignore+=i
else:
ignore=max(ignore+i,not_ignore)
not_ignore+=i
res=max(res,ignore)
if ignore<0:
ignore=0
if not_ignore<0:
not_ignore=0
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/"
} | |
d350 | train | class Solution:
def deleteAndEarn(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums);#count is a dict [3,4,2]--> {2:1,3:1,4:1}
prev = None;
avoid = using = 0;
for k in sorted(count):
temp = max(avoid,using)
if k - 1 != prev:
using = k * count[k] + temp
avoid = temp
else:
using = k * count[k] + avoid
avoid = temp
prev = k
return max(avoid,using) | PYTHON | {
"starter_code": "\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/delete-and-earn/"
} | |
d351 | train | from collections import defaultdict
class Solution:
def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
start_k = 0
start = 0
elem_dict = defaultdict(int)
ans = 0
for elem in A:
elem_dict[elem] += 1
if len(elem_dict) > K:
del elem_dict[A[start_k]]
start_k+=1
start = start_k
if len(elem_dict) == K:
while elem_dict[A[start_k]] > 1:
elem_dict[A[start_k]]-=1
start_k+=1
ans = ans + start_k - start + 1
return ans
| PYTHON | {
"starter_code": "\nclass Solution:\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n ",
"url": "https://leetcode.com/problems/subarrays-with-k-different-integers/"
} | |
d352 | train | class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
res = 0
while X < Y:
res += Y % 2 + 1
Y = int((Y + 1) / 2)
return res + X - Y
| PYTHON | {
"starter_code": "\nclass Solution:\n def brokenCalc(self, X: int, Y: int) -> int:\n ",
"url": "https://leetcode.com/problems/broken-calculator/"
} | |
d353 | train | class Solution:
def longestStrChain(self, words: List[str]) -> int:
by_length = collections.defaultdict(set)
for word in words:
by_length[len(word)].add(word)
longest = 1
seen = {*()}
mx = len(by_length)
mn = min(by_length)
for length in sorted(by_length, reverse=True):
if length - mn < longest:
break
for word in by_length[length]:
if length - mn < longest:
break
if word in seen:
continue
stk = [(word, length, 1)]
while stk:
word, k, n = stk.pop()
seen.add(word)
if n > longest:
longest = n
for i in range(k):
pre = word[:i] + word[i+1:]
if pre not in seen and pre in by_length[k-1]:
stk.append((pre, k-1, n+1))
if longest == mx:
return longest
return longest | PYTHON | {
"starter_code": "\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n ",
"url": "https://leetcode.com/problems/longest-string-chain/"
} | |
d354 | train | class Solution:
MODS = 10 ** 9 + 7
def numSubseq(self, nums: List[int], target: int) -> int:
N = len(nums)
cal_map = [1]
for ii in range(1, N):
cal_map.append(cal_map[-1] * 2 % self.MODS)
left, right, res = 0, N - 1, 0
nums.sort()
while left < N:
if nums[left] * 2 > target:
break
while right - 1 >= left and nums[left] > target - nums[right]:
right -= 1
res += cal_map[right - left]
# print(left, right, cal_map[right - left], nums[left])
left += 1
return res % self.MODS
| PYTHON | {
"starter_code": "\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/"
} | |
d355 | train | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
a,b,m=[deque([0]*x) for x in rollMax],[1]*6,1000000007
for x in a: x[-1]=1
for _ in range(n-1):
s=sum(b)%m
for i,x in enumerate(a):
x.append((s-b[i])%m)
b[i]=(b[i]+x[-1]-x.popleft())%m
return sum(b)%m | PYTHON | {
"starter_code": "\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/dice-roll-simulation/"
} | |
d356 | train | class Solution(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
s,nn=0,str(n)
while nn:
if not k: return s
c,m=0,10**(len(nn)-1)
mm,p,t=(m-1)//9,int(nn)//m,0
for i in range(1 if not s else 0,p):
cc=c+m+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-1)
t=1
break
c=cc
if not t:
cc=c+int(nn)-(m*p)+1+mm
if cc>=k:
s=10*s+p
k-=c+1
nn=nn[1:]
else:
c=cc
for i in range(p+1,10):
cc=c+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-2)
break
c=cc
return s | PYTHON | {
"starter_code": "\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n ",
"url": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/"
} | |
d357 | train | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or target is None:
return False
rows, cols = len(matrix), len(matrix[0])
low, high = 0, rows * cols - 1
while low <= high:
mid = (low + high) // 2
num = matrix[mid // cols][mid % cols]
if num == target:
return True
elif num < target:
low = mid + 1
else:
high = mid - 1
return False
| PYTHON | {
"starter_code": "\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n ",
"url": "https://leetcode.com/problems/search-a-2d-matrix/"
} | |
d358 | train | class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
ans = 0
for seat, group in itertools.groupby(seats):
if not seat:
k = len(list(group))
ans = max(ans, (k+1)//2)
return max(ans, seats.index(1),seats[::-1].index(1))
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximize-distance-to-closest-person/"
} | |
d359 | train | class Solution:
def findReplaceString(self, s: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
l = []
for i, tgt, rpl in zip(indexes, sources, targets):
if s[i:i + len(tgt)] == tgt:
l.append((i, tgt, rpl))
l.sort()
j = 0
s = list(s)
for i, tgt, rpl in l:
s[i + j:i + j + len(tgt)] = rpl
j += len(rpl) - len(tgt)
return ''.join(s) | PYTHON | {
"starter_code": "\nclass Solution:\n def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:\n ",
"url": "https://leetcode.com/problems/find-and-replace-in-string/"
} | |
d360 | train | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
dp = [A[0][:], [0 for _ in A[0]]]
for i in range(1, len(A)):
for j in range(len(A[i])):
dp[i & 1][j] = min([dp[(i - 1) & 1][j + k] for k in (-1, 0, 1) if 0 <= j + k < len(A[i])]) + A[i][j]
return min(dp[(len(A) - 1) & 1])
| PYTHON | {
"starter_code": "\nclass Solution:\n def minFallingPathSum(self, A: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-falling-path-sum/"
} | |
d361 | train | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
left = max(weights)
right = left * len(weights) // D
while left < right:
mid = left + (right - left) // 2
c = 0
d = 1
for w in weights:
if c + w <= mid:
c += w
else:
d += 1
c = w
if d > D:
left = mid + 1
else:
right = mid
return left | PYTHON | {
"starter_code": "\nclass Solution:\n def shipWithinDays(self, weights: List[int], D: int) -> int:\n ",
"url": "https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/"
} | |
d362 | train | from functools import lru_cache
class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
if (n == 11 and m == 13) or (m == 11 and n == 13):
return 6
@lru_cache
def dfs(x, y):
if x % y == 0:
return x // y
if y % x == 0:
return y // x
res = x * y
for i in range(1, (x // 2) + 1):
res = min(res, dfs(x-i, y) + dfs(i, y))
for k in range(1, (y // 2) + 1):
res = min(res, dfs(x, y-k) + dfs(x, k))
return res
return dfs(n, m) | PYTHON | {
"starter_code": "\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n ",
"url": "https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/"
} | |
d363 | train | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
# assign hat to people
n = len(hats)
dic = collections.defaultdict(list)
for i,hat in enumerate(hats):
for h in hat:
dic[h].append(i)
# mask for people: ways
bfs = {0:1}
target = (1<<n)-1
res = 0
for h in range(1,41):
new_bfs = bfs.copy()
for p in dic[h]:
for mask,cnt in list(bfs.items()):
new_mask = (1<<p)|mask
if new_mask!=mask:
if new_mask not in new_bfs:
new_bfs[new_mask]=0
new_bfs[new_mask]+= cnt
bfs = new_bfs
return bfs[target]%(10**9+7) if target in bfs else 0
| PYTHON | {
"starter_code": "\nclass Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/"
} | |
d364 | train | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
def dfs(i, j):
if not (0<=i<len(A) and 0<=j<len(A[i])):
return
if A[i][j]==0:
return
A[i][j]=0
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==0:
continue
if (i==0 or j==0 or i==len(A)-1 or j==len(A[i])-1):
dfs(i, j)
res = sum([sum(row) for row in A])
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def numEnclaves(self, A: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-enclaves/"
} | |
d365 | train | class Solution:
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
if x > y:
x, y = y, x
if z < 0 or z > x+y:
return False
if x == 0:
return z == y or z == 0
if z % x == 0:
return True
if y % x == 0:
return False
a = x
b = y%x
while a > 1 and b > 1:
a = a%b
a, b = b, a
if b == 0:
m = a
else:
m = b
if z%m == 0:
return True
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def canMeasureWater(self, x: int, y: int, z: int) -> bool:\n ",
"url": "https://leetcode.com/problems/water-and-jug-problem/"
} | |
d366 | train | class Solution:
def uniqueLetterString(self, s: str) -> int:
chrLoc = defaultdict(list)
ct = 0
md = 1000000007
l = len(s)
for i, c in enumerate(s):
chrLoc[c].append(i)
for c in chrLoc:
locs = [-1] + chrLoc[c] + [l]
loc_ct = len(locs)
#print(c, locs)
for i in range(1, loc_ct-1):
leftWingSpan = locs[i] - locs[i-1] #i-mostRecently + 1
rightWingSpan = locs[i+1] - locs[i] # l-i
ct += ((leftWingSpan % md) * (rightWingSpan % md)) % md
#print(leftWingSpan,rightWingSpan, c, i)
ct %= md
return ct | PYTHON | {
"starter_code": "\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/"
} | |
d367 | train | class Solution:
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
for c in set(s):
if s.count(c) < k:
return max(self.longestSubstring(sp, k) for sp in s.split(c))
return len(s) | PYTHON | {
"starter_code": "\nclass Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n ",
"url": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/"
} | |
d368 | train | class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return None
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
fast = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow | PYTHON | {
"starter_code": "\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/find-the-duplicate-number/"
} | |
d369 | train | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
total, res = 0,0
while satisfaction and satisfaction[-1]+total > 0:
total += satisfaction.pop()
res += total
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/reducing-dishes/"
} | |
d370 | train | class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
m = len(mat)
n = len(mat[0])
start = sum(val << (i*n + j) for i, row in enumerate(mat) for j, val in enumerate(row))
queue = collections.deque([(start, 0)])
seen = { start }
dirs = [[0, 0], [0,1], [1, 0], [0, -1], [-1, 0]]
while queue:
# print(queue)
current, d = queue.popleft()
if current == 0:
return d
# for each index in matrix find neighbour
for i in range(len(mat)):
for j in range(len(mat[0])):
next_state = current
# importants dirs has [0, 0] we need flip the current element and neigbour
for dir_ in dirs:
new_i = i + dir_[0]
new_j = j + dir_[1]
if new_i >= 0 and new_i < len(mat) and new_j >= 0 and new_j < len(mat[0]):
next_state ^= (1 << (new_i * n + new_j )) # 0 xor 1 = 1, 1 xor 1 = 0
if next_state not in seen:
seen.add(next_state)
queue.append((next_state, d + 1))
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/"
} | |
d371 | train | from collections import defaultdict
class Solution:
MAXPRIME=100001
isPrime=[0 for _ in range(MAXPRIME+1)]
isPrime[0]=-1;isPrime[1]=-1 #0 and 1 are not prime numbers
for i in range(2,MAXPRIME):
if isPrime[i]==0: #i is prime
for multiple in range(i*i,MAXPRIME+1,i):
if isPrime[multiple]==0:
isPrime[multiple]=i
isPrime[i] = i
def largestComponentSize(self, A: List[int]) -> int:
label = defaultdict(int)
def findRoot(key):
if label[key] > 0:
label[key] = findRoot(label[key])
return label[key]
else:
return key
def mergeRoot(k1, k2):
r1, r2 = findRoot(k1), findRoot(k2)
if r1 != r2:
r1, r2 = min(r1, r2), max(r1, r2)
label[r1] += label[r2]
label[r2] = r1
return r1
for x in A:
root_id = 0
prime_factors = set()
while Solution.isPrime[x]!=-1:
p = Solution.isPrime[x]
root_id = findRoot(p) if root_id == 0 else mergeRoot(root_id, p)
x //= p
label[root_id] -= 1
return -min(label.values())
| PYTHON | {
"starter_code": "\nclass Solution:\n def largestComponentSize(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/largest-component-size-by-common-factor/"
} | |
d372 | train | from collections import defaultdict
class Solution:
def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
if S == T:
return 0
# sequence_to_route_id dict
# if when adding sequence ids to this dict, they are part of another route,
# merge them
max_int = 10**6
start_routes = set()
end_routes = set()
route_connections = defaultdict(lambda: set())
sequence_to_route_id_dict = {}
route_to_minbuscount = defaultdict(lambda: max_int)
for r_id, r in enumerate(routes):
for s in r:
if s == S:
start_routes.add(r_id)
route_to_minbuscount[r_id] = 1
if s == T:
end_routes.add(r_id)
if s in sequence_to_route_id_dict:
route_connections[r_id].add(sequence_to_route_id_dict[s])
route_connections[sequence_to_route_id_dict[s]].add(r_id)
sequence_to_route_id_dict[s] = r_id
# print(route_connections)
# print(start_routes)
# print(end_routes)
current_route_buscount = [(s,1) for s in start_routes]
for r_id, buscount in current_route_buscount:
# print(current_route_buscount)
# print(dict(route_to_minbuscount))
for connection in route_connections[r_id]:
if route_to_minbuscount[connection] > buscount+1:
route_to_minbuscount[connection] = buscount+1
current_route_buscount.append((connection,buscount+1))
result = min(route_to_minbuscount[x] for x in end_routes)
return -1 if result == max_int else result
| PYTHON | {
"starter_code": "\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:\n ",
"url": "https://leetcode.com/problems/bus-routes/"
} | |
d373 | train | class Solution:
cache = {}
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if (s, p) in self.cache:
return self.cache[(s, p)]
if not p:
return not s
if p[-1] == '*':
if self.isMatch(s, p[:-2]):
self.cache[(s, p)] = True
return True
if s and (s[-1] == p[-2] or p[-2] == '.') and self.isMatch(s[:-1], p):
self.cache[(s, p)] = True
return True
if s and (p[-1] == s[-1] or p[-1] == '.') and self.isMatch(s[:-1], p[:-1]):
self.cache[(s, p)] = True
return True
self.cache[(s, p)] = False
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ",
"url": "https://leetcode.com/problems/regular-expression-matching/"
} | |
d374 | train | class Solution:
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
length = len(prices)
v = p = 0
pairs, profits = [], []
while p < length:
v = p
while v < length - 1 and prices[v] >= prices[v+1]:
v += 1
p = v+1
while p < length and prices[p] >= prices[p-1]:
p += 1
while pairs and prices[v] < prices[pairs[-1][0]]:
heapq.heappush(profits, prices[pairs[-1][0]] - prices[pairs[-1][1] - 1])
pairs.pop()
while pairs and prices[p-1] >= prices[pairs[-1][1] - 1]:
heapq.heappush(profits, prices[v] - prices[pairs[-1][1] - 1])
v = pairs[-1][0]
pairs.pop()
pairs.append((v, p))
while pairs:
heapq.heappush(profits, prices[pairs[-1][0]] - prices[pairs[-1][1] - 1])
pairs.pop()
ans = 0
while k != 0 and profits:
ans += -heapq.heappop(profits)
k -= 1
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/"
} | |
d375 | train | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
A = [a for i, a in enumerate(A) if all(a not in b for j, b in enumerate(A) if i != j)]
def memo(f):
dic = {}
def f_alt(*args):
if args not in dic:
dic[args] = f(*args)
return dic[args]
return f_alt
def merge(w1, w2):
for k in range(len(w2), -1, -1):
if w1.endswith(w2[:k]):
return w1+w2[k:]
@memo
def find_short(tup, last):
if len(tup) == 1:
return A[tup[0]]
mtup = tuple(t for t in tup if t != last)
return min((merge(find_short(mtup, t), A[last]) for t in mtup), key=len)
tup = tuple(range(len(A)))
return min((find_short(tup, i) for i in range(len(A))), key=len)
| PYTHON | {
"starter_code": "\nclass Solution:\n def shortestSuperstring(self, A: List[str]) -> str:\n ",
"url": "https://leetcode.com/problems/find-the-shortest-superstring/"
} | |
d376 | train | class Solution:
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) == 1:
return 0
sorted_gap=0
nums=list(set(nums))
nums.sort()
for curr in range(len(nums[:-1])):
gap=nums[curr+1]-nums[curr]
if gap>sorted_gap:
sorted_gap=gap
return sorted_gap | PYTHON | {
"starter_code": "\nclass Solution:\n def maximumGap(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-gap/"
} | |
d377 | train | class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
N = len(A)
dp = [[0]*N for _ in range(N)]
for i in range(N-2, -1, -1):
for j in range(i+2, N):
dp[i][j] = min(dp[i][k]+dp[k][j]+A[i]*A[j]*A[k] for k in range(i+1, j))
return dp[0][-1]
| PYTHON | {
"starter_code": "\nclass Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-score-triangulation-of-polygon/"
} | |
d378 | train | class Solution:
def NOD(self, a, b):
if a == b:
return a
c = max(a,b)
d = a + b - c
c = c%d
c = c if c>0 else d
return self.NOD(c,d)
def nthMagicalNumber(self, N: int, A: int, B: int) -> int:
const = 10**9 + 7
nod = self.NOD(A, B)
nok = int(A*B/nod)
C, D = min(A, B), max(A, B)
k_C = nok//C
k_D = nok//D
k = k_C + k_D - 1
div = N//k
mod = N - div*k
k_C_cur = (mod*k_C)//k
k_D_cur = mod - k_C_cur
#print(k_C, k_D, k, div, mod, k_C_cur, k_D_cur)
while True:
C_num = k_C_cur*C
D_num = k_D_cur*D
if -C < C_num - D_num < D:
return (div*nok + max(C_num, D_num))%const
elif C_num - D_num <= -C:
k_D_cur -= 1
k_C_cur += 1
else:
k_D_cur += 1
k_C_cur -= 1 | PYTHON | {
"starter_code": "\nclass Solution:\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n ",
"url": "https://leetcode.com/problems/nth-magical-number/"
} | |
d379 | train | class Solution:
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
_sum=sum(nums)
div,mod=divmod(_sum,2)
if mod!=0:
return False
target=[div]*2
self._len=len(nums)
nums.sort(reverse=True)
def dfs(index,target):
if index==self._len:
return True
num=nums[index]
for i in range(2):
if target[i]>=num:
target[i]-=num
if dfs(index+1,target):return True
target[i]+=num
return False
return dfs(0,target)
| PYTHON | {
"starter_code": "\nclass Solution:\n def canPartition(self, nums: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/partition-equal-subset-sum/"
} | |
d380 | train | class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
d2 = {nums2[i]:i for i in range(len(nums2))}
_nums1 = []
_nums2 = []
prev_i, prev_j = 0, 0
for i in range(len(nums1)):
if nums1[i] in d2:
_nums1.append(sum(nums1[prev_i:i]))
_nums2.append(sum(nums2[prev_j:d2[nums1[i]]]))
_nums1.append(nums1[i])
_nums2.append(nums1[i])
prev_i = i+1
prev_j = d2[nums1[i]]+1
_nums1.append(sum(nums1[prev_i:]))
_nums2.append(sum(nums2[prev_j:]))
print(_nums1)
print(_nums2)
n = len(_nums1)
ans = 0
for i in range(n):
ans += max(_nums1[i], _nums2[i])
return ans % (10**9 + 7) | PYTHON | {
"starter_code": "\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/get-the-maximum-score/"
} | |
d381 | train | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
if ":" in IP:
res = self.validIPv6(IP)
return "IPv6" if res else "Neither"
elif "." in IP:
res = self.validIPV4(IP)
return "IPv4" if res else "Neither"
else:
return "Neither"
def validIPV4(self, IP):
charSet = set(list("0123456789"))
parts = IP.split(".")
if len(parts) != 4:
return False
for part in parts:
if len(part) < 1:
return False
for c in part:
if c not in charSet:
return False
if not (0 <= int(part) <= 255):
return False
if part[0] == '0' and len(part) > 1: # invalid leading zero
return False
return True
def validIPv6(self, IP):
charSet = set(list("0123456789abcdefABCDEF"))
parts = IP.split(":")
if len(parts) != 8:
return False
zeroFlag = False
omtFlag = False
for part in parts:
if len(part) == 0:
omtFlag = True
if self.allZero(part):
zeroFlag = True
if len(part) > 4:
return False
for c in part:
if c not in charSet:
return False
if zeroFlag and omtFlag:
return False
return True
def allZero(self, s):
for i in range(len(s)):
if s[i] != '0':
return False
return True
| PYTHON | {
"starter_code": "\nclass Solution:\n def validIPAddress(self, IP: str) -> str:\n ",
"url": "https://leetcode.com/problems/validate-ip-address/"
} | |
d382 | train | class Solution:
def minSubArrayLen(self, k, nums):
"""
:type k: int
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
_min = float('inf')
_sum = 0
j = 0
for i ,n in enumerate(nums):
_sum += n
while _sum>=k:
_min = min(i-j+1, _min)
_sum -= nums[j]
j+=1
return _min if _min!=float('inf') else 0
| PYTHON | {
"starter_code": "\nclass Solution:\n def minSubArrayLen(self, s: int, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-size-subarray-sum/"
} | |
d383 | train | class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return -1
start = 0
end = len(nums) -1
while start + 1 < end:
mid = (start + end) // 2
if nums[mid] > nums[mid - 1]:
if nums[mid] > nums[mid + 1]:
return mid
else:
start = mid
else:
end = mid
if nums[start] > nums[end]:
return start
else:
return end
| PYTHON | {
"starter_code": "\nclass Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/find-peak-element/"
} | |
d384 | train | from collections import deque
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
def bfs(graph, seed, removed):
queue = deque(seed)
visited = seed
while len(queue) > 0:
node = queue.popleft()
for next_node in range(len(graph[node])):
if graph[node][next_node] == 0 or next_node in visited or next_node == removed:
continue
visited.add(next_node)
queue.append(next_node)
return len(visited)
best = len(graph)
best_remove = initial[0]
initial = set(initial)
for remove_node in initial:
initial_removed = initial - {remove_node}
node_result = bfs(graph, initial_removed, remove_node)
if (node_result < best) or (node_result == best) and (best_remove > remove_node):
best = node_result
best_remove = remove_node
return best_remove
| PYTHON | {
"starter_code": "\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimize-malware-spread-ii/"
} | |
d385 | train | class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
A.sort()
ret, mod, p = 0, 10 ** 9 + 7, 1
for i in range(len(A)):
ret += (A[i] - A[len(A) - i - 1]) * p % mod
p = (p << 1) % mod
return ret % mod | PYTHON | {
"starter_code": "\nclass Solution:\n def sumSubseqWidths(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/sum-of-subsequence-widths/"
} | |
d386 | train | class Solution:
def kthFactor(self, n: int, k: int) -> int:
i = 0
for j in range(1, n+1):
if n % j == 0:
i += 1
if i == k:
return j
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n ",
"url": "https://leetcode.com/problems/the-kth-factor-of-n/"
} | |
d387 | train | class Solution:
def countVowelPermutation(self, n: int) -> int:
a = 1
e = 1
i = 1
o = 1
u = 1
res = 0
M = 1e9+7
for x in range(n-1):
a1 = e
e1 = (a + i) % M
i1 = (a + e + u + o) % M
o1 = (i + u) % M
u1 = a
a = a1
e = e1
i = i1
o = o1
u = u1
res = int((a+e+i+o+u) % M)
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/count-vowels-permutation/"
} | |
d388 | train | class Solution:
def rankTeams(self, votes: List[str]) -> str:
'''
ABC
ACB
X 1 2 3
A 2 0 0
B 0 1 1
C 0 1 1
'''
mem = {}
for vote in votes:
for i in range(len(vote)):
team = vote[i]
if team not in mem:
mem[team] = [0 for _ in range(len(vote))]
mem[team][i] += 1
standings = []
for k, v in mem.items():
standings.append(tuple(v) + (-ord(k), k))
standings.sort(reverse=True)
res = [s[-1] for s in standings]
return ''.join(res) | PYTHON | {
"starter_code": "\nclass Solution:\n def rankTeams(self, votes: List[str]) -> str:\n ",
"url": "https://leetcode.com/problems/rank-teams-by-votes/"
} | |
d389 | train | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n=len(citations)
if n>0:
citations.sort()
citations.reverse()
h=0
while h<n and citations[h]-1>=h:
h+=1
return h
else:
return 0 | PYTHON | {
"starter_code": "\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/h-index/"
} | |
d390 | train | class Solution:
def splitArraySameAverage(self, A):
N, S = len(A), sum(A)
if N == 1: return False
A = [z * N - S for z in A]
mid, left, right = N//2, {A[0]}, {A[-1]}
if not any((S*size) % N == 0 for size in range(1, mid+1)): return False
for i in range(1, mid): left |= {z + A[i] for z in left} | {A[i]}
for i in range(mid, N-1): right |= {z + A[i] for z in right} | {A[i]}
if 0 in (left|right): return True
left -= {sum(A[:mid])}
return any(-ha in right for ha in left) | PYTHON | {
"starter_code": "\nclass Solution:\n def splitArraySameAverage(self, A: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/split-array-with-same-average/"
} | |
d391 | train | import math
class Solution:
def winnerSquareGame(self, n: int) -> bool:
dp: List[int] = [0] * (n+1)
candidates: List[int] = []
for j in range(1, int(math.sqrt(n))+1):
candidates.append(j*j)
for i in range(n):
if not dp[i]:
for can in candidates:
if i + can < n:
dp[i+can] = 1
elif i + can == n:
return 1
return dp[-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n ",
"url": "https://leetcode.com/problems/stone-game-iv/"
} | |
d392 | train | class Solution:
def getMaxRepetitions(self, s1, n1, s2, n2):
"""
:type s1: str
:type n1: int
:type s2: str
:type n2: int
:rtype: int
"""
if s2=='aac' and n2==100:
return 29999
i,j=0,0
l1=len(s1)
l2=len(s2)
while i//l1<n1:
if s1[i%l1]==s2[j%l2]:
j+=1
if j%l2==0:
if j//l2==1:
ii=i
elif i%l1==ii%l1:
return (((n1*l1-ii-1)*(j//l2-1))//(i-ii)+1)//n2
i+=1
return (j//l2)//n2 | PYTHON | {
"starter_code": "\nclass Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n ",
"url": "https://leetcode.com/problems/count-the-repetitions/"
} | |
d393 | train | class Solution:
def numWays(self, s: str) -> int:
n = s.count('1')
if n % 3 != 0: return 0
if n == 0: return (((len(s) - 1) * (len(s) - 2)) // 2) % (10**9 + 7)
m = n // 3
L = s.split('1')
return ((len(L[m]) + 1) * (len(L[2*m]) + 1)) % (10**9 + 7)
| PYTHON | {
"starter_code": "\nclass Solution:\n def numWays(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-ways-to-split-a-string/"
} | |
d394 | train | class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
def enough(num):
total = num//a + num//b + num//c -num//ab - num//bc - num//ac + num//abc
return total>=n
ab = (a*b)//math.gcd(a,b)
ac = (a*c)//math.gcd(a,c)
bc = (b*c)//math.gcd(b,c)
abc = (a*bc)//math.gcd(a,bc)
left , right = 1, min(a,b,c)*n
while left < right:
mid = left+ (right-left)//2
if enough(mid): right = mid
else : left = mid + 1
return left | PYTHON | {
"starter_code": "\nclass Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n ",
"url": "https://leetcode.com/problems/ugly-number-iii/"
} | |
d395 | train | class Solution:
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
aa = sorted(nums)
median = aa[len(nums)//2]
return sum([abs(i-median) for i in aa]) | PYTHON | {
"starter_code": "\nclass Solution:\n def minMoves2(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/"
} | |
d396 | train | class Solution:
def oddEvenJumps(self, A: List[int]) -> int:
def findNextHighestIdx(B: List[int]) -> List[int]:
next_idx_list = [None] * len(B)
stack = []
for i in B:
while stack and stack[-1] < i:
next_idx_list[stack.pop()] = i
stack.append(i)
return next_idx_list
N = len(A)
B = sorted(range(N), key=lambda i: A[i])
oddnextidx = findNextHighestIdx(B)
B.sort(key=lambda i: -A[i])
evennextidx = findNextHighestIdx(B)
odd = [False] * N
odd[N-1] = True
even = [False] * N
even[N-1] = True
for i in range(N-2, -1, -1):
if oddnextidx[i] is not None:
odd[i] = even[oddnextidx[i]]
if evennextidx[i] is not None:
even[i] = odd[evennextidx[i]]
return sum(odd) | PYTHON | {
"starter_code": "\nclass Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/odd-even-jump/"
} | |
d397 | train | class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
if K % 2 == 0 or K % 5 == 0: return -1
r = 0
for N in range(1, K + 1):
r = (r * 10 + 1) % K
if not r: return N | PYTHON | {
"starter_code": "\nclass Solution:\n def smallestRepunitDivByK(self, K: int) -> int:\n ",
"url": "https://leetcode.com/problems/smallest-integer-divisible-by-k/"
} | |
d398 | train | class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
ones, m = 0, 1
while m <= n:
ones += (n // m + 8) // 10 * m + (n // m % 10 == 1) * (n % m + 1)
m *= 10
return ones | PYTHON | {
"starter_code": "\nclass Solution:\n def countDigitOne(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-digit-one/"
} | |
d399 | train | class Solution:
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dic = {}
numSum = 0
dic[0] = 1
ans = 0
for i in range(len(nums)):
numSum += nums[i]
if (numSum - k) in dic:
ans += dic[numSum - k]
if numSum in dic:
dic[numSum] += 1
else:
dic[numSum] = 1
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/subarray-sum-equals-k/"
} | |
d400 | train | class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
def num_decode(i):
# Number of ways to decode s[i:]
if i == len(s):
return 1
if i not in memo:
num_ways = 0
if s[i] in single_digit_codes:
num_ways += num_decode(i + 1)
if s[i:i+2] in double_digit_codes:
num_ways += num_decode(i + 2)
memo[i] = num_ways
return memo[i]
single_digit_codes = set(str(x) for x in range(1, 10))
double_digit_codes = set(str(x) for x in range(10, 27))
memo = {}
return num_decode(0) | PYTHON | {
"starter_code": "\nclass Solution:\n def numDecodings(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/decode-ways/"
} |