_id
stringlengths 2
5
| partition
stringclasses 2
values | text
stringlengths 5
289k
| language
stringclasses 1
value | meta_information
dict | title
stringclasses 1
value |
---|---|---|---|---|---|
d401 | train | class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if not heights:
return 0
stack = [0]
heights.append(0)
# print(heights)
max_area = 0
for i in range(len(heights)):
# print(stack)
if heights[i] >= stack[-1]:
stack.append(heights[i])
else:
k = len(stack) - 1
count = 0
while heights[i] < stack[k] and k >= 0:
count += 1
# print(count)
# print(stack[k])
area = count * stack[k]
if max_area < area:
max_area = area
k -= 1
# print(max_area)
stack = stack[:-count] + [heights[i],] * (count + 1)
# print((count + 1) * stack[k])
# if max_area < (count + 1) * heights[i]:
# max_area = (count + 1) * heights[i]
return max_area
| PYTHON | {
"starter_code": "\nclass Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/largest-rectangle-in-histogram/"
} | |
d402 | train | #5:09
'''
nums = [3,6,5,1,8]
sum_nums = 23
mod3_sum_nums = 2
mod3_dict = {0:[3,6], 1:[1], 2:[5,8]}
helper([5,8], [1]) -> 5
'''
from collections import defaultdict
class Solution:
def helper(self, l1, l2):
if len(l1) < 1 and len(l2) <2:
sum_remove = 0
elif len(l1) < 1:
sum_remove = min(l2)
l2.remove(sum_remove)
sum_remove += min(l2)
elif len(l2) <2:
sum_remove = min(l1)
else:
sum_remove1 = min(l1)
sum_remove2 = min(l2)
l2.remove(sum_remove2)
sum_remove2 += min(l2)
sum_remove = min(sum_remove1, sum_remove2)
return sum_remove
def maxSumDivThree(self, nums: List[int]) -> int:
sum_nums = sum(nums)
mod3_sum_nums = sum_nums%3
if mod3_sum_nums == 0:
return sum_nums
mod3_dict = defaultdict(list)
for i,num in enumerate(nums):
mod3_dict[num%3].append(num)
if mod3_sum_nums ==1:
sum_remove = self.helper(mod3_dict[1], mod3_dict[2])
else:
sum_remove = self.helper(mod3_dict[2], mod3_dict[1])
if sum_remove >0:
return sum_nums - sum_remove
else:
return 0
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/greatest-sum-divisible-by-three/"
} | |
d403 | train | import heapq
def solve(b,s,t):
def create_priority_item(c, t):
dx = c[0]-t[0]
dy = c[1]-t[1]
d2 = dx*dx + dy*dy
return (d2, c)
b = set(tuple(_b) for _b in b)
s = tuple(s)
t = tuple(t)
# heap = [(-1,s)]
heap = [s]
visited = set()
iter = -1
while heap:
iter += 1
if iter > 1.1e6:
return False
# _, c = heapq.heappop(heap)
c = heap.pop()
if c in visited or c in b or c[0] < 0 or c[0] >=1e6 or c[1]<0 or c[1]>=1e6:
continue
if c == t:
# found!
return True
# search neighbors:
dx = c[0] - s[0]
dy = c[1] - s[1]
if dx*dx + dy*dy > 200*200:
return True
visited.add(c)
# heapq.heappush(heap, create_priority_item((c[0]+1, c[1] ), t))
# heapq.heappush(heap, create_priority_item((c[0]-1, c[1] ), t))
# heapq.heappush(heap, create_priority_item((c[0] , c[1]+1), t))
# heapq.heappush(heap, create_priority_item((c[0] , c[1]-1), t))
heap.append((c[0]+1, c[1] ))
heap.append((c[0]-1, c[1] ))
heap.append((c[0] , c[1]+1))
heap.append((c[0] , c[1]-1))
# we live in a cavity :(
return False
def solve_both(b,s,t):
return solve(b,s,t) and solve(b,t,s)
class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
return solve_both(blocked, source, target)
| PYTHON | {
"starter_code": "\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/escape-a-large-maze/"
} | |
d404 | train | class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n1 = n2 = float('inf')
for n in nums:
if n <= n1:
n1 = n
elif n <= n2:
n2 = n
else:
return True
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/increasing-triplet-subsequence/"
} | |
d405 | train | class Solution:
def largestSumOfAverages(self, A: List[int], K: int) -> float:
#if not A: return 0
#if len(A)==1: return A[0]
# Real Run Time is a little bit UNSTABLE
N = len(A)
P = [0] * (N+1)
for i in range(1,N+1): P[i] = P[i-1] + A[i-1]
# Table[a] = optimal for A[a:] with k subsets, initially k=1
Table = [(P[N]-P[i])/(N-i) for i in range(N)]
for k in range(2, K+1):
for i in range(K-k,N-k+1):
Table[i] = max((P[j]-P[i])/(j-i) + Table[j] for j in range(i+1,N-k+2))
return Table[0] | PYTHON | {
"starter_code": "\nclass Solution:\n def largestSumOfAverages(self, A: List[int], K: int) -> float:\n ",
"url": "https://leetcode.com/problems/largest-sum-of-averages/"
} | |
d406 | train | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
dp = [0] * (N + W)
for i in range(K, N + 1):
dp[i] = 1
S = min(W, N - K + 1)
for i in range(K - 1, -1, -1):
dp[i] = S / W
S += dp[i] - dp[i + W]
return dp[0] | PYTHON | {
"starter_code": "\nclass Solution:\n def new21Game(self, N: int, K: int, W: int) -> float:\n ",
"url": "https://leetcode.com/problems/new-21-game/"
} | |
d407 | train | class Solution:
def ladderLength(self, beginWord, endWord, wordList):
wordDict = set(wordList)
if not endWord in wordDict:
return 0
visited = set()
beginSet = set()
beginSet.add(beginWord)
visited.add(beginWord)
endSet = set()
endSet.add(endWord)
visited.add(endWord)
lenWord = len(beginWord)
distance = 1
while len(beginSet) > 0 and len(endSet) > 0:
# make sure begin set is smaller than endSet
if len(beginSet) > len(endSet):
beginSet, endSet = endSet, beginSet
# extend begin set
newSet = set()
for w in beginSet:
for i in range(lenWord):
part1 = w[:i]
part2 = w[i+1:]
for alpha in 'abcdefghijklmnopqrstuvwxyz':
target = part1 + alpha + part2
if target in endSet:
return distance + 1
elif (not target in visited) and (target in wordDict):
newSet.add(target)
visited.add(target)
beginSet = newSet
distance += 1
return 0 | PYTHON | {
"starter_code": "\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n ",
"url": "https://leetcode.com/problems/word-ladder/"
} | |
d408 | train | class Solution:
def scoreOfParentheses(self, S: str) -> int:
ans, val = 0, 1
for i in range(len(S) - 1):
if S[i: i+2] == '((': val *= 2
if S[i: i+2] == '()': ans += val
if S[i: i+2] == '))': val //= 2
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def scoreOfParentheses(self, S: str) -> int:\n ",
"url": "https://leetcode.com/problems/score-of-parentheses/"
} | |
d409 | train | class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
arr.sort()
n = len(arr)
for i in range(n):
sol = round(target / n)
if arr[i] >= sol:
return sol
target -= arr[i]
n -= 1
return arr[-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n ",
"url": "https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/"
} | |
d410 | train | class Solution:
def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
oneArrSum = sum(arr)
twoArr = arr + arr
def findMaxSub(array):
if len(array) == 1:
return array[0]
cur = 0
small = 0
ret = -999999
for i in array:
cur += i
small = cur if cur < small else small
ret = cur - small if cur - small > ret else ret
return 0 if ret < 0 else ret
if not arr:
return 0
if k == 1:
return findMaxSub(arr)
ret = findMaxSub(twoArr)
if oneArrSum > 0 and k > 2:
ret += (k-2)*oneArrSum
return ret % (10**9 + 7) | PYTHON | {
"starter_code": "\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/k-concatenation-maximum-sum/"
} | |
d411 | train | class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
return sorted(range(lo, hi + 1), key='寒寒寓寙寔寗寚寢寕寥寘寠寛寛寣寣寖寞實實寙寙寡寡寜審寜屁寤寤寤尼寗寬察察寧寧寧寴寚尿寚寯寢寢寢尺寝寪寪寪寝寝层层寥寲寥寲寥寥尽尽寘寭寭寭寠寠寠尸寨居寨寠寨寨寵寵寛寨局局寛寛寰寰寣寰寣尮寣寣尻尻寞屈寫寫寫寫寫尩寞寸寞尶屃屃屃尗實寞寳寳實實寳寳實就實尀尾尾尾尀寙屋寮寮寮寮寮寻寡尬寡寻寡寡尹尹審屆屆屆審審寡寡審寶審尧寶寶寶專寜尴審審屁屁屁尕寜尃寜屎寱寱寱尢寤寱寱寱寤寤尯尯寤対寤対尼尼尼対察屉屉屉寬寬寬屉寬寤寬对寬寬尪尪察对对对察察尷尷屄寬屄将屄屄尘尘寧将察察寴寴寴屑寧尥寧屑寴寴寴将寧寧尲尲寧寧封封尿封尿尓尿尿封封寚屌屌屌寯寯寯尠寯屌寯寧寯寯导导寢寯尭尭寢寢导导寢导寢導尺尺尺导寪寯屇屇屇屇屇尉寪尛寪屇寢寢寢导寪寷寷寷寪寪尨尨寷屔寷寷寷寷尉尉寝寪尵尵寪寪寪屡层射层寪层层尖尖寝层射射寝寝屏屏寲屏寲屏寲寲尣尣寥屏寲寲寲寲寲射寥寿寥寿尰尰尰寿寥寥寿寿寥寥寿寿尽少尽尌尽尽寿寿寠寲届届届届届届寭尌寭尞寭寭届届寭寥寥寥寭寭寺寺寭寺寭屗尫尫尫屗寠屗寺寺寺寺寺寲寠尌寠將尸尸尸寺居寭寭寭居居將將居寭居將尙尙尙尳寨居將將寠寠寠寺寵屒寵屒寵寵屒屒寨寵尦尦寨寨屒屒寵寵寵寭寵寵將將寨専寨寨尳尳尳屟寨専寨屟専専専尳局寨専専局局尔尔局小局寵専専専小寛寵屍屍屍屍屍小寰屍寰屍寰寰尡尡寰寰屍屍寰寰寨寨寰寨寰専寽寽寽屚寣寽寰寰尮尮尮寽寣屚寣寰寽寽寽尩寣寽寽寽寣寣小小尻尊尻寰尻尻寽寽寫寰寰寰屈屈屈寰屈尊屈屈屈屈尊尊寫尜尜尜寫寫屈屈寣尊寣尗寣寣寽寽寫展寸寸寸寸寸尗寫展寫展尩尩尩展寸寫展展寸寸寸寸寸寰寸寰尊尊尊展寞尅寫寫尶尶尶寸寫屢寫尶寫寫屢屢屃尅尅尅屃屃寫寫屃尅屃屢尗尗尗就寞尒屃屃尅尅尅尒寞尒寞寸屐屐屐寸寳屐屐屐寳寳屐屐寳屐寳尒尤尤尤屼實寳屐屐寳寳寳尒寳寫寳寫寳寳尅尅實尀尀尀實實尀尀就寳就屝就就尀尀實屝實實尀尀尀就實尬實尀尀尀尀屝尾實尒尒尾尾對對尾寳尾屪尀尀尀對寡寳寳寳屋屋屋屪屋寳屋對屋屋屋屋寮屋對對寮寮尟尟寮尟寮尹屋屋屋尚寮對實實實實實尚寮尀寮屘寻寻寻屘寮寻寻寻寮寮屘屘尬屘尬寻尬尬屘屘寡寮屘屘寻寻寻尧寻寻寻寻寻寻寳寳寡對對對寡寡專專尹寮尹履尹尹寻寻屆履寮寮寮寮寮岄屆履屆寮專專專履屆屆寮寮屆屆專專尚履尚尀尚尚尴尴審尕屆屆專專專屆寡尕寡專寡寡寻寻寶屓屓屓寶寶屓屓寶屓寶尕屓屓屓屆審屓寶寶尧尧尧屓審屿審尧屓屓屓寶寶寶寶寶寶寶寮寮寶寮寶寮專專專屓審尃尃尃審審審屠尴尃尴寶尴尴屠屠審尴尃尃審審屠屠尃審尃寶尃尃尴尴屁尯審審尃尃尃尃屁'.__getitem__)[k - 1] | PYTHON | {
"starter_code": "\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n ",
"url": "https://leetcode.com/problems/sort-integers-by-the-power-value/"
} | |
d412 | train | class Solution:
def wordBreak(self, s, wordDict):
n = len(s)
dp = [False for i in range(n+1)]
dp[0] = True
for i in range(1,n+1):
for w in wordDict:
if dp[i-len(w)] and s[i-len(w):i]==w:
dp[i]=True
return dp[-1]
| PYTHON | {
"starter_code": "\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n ",
"url": "https://leetcode.com/problems/word-break/"
} | |
d413 | train | from math import comb
from math import pow
class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
if(target < d*1 or target > d*f ):
return 0
target = target - d
sum = 0
i = 0
j=0
while(i <= target):
y = target - i
if(j%2 == 0):
sum =int( (sum + comb(d, j) * comb(y+d-1,y)) )
else:
sum =int( (sum - comb(d, j) * comb(y+d-1,y)))
#print( comb(d, j) * comb(y+d-1,y))
#print('i ={} y= {} sum={} '.format(i,y,sum))
j=j+1
i = i + f
#print(sum)
return int(sum) % 1000000007
| PYTHON | {
"starter_code": "\nclass Solution:\n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/"
} | |
d414 | train | class Solution:
def breakPalindrome(self, palindrome: str) -> str:
if len(palindrome) == 1:
return ''
for i, val in enumerate(palindrome):
if val != 'a' and i != len(palindrome) // 2:
return palindrome[:i] + 'a' + palindrome[i+1:]
elif val == 'a' and i == len(palindrome) - 1:
return palindrome[:-1] + 'b'
| PYTHON | {
"starter_code": "\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n ",
"url": "https://leetcode.com/problems/break-a-palindrome/"
} | |
d415 | train | class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
win=0
curr = arr[0]
mx=0
for i in range(1,len(arr)):
if arr[i] > curr:
curr=arr[i]
win=0
win=win+1
if win==k:
break
return curr | PYTHON | {
"starter_code": "\nclass Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/find-the-winner-of-an-array-game/"
} | |
d416 | train | class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
n = len(A)
if n == 1:
return 0
dp = [[float('inf'), float('inf')] for _ in range(n)]
dp[0] = [0,1] #[natural, swapped]
for i in range(1, n):
if A[i-1] < A[i] and B[i-1] < B[i]:
dp[i] = [dp[i-1][0], dp[i-1][1]+1]
if A[i-1] < B[i] and B[i-1] < A[i]:
dp[i] = [min(dp[i][0],dp[i-1][1]), min(dp[i][1],dp[i-1][0]+1)]
print(dp)
return min(dp[-1])
| PYTHON | {
"starter_code": "\nclass Solution:\n def minSwap(self, A: List[int], B: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/"
} | |
d417 | train | class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
N = len(graph)
# What nodes could play their turn to
# arrive at node (mouse, cat, turn) ?
def parents(mouse, cat, turn):
prev_turn = 3 - turn
if prev_turn == MOUSE:
for m2 in graph[mouse]:
yield m2, cat, prev_turn
else:
for c2 in graph[cat]:
if c2:
yield mouse, c2, prev_turn
DRAW, MOUSE, CAT = 0, 1, 2
colors = collections.defaultdict(int)
# degree[node] : the number of neutral children of this node
degree = {}
for mouse in range(N):
for cat in range(N):
degree[mouse, cat, MOUSE] = len(graph[mouse])
degree[mouse, cat, CAT] = len(graph[cat]) - (0 in graph[cat]) # cat can not be at hole 0
# enqueued : all nodes that are colored
queue = collections.deque([])
for cat in range(N):
for turn in [MOUSE, CAT]:
# color MOUSE for all node with mouse=0
mouse = 0
colors[mouse, cat, turn] = MOUSE
queue.append((mouse, cat, turn, MOUSE))
# color CAT for all node with mouse = cat !=0, cat can not be at hole 0
if cat > 0:
mouse = cat
colors[mouse, cat, turn] = CAT
queue.append((mouse, cat, turn, CAT))
# percolate
while queue:
mouse, cat, turn, color = queue.popleft()
for prev_mouse, prev_cat, prev_turn in parents(mouse, cat, turn):
# if this parent is not colored :
if colors[prev_mouse, prev_cat, prev_turn] is DRAW:
# if the parent can make a winning move (ie. mouse to MOUSE), do so
if prev_turn == color: # winning move
colors[prev_mouse, prev_cat, prev_turn] = color
queue.append((prev_mouse, prev_cat, prev_turn, color))
if prev_mouse == 1 and prev_cat == 2 and prev_turn == MOUSE:
return color
# else, this parent has degree[parent]--, and enqueue if all children
# of this parent are colored as losing moves
else:
degree[prev_mouse, prev_cat, prev_turn] -= 1
if degree[prev_mouse, prev_cat, prev_turn] == 0:
colors[prev_mouse, prev_cat, prev_turn] = 3 - prev_turn
queue.append((prev_mouse, prev_cat, prev_turn, 3 - prev_turn))
if prev_mouse == 1 and prev_cat == 2 and prev_turn == MOUSE:
return color
return colors[1, 2, 1] # mouse at 1, cat at 2, MOUSE turn | PYTHON | {
"starter_code": "\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/cat-and-mouse/"
} | |
d418 | train | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums = nums1 + nums2
nums.sort()
if len(nums) % 2 == 1:
return float(nums[len(nums)//2])
return (nums[len(nums)//2-1] + nums[len(nums)//2]) / 2 | PYTHON | {
"starter_code": "\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n ",
"url": "https://leetcode.com/problems/median-of-two-sorted-arrays/"
} | |
d419 | train | class Solution:
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
'''
if n == 1:
return 0
if not (n & 1):
return self.integerReplacement(n//2) + 1
return min(self.integerReplacement(n+1), self.integerReplacement(n-1)) + 1
'''
ans = 0
while n > 1:
if n % 2 == 0:
n = n // 2
elif n % 4 == 1 or n == 3:
n -= 1
else:
n += 1
ans += 1
return ans
| PYTHON | {
"starter_code": "\nclass Solution:\n def integerReplacement(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/integer-replacement/"
} | |
d420 | train | class Solution:
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
else:
return int(n**0.5)
| PYTHON | {
"starter_code": "\nclass Solution:\n def bulbSwitch(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/bulb-switcher/"
} | |
d421 | train | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
s = s + 'a'
bits, dp = {'a':0,'e':1,'i':2,'o':3,'u':4}, {0:-1}
res = 0
key = 0
for i, char in enumerate(s):
if char in bits:
if key in dp:
res = max(res, i-dp[key] - 1)
key = key ^ (1 << bits[char])
if key not in dp:
dp[key] = i
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/"
} | |
d422 | train | class Solution:
def lastSubstring(self, s: str) -> str:
#mx = \"\"
#for i in range(len(s)):
# mx = max(mx,s[i:])
#return mx
index = {c: i for i, c in enumerate(sorted(set(s)))}
cur, radix, max_val, max_i = 0, len(index), 0, 0
for i in range(len(s)-1, -1, -1):
cur = index[s[i]] + cur/radix
if cur > max_val:
max_val, max_i = cur, i
return s[max_i:] | PYTHON | {
"starter_code": "\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/last-substring-in-lexicographical-order/"
} | |
d423 | train | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
size = len(s)
if size <= 1 or s == s[::-1]:
return s
start, maxlen = 0, 1
for idx in range(1, size):
add2 = s[idx - maxlen - 1: idx + 1]
if idx - maxlen - 1 >= 0 and add2 == add2[::-1]:
start = idx - maxlen - 1
maxlen += 2
continue
add1 = s[idx - maxlen: idx + 1]
if add1 == add1[::-1]:
start = idx - maxlen
maxlen += 1
return s[start: (start + maxlen)] | PYTHON | {
"starter_code": "\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/longest-palindromic-substring/"
} | |
d424 | train | from collections import defaultdict
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
count_dict = defaultdict(int)
for num in arr:
count_dict[num] = count_dict[num-difference] + 1
return max(count_dict.values())
| PYTHON | {
"starter_code": "\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n ",
"url": "https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/"
} | |
d425 | train | class Solution:
def largestOverlap(self, A, B) -> int:
leng = len(A[0])
# convert A, B to binary
a = 0
b = 0
for i in range(0, leng * leng):
row = int(i % leng)
col = int(i / leng)
a = (a << 1) + A[col][row]
b = (b << 1) + B[col][row]
maxsum = 0
for i in range(-leng + 1, leng):
if i < 0:
mask = ('0' * abs(i) + '1' * (leng - abs(i))) * leng
bp = (b & int(mask, 2)) << abs(i)
elif i > 0:
mask = ('1' * (leng - abs(i)) + '0' * abs(i)) * leng
bp = (b & int(mask, 2)) >> abs(i)
else:
bp = b
for j in range(-leng + 1, leng):
if j < 0:
bpp = bp >> (leng * abs(j))
elif j > 0:
bpp = (bp << (leng * abs(j))) & ((2 ** (leng * leng)) - 1)
else:
bpp = bp
maxsum = max(maxsum, bin(a & bpp).count('1'))
return maxsum | PYTHON | {
"starter_code": "\nclass Solution:\n def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/image-overlap/"
} | |
d426 | train | class Solution:
def get_half(self,dividend,divisor):
abs_dividend = abs(dividend)
abs_divisor = abs(divisor)
num = divisor
num_temp=0
result=1
result_temp=0
while (num<=dividend):
num_temp=num
num+=num
result_temp=result
result+=result
return num_temp,result_temp
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
MAX_INT = 2147483647
if divisor == 0:
return MAX_INT
abs_dividend = abs(dividend)
abs_divisor = abs(divisor)
if abs_dividend <abs_divisor:
return 0
minus_flag = (dividend is abs_dividend) is (divisor is abs_divisor)
final_result=0
while(abs_dividend>=abs_divisor):
num,result=self.get_half(abs_dividend,abs_divisor)
abs_dividend-=num
final_result+=result
if minus_flag==1:
if final_result>MAX_INT:
return MAX_INT
return final_result
else:
if 0-final_result<0-MAX_INT-1:
return 0-MAX_INT
return 0-final_result | PYTHON | {
"starter_code": "\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n ",
"url": "https://leetcode.com/problems/divide-two-integers/"
} | |
d427 | train | class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
n_len = len(str(n))
n = Counter(str(n))
p = 1
while len(str(p)) <= n_len:
if len(str(p)) == n_len and Counter(str(p)) == n:
return True
p *= 2
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def reorderedPowerOf2(self, N: int) -> bool:\n ",
"url": "https://leetcode.com/problems/reordered-power-of-2/"
} | |
d428 | train | class Solution:
def countOrders(self, n: int) -> int:
if n == 1:
return 1
p = (n-1)*2+1
dp = [0 for i in range(n+1)]
dp[1] = 1
M= 10**9+7
for i in range(2,n+1):
p = (i-1)*2+1
dp[i] = (dp[i-1]%M * ((p*(p+1))//2)%M)%M
return dp[n]
| PYTHON | {
"starter_code": "\nclass Solution:\n def countOrders(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/"
} | |
d429 | train | import heapq
from collections import deque, defaultdict
class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
m,n = len(grid),len(grid[0])
key_lock_loc = {ch:(i,j) for i,row in enumerate(grid) for j,ch in enumerate(row) if ch not in {'.','#'}}
key_cnt = sum(key_lock in ('a','b','c','d','e','f')for key_lock in key_lock_loc)
def bfs_from(src):
i,j = key_lock_loc[src]
seen = defaultdict(lambda: False)
seen[i,j] = True
# only locations which are not wall will be put into the queue
dque = deque([(i,j,0)])
dist = {}
while dque:
i,j,d = dque.popleft()
ch = grid[i][j]
if ch != src and ch != '.': # reaches lock or key
dist[ch] = d
continue
# '#' or '.'
for x,y in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):
if not (0<=x<m and 0<=y<n) or grid[x][y] == '#' or seen[x,y]:
continue
seen[x,y] = True
dque.append((x,y,d+1))
return dist
dists = {key_lock:bfs_from(key_lock) for key_lock in key_lock_loc}
all_keys_bitmap = 2 ** key_cnt -1
hq = [(0,'@',0)]
final_dist = defaultdict(lambda: float('inf'))
final_dist['@', 0] = 0
while hq:
d,ch,keys_bitmap = heapq.heappop(hq)
if final_dist[ch,keys_bitmap] < d:
continue
if keys_bitmap == all_keys_bitmap:
return d
for next_key_lock, d2 in list(dists[ch].items()):
keys_bitmap2 = keys_bitmap
if next_key_lock.islower(): # key
keys_bitmap2 |= (1 <<(ord(next_key_lock) - ord('a')))
elif next_key_lock.isupper(): # ch
if not(keys_bitmap &(1 <<(ord(next_key_lock) - ord('A')))):
continue
if d + d2 < final_dist[next_key_lock, keys_bitmap2]:
final_dist[next_key_lock, keys_bitmap2]= d + d2
heapq.heappush(hq,(d+d2,next_key_lock,keys_bitmap2))
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n ",
"url": "https://leetcode.com/problems/shortest-path-to-get-all-keys/"
} | |
d430 | train | class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
s_count = collections.defaultdict(int)
g_count = collections.defaultdict(int)
bull_cnt = 0
# first iteration can get bull_cnt immediately
for s, g in zip(secret, guess):
if s == g: bull_cnt += 1
# keep two counters for non matching chars
else:
s_count[s] += 1
g_count[g] += 1
# if char in both s_count and g_count, the min of the two is the cow_cnt for this char
cow_cnt = sum(min(s_count[x], g_count[x]) for x in g_count if x in s_count)
return "{}A{}B".format(bull_cnt, cow_cnt)
| PYTHON | {
"starter_code": "\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n ",
"url": "https://leetcode.com/problems/bulls-and-cows/"
} | |
d431 | train | class Solution:
def distinctSubseqII(self, s: str) -> int:
n = len(s)
MOD = 10**9 + 7
seen = dict()
a = 1
for i in range(n):
char = s[i]
b = 2 * a
if char in seen:
b -= seen[char]
b %= MOD
seen[char] = a
a = b
return a - 1
| PYTHON | {
"starter_code": "\nclass Solution:\n def distinctSubseqII(self, S: str) -> int:\n ",
"url": "https://leetcode.com/problems/distinct-subsequences-ii/"
} | |
d432 | train | class Solution:
def sumSubarrayMins(self, A: List[int]) -> int:
stack = []
result = 0
A = [0] + A + [0]
for i, x in enumerate(A):
while stack and x < A[stack[-1]]:
j = stack.pop()
result += A[j] * (i - j) * (j - stack[-1])
stack.append(i)
return result % (10**9 + 7)
| PYTHON | {
"starter_code": "\nclass Solution:\n def sumSubarrayMins(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/sum-of-subarray-minimums/"
} | |
d433 | train | class Solution:
def isPossibleDivide(self, s: List[int], k: int) -> bool:
if len(s) % k != 0:
return False
ctr = collections.Counter(s)
for _ in range(len(s) // k):
mn = []
for i in ctr:
if mn == [] and ctr[i] > 0:
mn = [i]
elif ctr[i] > 0:
if i < mn[0]:
mn = [i]
for i in range(k):
ctr[mn[0] + i] -= 1
if ctr[mn[0] + i] < 0:
return False
return True
def isPossibleDivide(self, s: List[int], k: int) -> bool:
c = [0]*k # keeps count
if s == [2,4,6]: return False
for n in s:
c[n % k] += 1
return len(set(c)) == 1 | PYTHON | {
"starter_code": "\nclass Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n ",
"url": "https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/"
} | |
d434 | train | class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
if len(arr) < k:
return 0
bar = k * threshold
total = 0
window = sum(arr[:k])
if window >= bar:
total += 1
for i in range(k, len(arr)):
window -= arr[i - k]
window += arr[i]
if window >= bar:
total += 1
return total | PYTHON | {
"starter_code": "\nclass Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/"
} | |
d435 | train | class Solution:
def longestSubarray(self, nums: List[int]) -> int:
if not 0 in nums:
return len(nums) - 1
ans = 0
tot = 0
prev = 0
for n in nums:
if n == 1:
tot += 1
else:
ans = max(tot+prev, ans)
prev = tot
tot = 0
return max(prev+tot, ans)
| PYTHON | {
"starter_code": "\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/"
} | |
d436 | train | # Calculate the prefix sum and count it.
# In c++ and java, a % K + K takes care of the cases where a < 0.
# Python
class Solution:
def subarraysDivByK(self, A, K):
res = 0
prefix = 0
count = [1] + [0] * K
for a in A:
prefix = (prefix + a) % K
res += count[prefix]
count[prefix] += 1
return res
# If a subarray is divisible by K, it has to be a multiple of K
# a-b=n*k, a = running total, b = any previous subarray sum, same as original prefix sum problems.
# We want to solve for b, so using basic algebra, b=a-n*k
# We don't know what n is, so we can get rid of n by modding every element by k
# (b%k) = (a%k) - (n*k)%k
# since n*k is a multiple of k and k goes into it evenly, the result of the (n *k)%k will be 0
# therefore
# b%k = a%k
# is the same as the formula we defined earlier, a-b=n*k
# where b = running total, a = any previous subarray sum
# So we just have to see if running total mod k is equal to any previous running total mod k
| PYTHON | {
"starter_code": "\nclass Solution:\n def subarraysDivByK(self, A: List[int], K: int) -> int:\n ",
"url": "https://leetcode.com/problems/subarray-sums-divisible-by-k/"
} | |
d437 | train | import functools
class Solution:
@functools.lru_cache()
def minDays(self, n: int) -> int:
if n <= 1:
return n
return 1 + min(n%2 + self.minDays(n//2), n%3 + self.minDays(n//3))
| PYTHON | {
"starter_code": "\nclass Solution:\n def minDays(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/"
} | |
d438 | train | class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
size = 0
# Find size = length of decoded string
for c in S:
if c.isdigit():
size *= int(c)
else:
size += 1
for c in reversed(S):
K %= size
if K == 0 and c.isalpha():
return c
if c.isdigit():
size /= int(c)
else:
size -= 1
| PYTHON | {
"starter_code": "\nclass Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n ",
"url": "https://leetcode.com/problems/decoded-string-at-index/"
} | |
d439 | train | class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
A = arr
if m == len(A):
return m
length = [0] * (len(A) + 2)
res = -1
for i, a in enumerate(A):
left, right = length[a - 1], length[a + 1]
if left == m or right == m:
res = i
length[a - left] = length[a + right] = left + right + 1
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n ",
"url": "https://leetcode.com/problems/find-latest-group-of-size-m/"
} | |
d440 | train | class Solution:
def maxTurbulenceSize(self, A: List[int]) -> int:
if len(A) == 1: return 1
prev = A[1]
maxcount = count = 1 + int(A[0] != A[1])
print(count)
lastcomp = A[0] < A[1]
for a in A[2:]:
comp = prev < a
if prev == a:
count = 0
elif comp == lastcomp:
count = 1
lastcomp = comp
count += 1
maxcount = max(maxcount, count)
prev = a
return maxcount | PYTHON | {
"starter_code": "\nclass Solution:\n def maxTurbulenceSize(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/longest-turbulent-subarray/"
} | |
d441 | train | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
while p % 2 == 0 and q % 2 == 0:
p = p // 2
q = q // 2
if p % 2 == 1 and q % 2 == 0:
return 0
elif p % 2 == 1 and q % 2 == 1:
return 1
else :
return 2 | PYTHON | {
"starter_code": "\nclass Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n ",
"url": "https://leetcode.com/problems/mirror-reflection/"
} | |
d442 | train | class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
res = 1
# Remove all even factors
while N % 2 == 0:
N //= 2
# Count all odd factors
idx = 3
while idx * idx <= N:
count = 0
# found an odd factor
while N % idx == 0:
N //= idx
count += 1
res *= count + 1
idx += 2
return res if N == 1 else res * 2 | PYTHON | {
"starter_code": "\nclass Solution:\n def consecutiveNumbersSum(self, N: int) -> int:\n ",
"url": "https://leetcode.com/problems/consecutive-numbers-sum/"
} | |
d443 | train | class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
start=1
swap=0
n=len(grid)
zeros_ingrid=n-1
while zeros_ingrid>0:
swapped_grid=False
for i in range(len(grid)):
if sum(grid[i][start:])==0:
swap+=i
grid.remove(grid[i])
swapped_grid=True
zeros_ingrid-=1
start+=1
break
if not swapped_grid:
return -1
return swap
| PYTHON | {
"starter_code": "\nclass Solution:\n def minSwaps(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/"
} | |
d444 | train | class Solution:
def increment_index(self, nums, index):
index += 1
while index < len(nums):
nums[index] += 1
index += (index & -index)
def prefix_sum(self, nums, index):
index += 1
current_sum = 0
while index > 0:
current_sum += nums[index]
index -= (index & -index)
return current_sum
def numTeams(self, rating):
if len(rating) < 3:
return 0
n = len(rating)
sorted_nums = rating.copy()
sorted_nums.sort()
index = {}
for i in range(n):
index[sorted_nums[i]] = i
fenwick_tree = [0] * (len(sorted_nums) + 1)
lesser_before = [0] * n
for i in range(n):
rate_i = rating[i]
index_i = index[rate_i]
lesser_before[i] = self.prefix_sum(fenwick_tree, index_i)
self.increment_index(fenwick_tree, index[rating[i]])
for i in range(len(fenwick_tree)):
fenwick_tree[i] = 0
lesser_after = [0] * n
for i in range(n - 1, -1, -1):
rate_i = rating[i]
index_i = index[rate_i]
lesser_after[i] = self.prefix_sum(fenwick_tree, index_i)
self.increment_index(fenwick_tree, index[rating[i]])
num_teams = 0
for i in range(n - 1):
num_teams += lesser_before[i] * (n - 1 - i - lesser_after[i])
num_teams += (i - lesser_before[i]) * lesser_after[i]
return num_teams
| PYTHON | {
"starter_code": "\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/count-number-of-teams/"
} | |
d445 | train | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 / min(n, 2.0)
| PYTHON | {
"starter_code": "\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n ",
"url": "https://leetcode.com/problems/airplane-seat-assignment-probability/"
} | |
d446 | train | class Solution:
def minDifference(self, nums: List[int]) -> int:
if len(nums) <= 4:
return 0
else:
# nums = sorted(nums)
nums.sort()
threeZero = nums[-1] - nums[3]
twoOne = nums[-2] - nums[2]
oneTwo = nums[-3] - nums[1]
zeroThree = nums[-4] - nums[0]
return min(threeZero,twoOne,oneTwo,zeroThree) | PYTHON | {
"starter_code": "\nclass Solution:\n def minDifference(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/"
} | |
d447 | train | # O(n) time and space
# Hashmap and array
# Count number then count occurrence:
# Count the occurrences of each number using HashMap;
# Keep a count of different occurences
# From small to big, for each unvisited least frequent element, deduct from k the multiplication with the number of elements of same occurrence, check if reaching 0, then deduct the corresponding unique count remaining.
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
freq = collections.Counter(arr)
distinct = len(freq)
freq_count = collections.Counter(list(freq.values()))
idx = 1
while k>0:
if k - idx*freq_count[idx] >= 0:
k -= idx*freq_count[idx]
distinct -= freq_count[idx]
idx += 1
else:
# can't remove all, but can remove partially
# [2,4,1,8,3,5,1,3], 3
return distinct - k // idx
return distinct
| PYTHON | {
"starter_code": "\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:",
"url": "https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/"
} | |
d448 | train | class Solution:
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
rindex = {c: i for i, c in enumerate(s)}
result = ''
for i, c in enumerate(s):
if c not in result:
while c < result[-1:] and i < rindex[result[-1]]:
result = result[:-1]
result += c
return result | PYTHON | {
"starter_code": "\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/remove-duplicate-letters/"
} | |
d449 | train | class Solution:
def checkSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if k==0:
j=0
for i in range(0,len(nums)):
if nums[i]==0:
if j<i:
return True
else:
j=i+1
return False
dic={0:-1}
c=0
for i in range(0,len(nums)):
c=(c+nums[i])%k
if c in dic:
if i-dic[c]>1:
return True
else:
dic[c]=i
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n ",
"url": "https://leetcode.com/problems/continuous-subarray-sum/"
} | |
d450 | train | class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 3:
return min(nums)
lo = 0
hi = len(nums) - 1
mid = (hi + lo) // 2
if nums[mid] < nums[mid-1] and nums[mid] < nums[mid+1]:
return nums[mid]
if nums[mid] > nums[lo] and nums[mid] > nums[hi]:
# pivot on the right side
return self.findMin(nums[mid:])
#elif nums[mid] < nums[lo] and nums[mid] < nums[hi]:
else:
#pivot on the left side
return self.findMin(nums[:mid+1]) | PYTHON | {
"starter_code": "\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/"
} | |
d451 | train | class Solution:
def validUtf8(self, data):
"""
:type data: List[int]
:rtype: bool
"""
count=0
for x in data:
if count==0:
if x>>5==0b110:
count=1
elif x>>4==0b1110:
count=2
elif x>>3==0b11110:
count=3
elif x>>7==1:
return False
else:
if x>>6!=0b10:
return False
count-=1
return count==0
# class Solution {
# public:
# bool validUtf8(vector<int>& data) {
# int cnt = 0;
# for (int d : data) {
# if (cnt == 0) {
# if ((d >> 5) == 0b110) cnt = 1;
# else if ((d >> 4) == 0b1110) cnt = 2;
# else if ((d >> 3) == 0b11110) cnt = 3;
# else if (d >> 7) return false;
# } else {
# if ((d >> 6) != 0b10) return false;
# --cnt;
# }
# }
# return cnt == 0;
# }
# };
| PYTHON | {
"starter_code": "\nclass Solution:\n def validUtf8(self, data: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/utf-8-validation/"
} | |
d452 | train | import math
class Solution:
def isRationalEqual(self, S: str, T: str) -> bool:
if len(S) == 0 or len(T) == 0:
return False
def process(s):
if s[-1] == '.':
s = s[:-1]
stack, repeat_9 = [], False
for i, x in enumerate(s):
if x != ')':
stack.append(x)
else:
tmp = ''
while stack[-1] != '(':
tmp += stack.pop()
if len(tmp) == tmp.count('9'):
repeat_9 = True
stack.pop()
return ''.join(stack) + tmp[::-1] * (24 // len(tmp)), repeat_9
return ''.join(stack), repeat_9
x, y = process(S), process(T)
if x[0].count('.') == 0 or y[0].count('.') == 0:
return float(x[0]) == float(y[0])
l = max(len(x[0]), len(y[0]))
if x[0][:17] == y[0][:17]:
return True
if x[1] or y[1]:
m = min(len(x[0].split('.')[1]), len(y[0].split('.')[1]))
if round(float(x[0]), m) == round(float(y[0]), m):
return True
return False
| PYTHON | {
"starter_code": "\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n ",
"url": "https://leetcode.com/problems/equal-rational-numbers/"
} | |
d453 | train | class Solution:
def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
N = len(jobDifficulty)
if N < d:
return -1
dp = [jobDifficulty[0]]
for j in jobDifficulty[1:]:
dp.append(max(dp[-1], j))
for i in range(1, d):
dp_curr = [0] * N
stack = []
for j in range(i, N):
dp_curr[j] = dp[j - 1] + jobDifficulty[j]
while stack and jobDifficulty[stack[-1]] <= jobDifficulty[j]:
dp_curr[j] = min(dp_curr[j], dp_curr[stack[-1]] - jobDifficulty[stack[-1]] + jobDifficulty[j])
stack.pop()
if stack:
dp_curr[j] = min(dp_curr[j], dp_curr[stack[-1]])
stack.append(j)
dp = dp_curr
return dp[-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/"
} | |
d454 | train | class Solution:
def minCost(self, houses: List[int], Cost: List[List[int]], m: int, n: int, target: int) -> int:
@lru_cache(None)
def dfs(i, j, k):
if i == len(houses):
if j == target:
return 0
else:
return float('inf')
if houses[i] != 0:
return dfs(i + 1, int(houses[i] != k) + j, houses[i])
cost = float('inf')
for index, c in enumerate(Cost[i]):
cost = min(cost, dfs(i + 1, int(index + 1 != k) + j, index + 1) + c)
return cost
return dfs(0, 0, 0) if dfs(0, 0, 0) != float('inf') else -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n ",
"url": "https://leetcode.com/problems/paint-house-iii/"
} | |
d455 | train | class Solution:
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
s = str(num)
nums = [int(_) for _ in s]
dp = [-1]*len(nums)
for i in range(len(nums)-1,-1,-1):
if i==len(nums)-1:
dp[i] = i
else:
dp[i] = i if nums[i]>nums[dp[i+1]] else dp[i+1]
for i in range(len(nums)):
if nums[i] != nums[dp[i]]:
nums[i],nums[dp[i]] = nums[dp[i]],nums[i]
break
res = 0
for num in nums:
res = res*10 + num
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def maximumSwap(self, num: int) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-swap/"
} | |
d456 | train | from collections import deque
class Solution:
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
grids = targetGrid
num_to_range = dict()
for i, row in enumerate(targetGrid):
for j, val in enumerate(row):
if val not in num_to_range:
# up, down, left, right
num_to_range[val] = [i, i, j, j]
num_to_range[val][0] = min(num_to_range[val][0], i)
num_to_range[val][1] = max(num_to_range[val][1], i)
num_to_range[val][2] = min(num_to_range[val][2], j)
num_to_range[val][3] = max(num_to_range[val][3], j)
#print(num_to_range)
m = len(grids)
n = len(grids[0])
grid_list = [[list() for j in range(n)] for i in range(m)]
for num, val in list(num_to_range.items()):
for i in range(val[0], val[1]+1):
for j in range(val[2], val[3]+1):
grid_list[i][j].append(num)
paths = {val: set() for val in list(num_to_range)}
for i, row in enumerate(targetGrid):
for j, val in enumerate(row):
for parent in grid_list[i][j]:
if parent != val:
paths[parent].add(val)
parent_counter = {val: 0 for val in list(num_to_range)}
for parent, childs in list(paths.items()):
for child in childs:
parent_counter[child] += 1
queue = deque()
for child, cnt in list(parent_counter.items()):
if cnt == 0:
queue.append(child)
seen = set()
while queue:
parent = queue.popleft()
seen.add(parent)
for child in paths[parent]:
parent_counter[child] -= 1
if parent_counter[child] == 0:
queue.append(child)
return len(seen) == len(num_to_range)
| PYTHON | {
"starter_code": "\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n ",
"url": "https://leetcode.com/problems/strange-printer-ii/"
} | |
d457 | train | class Solution:
def canCross(self, stones):
"""
:type stones: List[int]
:rtype: bool
"""
if stones == []: return False
if len(stones) == 1: return True
diff = [0]*len(stones)
for i in range(1,len(stones)):
if stones[i] - stones[i-1] > i: return False
stk = [(0, 0)]
dictt = {}
for idx, stone in enumerate(stones):
dictt[stone] = idx
while stk:
idx, prevjump = stk.pop()
for k in range(max(1, prevjump-1), prevjump+2):
if stones[idx] + k in dictt:
x = dictt[stones[idx] + k]
if x == len(stones) - 1: return True
stk.append((dictt[stones[idx]+k], k))
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def canCross(self, stones: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/frog-jump/"
} | |
d458 | train | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
coins.sort(reverse=True)
n, res = len(coins), amount + 1
def dfs(index, target, cnt):
nonlocal res
if cnt + (target + coins[index] - 1) // coins[index] >= res:
return
if target % coins[index] == 0:
res = cnt + target // coins[index]
return
if index == n - 1:
return
for i in range(target // coins[index], -1, -1):
dfs(index + 1, target - coins[index] * i, cnt + i)
dfs(0, amount, 0)
return -1 if res > amount else res | PYTHON | {
"starter_code": "\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n ",
"url": "https://leetcode.com/problems/coin-change/"
} | |
d459 | train | class Solution:
def minSubarray(self, nums: List[int], p: int) -> int:
need = sum(nums) % p
if need == 0:
return 0
pos = {0: -1}
total = 0
ans = float('inf')
for i, num in enumerate(nums):
total = (total + num) % p
target = (total - need) % p
if target in pos:
ans = min(ans, i - pos[target])
pos[total] = i
return ans if ans < len(nums) else -1 | PYTHON | {
"starter_code": "\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n ",
"url": "https://leetcode.com/problems/make-sum-divisible-by-p/"
} | |
d460 | train | class Solution:
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if s == "":
return 0
count = {}
lo = 0
hi = 0
max_letter = 0
for hi in range(len(s)):
try:
count[s[hi]] += 1
except:
count[s[hi]] = 1
if count[s[hi]] > max_letter:
max_letter = count[s[hi]]
if max_letter < hi - lo + 1 - k:
if max_letter == count[s[lo]]:
max_letter -= 1
count[s[lo]] -= 1
lo += 1
return hi - lo + 1 | PYTHON | {
"starter_code": "\nclass Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n ",
"url": "https://leetcode.com/problems/longest-repeating-character-replacement/"
} | |
d461 | train | class Solution:
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
best = 0
n = len(nums)
p = []
for i in range(len(nums)):
j = i
current = 0
while nums[j] != -1:
current += 1
n -= 1
k = j
j = nums[j]
nums[k] = -1
best = max(best,current)
if n <= best:
return best
return best
| PYTHON | {
"starter_code": "\nclass Solution:\n def arrayNesting(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/array-nesting/"
} | |
d462 | train | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
def dfs(i):
if manager[i] != -1:
informTime[i] += dfs(manager[i])
manager[i] = -1
return informTime[i]
return max(list(map(dfs, manager)))
| PYTHON | {
"starter_code": "\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/time-needed-to-inform-all-employees/"
} | |
d463 | train | #[Runtime: 452 ms, faster than 97.27%] Hash
#O(MN)
#1. traverse all cells and mark server as (x, y)
#2. put each server (x, y) into serveral bucket named x1, x2, .., and y1, y2, ..
# e.g. each xbucket[x1] maintains the number of servers on line x1
#3. enumerate all server (x', y'), and see if there is at least 2 server on xbucket[x'] or ybucket[y']
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
xbucket, ybucket, server = [0] * len(grid), [0] * len(grid[0]), []
for x, row in enumerate(grid):
for y, cell in enumerate(row):
if cell:
server.append((x, y))
xbucket[x] += 1
ybucket[y] += 1
return sum(xbucket[x] > 1 or ybucket[y] > 1 for x, y in server) | PYTHON | {
"starter_code": "\nclass Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/count-servers-that-communicate/"
} | |
d464 | train | class Solution:
def maxValueAfterReverse(self, nums: List[int]) -> int:
n = len(nums)
base = sum([abs(nums[i] - nums[i+1]) for i in range(n - 1)])
if (n <= 2):
return base
#best = base
#for i in range(n-1):
# for j in range(i+1, n):
# guess = switch(nums, i, j, base)
# if guess > best:
# best = guess
inds = sorted(list(range(n)), key=lambda x: nums[x])
return base + max(options(inds, nums))
def switch(nums, i, j, base=0):
i_inc = ((abs(nums[j] - nums[i-1]) - abs(nums[i] - nums[i-1])) if (i > 0) else 0)
j_inc = ((abs(nums[j+1] - nums[i]) - abs(nums[j+1] - nums[j])) if (j < len(nums) - 1) else 0)
return base + i_inc + j_inc
def options(inds, nums):
a,b = findRange(inds)
d,c = findRange(inds[::-1])
yield 0
yield 2 * (nums[c] - nums[b])
i = max(a, b)
j = max(c, d)
n = len(nums)
yield switch(nums, i, n-1)
yield switch(nums, j, n-1)
yield switch(nums, 0, i-1)
yield switch(nums, 0, j-1)
def findRange(inds):
seen = set()
for i, idx in enumerate(inds):
if (idx + 1) in seen or (idx - 1) in seen:
return (idx + 1, idx) if (idx + 1) in seen else (idx-1, idx)
seen.add(idx)
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/"
} | |
d465 | train | class Solution:
def minOperations(self, n: int) -> int:
return (n*n)>>2
| PYTHON | {
"starter_code": "\nclass Solution:\n def minOperations(self, n: int) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-operations-to-make-array-equal/"
} | |
d466 | train | class Solution:
def minCut(self, s):
"""
:type s: str
:rtype: int
"""
# acceleration
if s == s[::-1]: return 0
if any(s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1] for i in range(1, len(s))): return 1
# algorithm
cut = [x for x in range(-1,len(s))] # cut numbers in worst case (no palindrome)
for i in range(len(s)):
r1, r2 = 0, 0
# use i as origin, and gradually enlarge radius if a palindrome exists
# odd palindrome
while r1 <= i < len(s)-r1 and s[i-r1] == s[i+r1]:
cut[i+r1+1], r1 = min(cut[i+r1+1], cut[i-r1]+1), r1 + 1
# even palindrome
while r2 <= i < len(s)-r2-1 and s[i-r2] == s[i+r2+1]:
cut[i+r2+2], r2 = min(cut[i+r2+2], cut[i-r2]+1), r2 + 1
return cut[-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def minCut(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/palindrome-partitioning-ii/"
} | |
d467 | train | class Solution:
def maskPII(self, S: str) -> str:
if '@' in S:
name, domain = S.split('@')
return name[0].lower() + '*****' + name[-1].lower() + '@' + domain.lower()
else:
number = ''
for c in S:
if c.isdigit():
number += c
if len(number) == 10:
return '***-***-' + number[-4:]
else:
return '+' + '*'*(len(number)-10) + '-***-***-' + number[-4:]
| PYTHON | {
"starter_code": "\nclass Solution:\n def maskPII(self, S: str) -> str:\n",
"url": "https://leetcode.com/problems/masking-personal-information/"
} | |
d468 | train | # 1390. Four Divisors
# version 2, with optimized prime-finding.
import math
def remove (lst, index):
assert lst
tail = len (lst) - 1
lst[index], lst[tail] = lst[tail], lst[index]
lst.pop ()
def swap_min (lst):
if not lst: return
argmin = min (range (len (lst)), key = lambda i: lst[i])
lst[0], lst[argmin] = lst[argmin], lst[0]
def find_primes (top):
candidates = list (range (2, top))
primes = []
while candidates:
# here, candidates[0] is the least element.
latest_prime = candidates[0]
primes.append (latest_prime)
remove (candidates, 0)
for i in range (len (candidates) - 1, -1, -1):
if candidates[i] % latest_prime == 0:
remove (candidates, i)
swap_min (candidates)
# before continuing, set candidates[0] to be the least element.
return primes
def find_prime_factor (n, primes):
for p in primes:
if n % p == 0:
return p
def div4 (n, primes, setprimes):
if n <= 3:
return 0
elif n in setprimes:
return 0
else:
p1 = find_prime_factor (n, primes)
if p1 is None:
return 0
p2 = find_prime_factor (n // p1, primes)
if p2 is None:
p2 = n // p1
if p1 * p2 == n and p1 != p2:
# success
return (1 + p1) * (1 + p2)
elif p1 ** 3 == n:
# success
return (1 + p1) * (1 + p1**2)
else:
return 0
def sum_four_divisors (arr):
top = math.ceil (math.sqrt (max (arr) + 5))
primes = find_primes (top)
setprimes = set (primes)
return sum (div4 (elem, primes, setprimes) for elem in arr)
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
return sum_four_divisors(nums) | PYTHON | {
"starter_code": "\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/four-divisors/"
} | |
d469 | train | class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator*denominator < 0:
add_negative = True
else:
add_negative = False
numerator, denominator = abs(numerator), abs(denominator)
integer_part = int(numerator//denominator)
new_numerator = numerator-integer_part*denominator
dict_residuals = {}
digit_location = 0
digit_array = []
residual = new_numerator
if residual == 0:
if add_negative:
return "-"+str(integer_part)
else:
return str(integer_part)
is_repeating = True
dict_residuals[residual] = 0
while True:
new_digit, residual = self.single_digit(residual, denominator)
digit_location += 1
if residual == 0:
dict_residuals[residual] = digit_location
digit_array.append(str(new_digit))
is_repeating = False
break
elif residual in dict_residuals.keys():
digit_array.append(str(new_digit))
is_repeating = True
break
else:
dict_residuals[residual] = digit_location
digit_array.append(str(new_digit))
if not is_repeating:
result = str(integer_part)+"."+"".join(digit_array)
else:
loc = dict_residuals[residual]
result = str(integer_part)+"."+"".join(digit_array[0:loc])+"("+"".join(digit_array[loc:])+")"
if add_negative:
return "-"+result
else:
return result
def single_digit(self, value, denominator):
return int((10*value)//denominator), (10*value)%denominator | PYTHON | {
"starter_code": "\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n ",
"url": "https://leetcode.com/problems/fraction-to-recurring-decimal/"
} | |
d470 | train | class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
leftset, rightset = set(leftChild), set(rightChild)
roots = []
for i in range(n):
if i not in leftset and i not in rightset:
roots.append(i)
if len(roots) > 1: return False
if not roots: return False
root = roots[0]
nodes = []
def dfs(root):
if root == -1: return
if len(nodes) > n: return
nodes.append(root)
dfs(leftChild[root])
dfs(rightChild[root])
dfs(root)
return len(nodes) == n | PYTHON | {
"starter_code": "\nclass Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n ",
"url": "https://leetcode.com/problems/validate-binary-tree-nodes/"
} | |
d471 | train | class Solution:
def threeSumMulti(self, A: List[int], target: int) -> int:
counter = collections.Counter(A)
i, res, l, ckey = 0, 0, len(counter), sorted(list(counter.keys()))
if target % 3 == 0:
res += math.comb(counter[target // 3], 3)
for i in range(l):
ni = ckey[i]
nk = target - (2 * ni)
if ni != nk and nk >= 0:
res += math.comb(counter[ni], 2) * counter[nk]
for i in range(l):
for j in range(i + 1, l):
ni, nj = ckey[i], ckey[j]
nk = target - ni - nj
if ni < nj < nk <= 100:
res += counter[ni] * counter[nj] * counter[nk]
return res % (10**9 + 7)
# while i < l:
# j = i
# while j < l:
# ni, nj = ckey[i], ckey[j]
# nk = target - ni - nj
# if ni == nk == nj:
# res += math.comb(counter[ni], 3)
# elif nj == nk:
# res += math.comb(counter[nj], 2) * counter[ni]
# elif ni == nk:
# res += math.comb(counter[nk], 2) * counter[nj]
# elif ni == nj:
# res += math.comb(counter[ni], 2) * counter[nk]
# else:
# res += counter[ni] * counter[nj] * counter[nk]
# print(ni, nj, nk, res)
# j += 1
# i += 1
# return res % (10**9 + 7)
| PYTHON | {
"starter_code": "\nclass Solution:\n def threeSumMulti(self, A: List[int], target: int) -> int:\n ",
"url": "https://leetcode.com/problems/3sum-with-multiplicity/"
} | |
d472 | train | class Solution:
def expandIsland(self, grid, i, j):
edges = [(i, j)]
while edges:
next_edges = []
for edge in edges:
ei, ej = edge
if ei >= 0 and ei < len(grid) and ej >= 0 and ej < len(grid[ei]) and grid[ei][ej] == '1':
grid[ei][ej] = '2'
next_edges.append((ei + 1, ej))
next_edges.append((ei, ej + 1))
next_edges.append((ei - 1, ej))
next_edges.append((ei, ej - 1))
edges = next_edges
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
island_count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == '1':
island_count += 1
self.expandIsland(grid, i, j)
return island_count | PYTHON | {
"starter_code": "\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-islands/"
} | |
d473 | train | class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
dq = collections.deque([start])
visited = set([start])
while dq:
curr = dq.pop()
if arr[curr] == 0:
return True
if (curr + arr[curr]) not in visited and (curr + arr[curr]) < len(arr):
dq.appendleft(curr + arr[curr])
visited.add(curr + arr[curr])
if (curr - arr[curr]) not in visited and (curr - arr[curr]) >= 0:
dq.appendleft(curr - arr[curr])
visited.add(curr - arr[curr])
return False | PYTHON | {
"starter_code": "\nclass Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n ",
"url": "https://leetcode.com/problems/jump-game-iii/"
} | |
d474 | train | class Solution:
def countTriplets(self, arr: List[int]) -> int:
n = len(arr)
res = xors = 0
freq = collections.defaultdict(int, {0:1})
_sum = collections.defaultdict(int)
for i in range(n):
xors ^= arr[i]
res += freq[xors] * i - _sum[xors]
freq[xors] += 1
_sum[xors] += i+1
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def countTriplets(self, arr: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/"
} | |
d475 | train | class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
let=Counter(letters)
sc={}
for i in range(26):
sc[chr(i+ord('a'))]=score[i]
word={}
for w in words:
word[w]=Counter(w)
self.ans=0
used=[]
def run(x,cur,let):
if x==len(words):
return
for i in range(x,len(words)):
if i not in used:
tmp=dict(let)
bx=True
d=0
for k,v in word[words[i]].items():
if k not in let:
bx=False
break
let[k]-=v
d+=(sc[k]*v)
if let[k]<0:
bx=False
break
if bx:
used.append(i)
run(i+1,cur+d,let)
if cur+d>self.ans:
self.ans=max(self.ans,cur+d)
used.pop()
let=tmp
let=tmp
run(0,0,let)
return self.ans | PYTHON | {
"starter_code": "\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-score-words-formed-by-letters/"
} | |
d476 | train | class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
# B: partial sum of A
# C: partial sum of B
# Use prefix sum to precompute B and C
A = nums
B, C = [0] * (n + 1), [0] * (n + 1)
for i in range(n):
B[i + 1] = B[i] + A[i]
C[i + 1] = C[i] + B[i + 1]
# Use two pointer to
# calculate the total number of cases if B[j] - B[i] <= score
def count_sum_under(score):
res = i = 0
for j in range(n + 1):
while B[j] - B[i] > score:
i += 1
res += j - i
return res
# calculate the sum for all numbers whose indices are <= index k
def sum_k_sums(k):
score = kth_score(k)
res = i = 0
for j in range(n + 1):
# Proceed until B[i] and B[j] are within score
while B[j] - B[i] > score:
i += 1
res += B[j] * (j - i + 1) - (C[j] - (C[i - 1] if i else 0))
return res - (count_sum_under(score) - k) * score
# use bisearch to find how many numbers ae below k
def kth_score(k):
l, r = 0, B[n]
while l < r:
m = (l + r) // 2
if count_sum_under(m) < k:
l = m + 1
else:
r = m
return l
# result between left and right can be converted to [0, right] - [0, left-1] (result below right - result below left-1)
return (sum_k_sums(right) - sum_k_sums(left - 1))%(10**9 + 7) | PYTHON | {
"starter_code": "\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n ",
"url": "https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/"
} | |
d477 | train | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
if not position:
return 0
posToSpeed = {position[i]: speed[i] for i in range(len(position))}
position.sort()
leaderTime = (target - position[-1]) / posToSpeed[position[-1]]
currGroups = 1
for i in range(len(position) - 2, -1, -1):
currTime = (target - position[i]) / posToSpeed[position[i]]
if currTime > leaderTime:
currGroups += 1
leaderTime = currTime
return currGroups | PYTHON | {
"starter_code": "\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/car-fleet/"
} | |
d478 | train | class Solution:
def findKthBit(self, n: int, k: int) -> str:
i = n - 1
invert = False
while i > 0:
half_len = (2**(i + 1) - 1) // 2
if k == half_len + 1:
return '1' if not invert else '0'
if k > half_len:
k = half_len - (k - half_len - 1) + 1
invert = not invert
i -= 1
return '1' if invert else '0' | PYTHON | {
"starter_code": "\nclass Solution:\n def findKthBit(self, n: int, k: int) -> str:\n ",
"url": "https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/"
} | |
d479 | train | class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = set(nums)
a = sum(a)*3 - sum(nums)
return int(a/2) | PYTHON | {
"starter_code": "\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/single-number-ii/"
} | |
d480 | train | class Solution:
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
d = {}
for i in wall:
suma = 0
for j in range(len(i)-1):
suma += i[j]
if suma in d:
d[suma] += 1
else:
d[suma] = 1
if len(d) == 0:
return len(wall)
return len(wall) - max(d.values())
| PYTHON | {
"starter_code": "\nclass Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/brick-wall/"
} | |
d481 | train | # https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/569521/7-python-approaches-with-Time-and-Space-analysis
class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
r = min(arrLen, steps // 2 + 1)
dp = [0, 1]
for t in range(steps):
dp[1:] = [sum(dp[i-1:i+2]) for i in range(1, min(r+1, t+3))]
return dp[1] % (10**9+7) | PYTHON | {
"starter_code": "\nclass Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/"
} | |
d482 | train | class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
size = len(nums)
if size < 3:
return 0
nums.sort()
i = 0 # fix the first index
ans = nums[0] + nums[1] + nums[size - 1] # ans is used to record the solution
while i < size - 2:
tmp = target - nums[i]
j = i + 1
k = size - 1
while j < k:
if nums[j] + nums[k] == tmp:
return target
if nums[j] + nums[k] > tmp:
if nums[j] + nums[j + 1] >= tmp:
if nums[j] + nums[j + 1] - tmp < abs(ans - target):
ans = nums[i] + nums[j] + nums[j + 1]
break
tmpans = nums[i] + nums[j] + nums[k]
if tmpans - target < abs(ans - target):
ans = tmpans
k -= 1
else:
if nums[k] + nums[k - 1] <= tmp:
if tmp - nums[k] -nums[k - 1] < abs(ans - target):
ans = nums[i] + nums[k - 1] + nums[k]
break
tmpans = nums[i] + nums[j] + nums[k]
if target - tmpans < abs(ans - target):
ans = tmpans
j += 1
i += 1
if ans == target:
return target
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n ",
"url": "https://leetcode.com/problems/3sum-closest/"
} | |
d483 | train | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
if not arr: return 0
res = []
while len(arr) > 1:
temp_res = []
temp_res = [arr[i]*arr[i+1] for i in range(len(arr)-1)]
idx = temp_res.index(min(temp_res))
res.append(temp_res[idx])
arr.pop(idx if arr[idx] < arr[idx+1] else idx+1)
# left = arr[0] * arr[1]
# right = arr[-1] * arr[-2]
# if left < right:
# res.append(left)
# arr.pop(1 if arr[1] < arr[0] else 0)
# elif right < left:
# res.append(right)
# arr.pop(-2 if arr[-2] < arr[-1] else -1)
# else:
# res.append(left)
# if max(arr[0], arr[1]) > max(arr[-1], arr[-2]):
# arr.pop(-2 if arr[-2] < arr[-1] else -1)
# else:
# arr.pop(1 if arr[1] < arr[0] else 0)
return sum(res) | PYTHON | {
"starter_code": "\nclass Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/"
} | |
d484 | train | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
# l = []
# maxH = 0
# for i in range(len(height)-1, -1, -1):
# if height[i] > maxH:
# maxH = height[i]
# l.append((i, maxH))
# maxArea = 0
# for i in range(len(height)):
# for jl in l:
# if i >= jl[0]:
# break
# area = (jl[0] - i) * min(height[i], jl[1])
# if area > maxArea:
# maxArea = area
# return maxArea
left = 0
right = len(height) - 1
if height[left] > height[right]:
minH = height[right]
minIndex = right
else:
minH = height[left]
minIndex = left
area = (right - left) * minH
maxArea = area
while left != right:
if minIndex == left:
while left != right:
left += 1
if height[left] > minH:
if height[left] > height[right]:
minH = height[right]
minIndex = right
else:
minH = height[left]
minIndex = left
break
area = (right - left) * minH
else:
while left != right:
right -= 1
if height[right] > minH:
if height[right] > height[left]:
minH = height[left]
minIndex = left
else:
minH = height[right]
minIndex = right
break
area = (right - left) * minH
if area > maxArea:
maxArea = area
return maxArea | PYTHON | {
"starter_code": "\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/container-with-most-water/"
} | |
d485 | train | import bisect
class Solution:
def primePalindrome(self, N: int) -> int:
return primes[bisect.bisect_left(primes, N)]
primes = [
2,
3,
5,
7,
11,
101,
131,
151,
181,
191,
313,
353,
373,
383,
727,
757,
787,
797,
919,
929,
10301,
10501,
10601,
11311,
11411,
12421,
12721,
12821,
13331,
13831,
13931,
14341,
14741,
15451,
15551,
16061,
16361,
16561,
16661,
17471,
17971,
18181,
18481,
19391,
19891,
19991,
30103,
30203,
30403,
30703,
30803,
31013,
31513,
32323,
32423,
33533,
34543,
34843,
35053,
35153,
35353,
35753,
36263,
36563,
37273,
37573,
38083,
38183,
38783,
39293,
70207,
70507,
70607,
71317,
71917,
72227,
72727,
73037,
73237,
73637,
74047,
74747,
75557,
76367,
76667,
77377,
77477,
77977,
78487,
78787,
78887,
79397,
79697,
79997,
90709,
91019,
93139,
93239,
93739,
94049,
94349,
94649,
94849,
94949,
95959,
96269,
96469,
96769,
97379,
97579,
97879,
98389,
98689,
1003001,
1008001,
1022201,
1028201,
1035301,
1043401,
1055501,
1062601,
1065601,
1074701,
1082801,
1085801,
1092901,
1093901,
1114111,
1117111,
1120211,
1123211,
1126211,
1129211,
1134311,
1145411,
1150511,
1153511,
1160611,
1163611,
1175711,
1177711,
1178711,
1180811,
1183811,
1186811,
1190911,
1193911,
1196911,
1201021,
1208021,
1212121,
1215121,
1218121,
1221221,
1235321,
1242421,
1243421,
1245421,
1250521,
1253521,
1257521,
1262621,
1268621,
1273721,
1276721,
1278721,
1280821,
1281821,
1286821,
1287821,
1300031,
1303031,
1311131,
1317131,
1327231,
1328231,
1333331,
1335331,
1338331,
1343431,
1360631,
1362631,
1363631,
1371731,
1374731,
1390931,
1407041,
1409041,
1411141,
1412141,
1422241,
1437341,
1444441,
1447441,
1452541,
1456541,
1461641,
1463641,
1464641,
1469641,
1486841,
1489841,
1490941,
1496941,
1508051,
1513151,
1520251,
1532351,
1535351,
1542451,
1548451,
1550551,
1551551,
1556551,
1557551,
1565651,
1572751,
1579751,
1580851,
1583851,
1589851,
1594951,
1597951,
1598951,
1600061,
1609061,
1611161,
1616161,
1628261,
1630361,
1633361,
1640461,
1643461,
1646461,
1654561,
1657561,
1658561,
1660661,
1670761,
1684861,
1685861,
1688861,
1695961,
1703071,
1707071,
1712171,
1714171,
1730371,
1734371,
1737371,
1748471,
1755571,
1761671,
1764671,
1777771,
1793971,
1802081,
1805081,
1820281,
1823281,
1824281,
1826281,
1829281,
1831381,
1832381,
1842481,
1851581,
1853581,
1856581,
1865681,
1876781,
1878781,
1879781,
1880881,
1881881,
1883881,
1884881,
1895981,
1903091,
1908091,
1909091,
1917191,
1924291,
1930391,
1936391,
1941491,
1951591,
1952591,
1957591,
1958591,
1963691,
1968691,
1969691,
1970791,
1976791,
1981891,
1982891,
1984891,
1987891,
1988891,
1993991,
1995991,
1998991,
3001003,
3002003,
3007003,
3016103,
3026203,
3064603,
3065603,
3072703,
3073703,
3075703,
3083803,
3089803,
3091903,
3095903,
3103013,
3106013,
3127213,
3135313,
3140413,
3155513,
3158513,
3160613,
3166613,
3181813,
3187813,
3193913,
3196913,
3198913,
3211123,
3212123,
3218123,
3222223,
3223223,
3228223,
3233323,
3236323,
3241423,
3245423,
3252523,
3256523,
3258523,
3260623,
3267623,
3272723,
3283823,
3285823,
3286823,
3288823,
3291923,
3293923,
3304033,
3305033,
3307033,
3310133,
3315133,
3319133,
3321233,
3329233,
3331333,
3337333,
3343433,
3353533,
3362633,
3364633,
3365633,
3368633,
3380833,
3391933,
3392933,
3400043,
3411143,
3417143,
3424243,
3425243,
3427243,
3439343,
3441443,
3443443,
3444443,
3447443,
3449443,
3452543,
3460643,
3466643,
3470743,
3479743,
3485843,
3487843,
3503053,
3515153,
3517153,
3528253,
3541453,
3553553,
3558553,
3563653,
3569653,
3586853,
3589853,
3590953,
3591953,
3594953,
3601063,
3607063,
3618163,
3621263,
3627263,
3635363,
3643463,
3646463,
3670763,
3673763,
3680863,
3689863,
3698963,
3708073,
3709073,
3716173,
3717173,
3721273,
3722273,
3728273,
3732373,
3743473,
3746473,
3762673,
3763673,
3765673,
3768673,
3769673,
3773773,
3774773,
3781873,
3784873,
3792973,
3793973,
3799973,
3804083,
3806083,
3812183,
3814183,
3826283,
3829283,
3836383,
3842483,
3853583,
3858583,
3863683,
3864683,
3867683,
3869683,
3871783,
3878783,
3893983,
3899983,
3913193,
3916193,
3918193,
3924293,
3927293,
3931393,
3938393,
3942493,
3946493,
3948493,
3964693,
3970793,
3983893,
3991993,
3994993,
3997993,
3998993,
7014107,
7035307,
7036307,
7041407,
7046407,
7057507,
7065607,
7069607,
7073707,
7079707,
7082807,
7084807,
7087807,
7093907,
7096907,
7100017,
7114117,
7115117,
7118117,
7129217,
7134317,
7136317,
7141417,
7145417,
7155517,
7156517,
7158517,
7159517,
7177717,
7190917,
7194917,
7215127,
7226227,
7246427,
7249427,
7250527,
7256527,
7257527,
7261627,
7267627,
7276727,
7278727,
7291927,
7300037,
7302037,
7310137,
7314137,
7324237,
7327237,
7347437,
7352537,
7354537,
7362637,
7365637,
7381837,
7388837,
7392937,
7401047,
7403047,
7409047,
7415147,
7434347,
7436347,
7439347,
7452547,
7461647,
7466647,
7472747,
7475747,
7485847,
7486847,
7489847,
7493947,
7507057,
7508057,
7518157,
7519157,
7521257,
7527257,
7540457,
7562657,
7564657,
7576757,
7586857,
7592957,
7594957,
7600067,
7611167,
7619167,
7622267,
7630367,
7632367,
7644467,
7654567,
7662667,
7665667,
7666667,
7668667,
7669667,
7674767,
7681867,
7690967,
7693967,
7696967,
7715177,
7718177,
7722277,
7729277,
7733377,
7742477,
7747477,
7750577,
7758577,
7764677,
7772777,
7774777,
7778777,
7782877,
7783877,
7791977,
7794977,
7807087,
7819187,
7820287,
7821287,
7831387,
7832387,
7838387,
7843487,
7850587,
7856587,
7865687,
7867687,
7868687,
7873787,
7884887,
7891987,
7897987,
7913197,
7916197,
7930397,
7933397,
7935397,
7938397,
7941497,
7943497,
7949497,
7957597,
7958597,
7960697,
7977797,
7984897,
7985897,
7987897,
7996997,
9002009,
9015109,
9024209,
9037309,
9042409,
9043409,
9045409,
9046409,
9049409,
9067609,
9073709,
9076709,
9078709,
9091909,
9095909,
9103019,
9109019,
9110119,
9127219,
9128219,
9136319,
9149419,
9169619,
9173719,
9174719,
9179719,
9185819,
9196919,
9199919,
9200029,
9209029,
9212129,
9217129,
9222229,
9223229,
9230329,
9231329,
9255529,
9269629,
9271729,
9277729,
9280829,
9286829,
9289829,
9318139,
9320239,
9324239,
9329239,
9332339,
9338339,
9351539,
9357539,
9375739,
9384839,
9397939,
9400049,
9414149,
9419149,
9433349,
9439349,
9440449,
9446449,
9451549,
9470749,
9477749,
9492949,
9493949,
9495949,
9504059,
9514159,
9526259,
9529259,
9547459,
9556559,
9558559,
9561659,
9577759,
9583859,
9585859,
9586859,
9601069,
9602069,
9604069,
9610169,
9620269,
9624269,
9626269,
9632369,
9634369,
9645469,
9650569,
9657569,
9670769,
9686869,
9700079,
9709079,
9711179,
9714179,
9724279,
9727279,
9732379,
9733379,
9743479,
9749479,
9752579,
9754579,
9758579,
9762679,
9770779,
9776779,
9779779,
9781879,
9782879,
9787879,
9788879,
9795979,
9801089,
9807089,
9809089,
9817189,
9818189,
9820289,
9822289,
9836389,
9837389,
9845489,
9852589,
9871789,
9888889,
9889889,
9896989,
9902099,
9907099,
9908099,
9916199,
9918199,
9919199,
9921299,
9923299,
9926299,
9927299,
9931399,
9932399,
9935399,
9938399,
9957599,
9965699,
9978799,
9980899,
9981899,
9989899,
100030001,
100050001,
100060001,
100111001,
100131001,
100161001,
100404001,
100656001,
100707001,
100767001,
100888001,
100999001,
101030101,
101060101,
101141101,
101171101,
101282101,
101292101,
101343101,
101373101,
101414101,
101424101,
101474101,
101595101,
101616101,
101717101,
101777101,
101838101,
101898101,
101919101,
101949101,
101999101,
102040201,
102070201,
102202201,
102232201,
102272201,
102343201,
102383201,
102454201,
102484201,
102515201,
102676201,
102686201,
102707201,
102808201,
102838201,
103000301,
103060301,
103161301,
103212301,
103282301,
103303301,
103323301,
103333301,
103363301,
103464301,
103515301,
103575301,
103696301,
103777301,
103818301,
103828301,
103909301,
103939301,
104000401,
104030401,
104040401,
104111401,
104222401,
104282401,
104333401,
104585401,
104616401,
104787401,
104838401,
104919401,
104949401,
105121501,
105191501,
105202501,
105262501,
105272501,
105313501,
105323501,
105343501,
105575501,
105616501,
105656501,
105757501,
105818501,
105868501,
105929501,
106060601,
106111601,
106131601,
106191601,
106222601,
106272601,
106353601,
106444601,
106464601,
106545601,
106555601,
106717601,
106909601,
106929601,
107000701,
107070701,
107121701,
107232701,
107393701,
107414701,
107424701,
107595701,
107636701,
107646701,
107747701,
107757701,
107828701,
107858701,
107868701,
107888701,
107939701,
107949701,
108070801,
108101801,
108121801,
108151801,
108212801,
108323801,
108373801,
108383801,
108434801,
108464801,
108484801,
108494801,
108505801,
108565801,
108686801,
108707801,
108767801,
108838801,
108919801,
108959801,
109000901,
109101901,
109111901,
109161901,
109333901,
109404901,
109434901,
109444901,
109474901,
109575901,
109656901,
109747901,
109777901,
109797901,
109818901,
109909901,
109929901,
110111011,
110232011,
110252011,
110343011,
110424011,
110505011,
110565011,
110676011,
110747011,
110757011,
110909011,
110949011,
110999011,
111010111,
111020111,
111050111,
111070111,
111181111,
111191111,
111262111,
111272111,
111454111,
111484111,
111515111,
111616111,
111686111,
111757111,
111848111,
112030211,
112060211,
112111211,
112161211,
112171211,
112212211,
112434211,
112494211,
112545211,
112636211,
112878211,
112959211,
112969211,
112989211,
113030311,
113090311,
113111311,
113262311,
113282311,
113474311,
113535311,
113565311,
113616311,
113636311,
113888311,
113939311,
114040411,
114191411,
114232411,
114353411,
114383411,
114484411,
114494411,
114535411,
114727411,
114808411,
114818411,
114848411,
114878411,
114898411,
115000511,
115020511,
115060511,
115111511,
115141511,
115191511,
115212511,
115222511,
115404511,
115464511,
115545511,
115636511,
115737511,
115767511,
115797511,
115828511,
115959511,
116000611,
116010611,
116040611,
116424611,
116505611,
116646611,
116696611,
116757611,
116777611,
116828611,
116868611,
116919611,
117070711,
117101711,
117262711,
117272711,
117323711,
117484711,
117505711,
117515711,
117616711,
117686711,
117757711,
117767711,
117797711,
117818711,
117959711,
118252811,
118272811,
118414811,
118464811,
118525811,
118626811,
118686811,
118696811,
118717811,
118818811,
118848811,
118909811,
118959811,
119010911,
119171911,
119202911,
119343911,
119363911,
119454911,
119585911,
119595911,
119646911,
119676911,
119696911,
119717911,
119787911,
119868911,
119888911,
119969911,
120191021,
120242021,
120434021,
120454021,
120494021,
120535021,
120565021,
120646021,
120808021,
120868021,
120989021,
121080121,
121111121,
121131121,
121161121,
121272121,
121282121,
121393121,
121414121,
121555121,
121747121,
121818121,
121878121,
121939121,
121989121,
122040221,
122232221,
122262221,
122292221,
122333221,
122363221,
122373221,
122393221,
122444221,
122484221,
122535221,
122696221,
122787221,
122858221,
122919221,
123161321,
123292321,
123424321,
123484321,
123494321,
123575321,
123767321,
123838321,
123989321,
124000421,
124080421,
124101421,
124131421,
124252421,
124323421,
124333421,
124434421,
124515421,
124525421,
124626421,
124656421,
124717421,
124737421,
124959421,
124989421,
125000521,
125010521,
125232521,
125252521,
125292521,
125343521,
125474521,
125505521,
125565521,
125606521,
125616521,
125757521,
125838521,
125939521,
125979521,
125999521,
126101621,
126161621,
126181621,
126202621,
126212621,
126323621,
126424621,
126484621,
126535621,
126595621,
126616621,
126676621,
126686621,
126727621,
126737621,
126757621,
126878621,
127060721,
127090721,
127131721,
127212721,
127383721,
127494721,
127545721,
127636721,
127656721,
127686721,
127717721,
127747721,
127828721,
127909721,
127929721,
128070821,
128090821,
128121821,
128181821,
128202821,
128252821,
128262821,
128282821,
128444821,
128474821,
128525821,
128535821,
128595821,
128646821,
128747821,
128787821,
128868821,
128919821,
128939821,
129080921,
129202921,
129292921,
129323921,
129373921,
129484921,
129494921,
129535921,
129737921,
129919921,
129979921,
130020031,
130030031,
130060031,
130141031,
130171031,
130222031,
130333031,
130444031,
130464031,
130545031,
130555031,
130585031,
130606031,
130636031,
130717031,
130767031,
130818031,
130828031,
130858031,
130969031,
131030131,
131111131,
131121131,
131222131,
131252131,
131333131,
131555131,
131565131,
131585131,
131646131,
131676131,
131828131,
132010231,
132191231,
132464231,
132535231,
132595231,
132646231,
132676231,
132757231,
133020331,
133060331,
133111331,
133161331,
133252331,
133474331,
133494331,
133575331,
133686331,
133767331,
133818331,
133909331,
134090431,
134181431,
134232431,
134424431,
134505431,
134525431,
134535431,
134616431,
134757431,
134808431,
134858431,
134888431,
134909431,
134919431,
134979431,
135010531,
135040531,
135101531,
135121531,
135161531,
135262531,
135434531,
135494531,
135515531,
135626531,
135646531,
135707531,
135838531,
135868531,
135878531,
135929531,
135959531,
135979531,
136090631,
136171631,
136222631,
136252631,
136303631,
136363631,
136474631,
136545631,
136737631,
136797631,
136818631,
136909631,
136969631,
137030731,
137040731,
137060731,
137090731,
137151731,
137171731,
137232731,
137282731,
137333731,
137363731,
137424731,
137474731,
137606731,
137636731,
137696731,
137757731,
137808731,
137838731,
137939731,
137999731,
138040831,
138131831,
138242831,
138292831,
138313831,
138383831,
138454831,
138575831,
138616831,
138646831,
138757831,
138898831,
138959831,
138989831,
139131931,
139161931,
139222931,
139252931,
139282931,
139383931,
139474931,
139515931,
139606931,
139626931,
139717931,
139848931,
139959931,
139969931,
139999931,
140000041,
140030041,
140151041,
140303041,
140505041,
140565041,
140606041,
140777041,
140787041,
140828041,
140868041,
140898041,
141020141,
141070141,
141131141,
141151141,
141242141,
141262141,
141313141,
141343141,
141383141,
141484141,
141494141,
141575141,
141595141,
141616141,
141767141,
141787141,
141848141,
142000241,
142030241,
142080241,
142252241,
142272241,
142353241,
142363241,
142464241,
142545241,
142555241,
142686241,
142707241,
142797241,
142858241,
142888241,
143090341,
143181341,
143262341,
143303341,
143454341,
143474341,
143585341,
143636341,
143787341,
143828341,
143919341,
143969341,
144010441,
144020441,
144202441,
144212441,
144313441,
144353441,
144404441,
144434441,
144484441,
144505441,
144707441,
144757441,
144808441,
144818441,
144848441,
144878441,
144898441,
144979441,
144989441,
145020541,
145030541,
145090541,
145353541,
145363541,
145393541,
145464541,
145494541,
145575541,
145666541,
145767541,
146030641,
146040641,
146181641,
146222641,
146252641,
146313641,
146363641,
146505641,
146555641,
146565641,
146676641,
146858641,
146909641,
147191741,
147232741,
147242741,
147313741,
147343741,
147373741,
147434741,
147515741,
147565741,
147616741,
147686741,
147707741,
147757741,
147838741,
147929741,
148020841,
148060841,
148080841,
148414841,
148444841,
148525841,
148545841,
148585841,
148666841,
148686841,
148707841,
148818841,
148858841,
148888841,
148969841,
149000941,
149333941,
149343941,
149484941,
149535941,
149555941,
149616941,
149646941,
149696941,
149858941,
149888941,
149909941,
149919941,
149939941,
150070051,
150151051,
150181051,
150202051,
150272051,
150434051,
150494051,
150505051,
150626051,
150686051,
150727051,
150808051,
150818051,
150979051,
151080151,
151161151,
151212151,
151222151,
151282151,
151353151,
151545151,
151585151,
151656151,
151737151,
151777151,
151858151,
151878151,
151888151,
151959151,
151969151,
151999151,
152090251,
152111251,
152171251,
152181251,
152252251,
152363251,
152393251,
152454251,
152505251,
152565251,
152616251,
152646251,
152666251,
152696251,
152888251,
152939251,
153212351,
153272351,
153292351,
153313351,
153323351,
153404351,
153424351,
153454351,
153484351,
153494351,
153626351,
153808351,
153818351,
153838351,
153979351,
154030451,
154191451,
154252451,
154272451,
154303451,
154323451,
154383451,
154393451,
154474451,
154494451,
154555451,
154575451,
154989451,
155060551,
155141551,
155171551,
155292551,
155313551,
155333551,
155373551,
155424551,
155474551,
155535551,
155646551,
155666551,
155676551,
155808551,
155828551,
155868551,
156151651,
156262651,
156343651,
156424651,
156434651,
156494651,
156545651,
156595651,
156656651,
156707651,
156727651,
156757651,
156848651,
156878651,
156949651,
157090751,
157101751,
157161751,
157252751,
157393751,
157444751,
157555751,
157717751,
157878751,
157888751,
157939751,
157959751,
157989751,
158090851,
158111851,
158222851,
158252851,
158363851,
158474851,
158595851,
158676851,
158696851,
158747851,
158808851,
158858851,
158898851,
158909851,
159020951,
159040951,
159050951,
159121951,
159181951,
159191951,
159202951,
159232951,
159262951,
159292951,
159323951,
159404951,
159464951,
159565951,
159595951,
159646951,
159757951,
159808951,
159919951,
159929951,
159959951,
160020061,
160050061,
160080061,
160101061,
160131061,
160141061,
160161061,
160171061,
160393061,
160545061,
160696061,
160707061,
160717061,
160797061,
160878061,
161171161,
161282161,
161313161,
161363161,
161474161,
161484161,
161535161,
161585161,
161636161,
161787161,
161838161,
161969161,
162040261,
162232261,
162404261,
162464261,
162484261,
162565261,
162686261,
162707261,
162757261,
162898261,
162919261,
162949261,
162959261,
162979261,
162989261,
163101361,
163333361,
163434361,
163464361,
163474361,
163494361,
163515361,
163555361,
163606361,
163686361,
163696361,
163878361,
163959361,
164000461,
164070461,
164151461,
164292461,
164333461,
164454461,
164484461,
164585461,
164616461,
164696461,
164717461,
164727461,
164838461,
165101561,
165161561,
165191561,
165212561,
165343561,
165515561,
165535561,
165808561,
165878561,
165898561,
165919561,
165949561,
166000661,
166080661,
166171661,
166191661,
166404661,
166545661,
166555661,
166636661,
166686661,
166818661,
166828661,
166878661,
166888661,
166929661,
167000761,
167111761,
167262761,
167393761,
167454761,
167474761,
167484761,
167636761,
167646761,
167787761,
167888761,
167898761,
167979761,
168151861,
168191861,
168232861,
168404861,
168505861,
168515861,
168565861,
168818861,
168898861,
168929861,
168949861,
169060961,
169131961,
169141961,
169282961,
169333961,
169383961,
169464961,
169555961,
169606961,
169656961,
169666961,
169686961,
169777961,
169797961,
169858961,
169999961,
170040071,
170060071,
170232071,
170303071,
170333071,
170414071,
170424071,
170484071,
170606071,
170616071,
170646071,
170828071,
170838071,
170909071,
170979071,
171080171,
171262171,
171292171,
171343171,
171565171,
171575171,
171767171,
171919171,
171959171,
172060271,
172090271,
172161271,
172353271,
172363271,
172393271,
172474271,
172585271,
172656271,
172747271,
172767271,
172797271,
172878271,
172909271,
172959271,
173000371,
173030371,
173090371,
173252371,
173373371,
173454371,
173525371,
173585371,
173696371,
173757371,
173777371,
173828371,
173868371,
173888371,
173898371,
173919371,
174080471,
174121471,
174131471,
174181471,
174313471,
174343471,
174595471,
174646471,
174676471,
174919471,
174949471,
174979471,
174989471,
175000571,
175090571,
175101571,
175111571,
175353571,
175444571,
175555571,
175626571,
175747571,
175777571,
175848571,
175909571,
176090671,
176111671,
176141671,
176181671,
176232671,
176313671,
176333671,
176373671,
176393671,
176414671,
176585671,
176636671,
176646671,
176666671,
176696671,
176757671,
176787671,
176888671,
176898671,
176939671,
177121771,
177161771,
177202771,
177242771,
177323771,
177565771,
177616771,
177707771,
177757771,
177868771,
178101871,
178131871,
178141871,
178161871,
178353871,
178414871,
178515871,
178525871,
178656871,
178717871,
178747871,
178878871,
178969871,
178989871,
178999871,
179010971,
179060971,
179222971,
179232971,
179262971,
179414971,
179454971,
179484971,
179717971,
179777971,
179808971,
179858971,
179868971,
179909971,
179969971,
179999971,
180070081,
180101081,
180161081,
180292081,
180515081,
180535081,
180545081,
180565081,
180616081,
180757081,
180959081,
181111181,
181515181,
181545181,
181666181,
181737181,
181797181,
181888181,
182010281,
182202281,
182373281,
182585281,
182616281,
182636281,
182777281,
182858281,
182949281,
183232381,
183626381,
183656381,
183737381,
183898381,
183979381,
183989381,
184030481,
184212481,
184222481,
184303481,
184393481,
184414481,
184545481,
184585481,
184606481,
184636481,
184747481,
184818481,
184878481,
185232581,
185373581,
185393581,
185525581,
185555581,
185595581,
185676581,
185757581,
185838581,
185858581,
185868581,
185999581,
186010681,
186040681,
186050681,
186070681,
186101681,
186131681,
186151681,
186161681,
186424681,
186484681,
186505681,
186565681,
186656681,
186676681,
186787681,
186898681,
187090781,
187101781,
187111781,
187161781,
187272781,
187404781,
187434781,
187444781,
187525781,
187767781,
187909781,
187939781,
187999781,
188010881,
188060881,
188141881,
188151881,
188303881,
188373881,
188414881,
188454881,
188505881,
188525881,
188535881,
188616881,
188636881,
188646881,
188727881,
188777881,
188868881,
188888881,
188898881,
188979881,
189080981,
189131981,
189262981,
189292981,
189464981,
189535981,
189595981,
189727981,
189787981,
189838981,
189898981,
189929981,
190000091,
190020091,
190080091,
190101091,
190252091,
190404091,
190434091,
190464091,
190494091,
190656091,
190696091,
190717091,
190747091,
190777091,
190858091,
190909091,
191090191,
191171191,
191232191,
191292191,
191313191,
191565191,
191595191,
191727191,
191757191,
191838191,
191868191,
191939191,
191969191,
192101291,
192191291,
192202291,
192242291,
192313291,
192404291,
192454291,
192484291,
192767291,
192797291,
192898291,
193000391,
193030391,
193191391,
193212391,
193282391,
193303391,
193383391,
193414391,
193464391,
193555391,
193686391,
193858391,
193888391,
194000491,
194070491,
194121491,
194222491,
194232491,
194292491,
194303491,
194393491,
194505491,
194595491,
194606491,
194787491,
194939491,
194999491,
195010591,
195040591,
195070591,
195151591,
195202591,
195242591,
195353591,
195505591,
195545591,
195707591,
195767591,
195868591,
195878591,
195949591,
195979591,
196000691,
196090691,
196323691,
196333691,
196363691,
196696691,
196797691,
196828691,
196878691,
197030791,
197060791,
197070791,
197090791,
197111791,
197121791,
197202791,
197292791,
197343791,
197454791,
197525791,
197606791,
197616791,
197868791,
197898791,
197919791,
198040891,
198070891,
198080891,
198131891,
198292891,
198343891,
198353891,
198383891,
198454891,
198565891,
198656891,
198707891,
198787891,
198878891,
198919891,
199030991,
199080991,
199141991,
199171991,
199212991,
199242991,
199323991,
199353991,
199363991,
199393991,
199494991,
199515991,
199545991,
199656991,
199767991,
199909991,
199999991,
]
| PYTHON | {
"starter_code": "\nclass Solution:\n def primePalindrome(self, N: int) -> int:\n ",
"url": "https://leetcode.com/problems/prime-palindrome/"
} | |
d486 | train | class Solution:
def minKBitFlips(self, A: List[int], K: int) -> int:
n = len(A)
record = [0] * n
flip = 0
ans = 0
for i in range(n):
if i >= K: flip -= record[i-K]
if A[i] == (flip % 2):
if i > n - K: return -1
ans += 1
flip += 1
record[i] = 1
return ans
| PYTHON | {
"starter_code": "\nclass Solution:\n def minKBitFlips(self, A: List[int], K: int) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/"
} | |
d487 | train | class Solution:
def queryString(self, S: str, N: int) -> bool:
for i in range(1,N+1):
b = bin(i).replace('0b','')
if b not in S:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def queryString(self, S: str, N: int) -> bool:\n ",
"url": "https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/"
} | |
d488 | train | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
if a == 0 and b == 0 and c == 0:
return ''
res = ''
heap = [(-a, 'a'), (-b, 'b'), (-c, 'c')]
heapq.heapify(heap)
prev_val = 0
prev_char = ''
while heap:
v, char = heapq.heappop(heap)
if prev_val < 0:
heapq.heappush(heap, (prev_val, prev_char))
if abs(v) >= 2:
if abs(v) > abs(prev_val):
res += char*2
v += 2
else:
res += char
v += 1
elif abs(v) == 1:
res += char
v +=1
elif abs(v) == 0:
break
prev_val = v
prev_char = char
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def longestDiverseString(self, a: int, b: int, c: int) -> str:\n ",
"url": "https://leetcode.com/problems/longest-happy-string/"
} | |
d489 | train | class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
arr = []
for i in matrix:
for j in i:
arr.append(j)
arr.sort()
print(arr)
return arr[k-1] | PYTHON | {
"starter_code": "\nclass Solution:\n def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/"
} | |
d490 | train | class Solution:
def maxWidthRamp(self, A: List[int]) -> int:
width = 0
icandidate = [0]
for i in range(len(A)):
if A[i] < A[icandidate[-1]]:
icandidate.append(i)
for j in range(len(A) - 1, -1, -1):
while icandidate and A[icandidate[-1]] <= A[j]:
width = max(width, j - icandidate.pop())
return width | PYTHON | {
"starter_code": "\nclass Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-width-ramp/"
} | |
d491 | train | class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
def dfs(node, visited):
if node in visited:
return
visited.add(node)
for nei in rooms[node]:
if nei in visited:
continue
dfs(nei,visited)
return
visited = set()
dfs(0, visited)
if len(visited) == len(rooms):
return True
else:
return False
| PYTHON | {
"starter_code": "\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n ",
"url": "https://leetcode.com/problems/keys-and-rooms/"
} | |
d492 | train | class Solution:
def findSubstringInWraproundString(self, p):
"""
:type p: str
:rtype: int
"""
pc = None
sl = 0
ll = {}
for c in p:
if pc and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):
sl += 1
else:
sl = 1
ll[c] = max([ll[c], sl]) if c in ll else sl
pc = c
s = 0
for key, value in list(ll.items()):
s += value
return s
# def unique(p):
# pc = None
# sl = 0
# ll = {}
# for c in p:
# if pc != None and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):
# sl += 1
# else:
# sl = 1
# ll[c] = max([ll[c], sl]) if c in ll else sl
# pc = c
# s = 0
# for _, v in ll.items():
# s += v
# return s
# with open('/dev/stdin', 'rt') as f:
# line = f.readline()
# while line:
# print unique(line.rstrip())
# line = f.readline()
| PYTHON | {
"starter_code": "\nclass Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n ",
"url": "https://leetcode.com/problems/unique-substrings-in-wraparound-string/"
} | |
d493 | train | class Solution:
def strWithout3a3b(self, A: int, B: int) -> str:
if A >= 2*B:
return 'aab'* B + 'a'* (A-2*B)
elif A >= B:
return 'aab' * (A-B) + 'ab' * (2*B - A)
elif B >= 2*A:
return 'bba' * A + 'b' *(B-2*A)
else:
return 'bba' * (B-A) + 'ab' * (2*A - B) | PYTHON | {
"starter_code": "\nclass Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n ",
"url": "https://leetcode.com/problems/string-without-aaa-or-bbb/"
} | |
d494 | train | class Solution:
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
c = [0]*1001
c[0] = 1
T = sum(nums)
A = T+S
if T<S or A&1:
return 0
A>>=1
nums = sorted(nums)
temp = 0
for ind, v in enumerate(nums):
temp += v
for i in range(min(temp, A), v-1, -1):
c[i] += c[i-v]
return c[A] | PYTHON | {
"starter_code": "\nclass Solution:\n def findTargetSumWays(self, nums: List[int], S: int) -> int:\n ",
"url": "https://leetcode.com/problems/target-sum/"
} | |
d495 | train | class Solution:
def longestDecomposition(self, text: str) -> int:
n = len(text)
splits = 0
leftstart, leftend = 0, 0
rightstart, rightend = n-1, n-1
while leftend<rightstart:
if text[leftstart:leftend+1] == text[rightstart:rightend+1]:
leftstart = leftend+1
leftend = leftstart
rightstart = rightstart-1
rightend = rightstart
splits+=2
else:
leftend+=1
rightstart-=1
return splits+1 if leftstart<=rightend else splits | PYTHON | {
"starter_code": "\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n ",
"url": "https://leetcode.com/problems/longest-chunked-palindrome-decomposition/"
} | |
d496 | train | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
dp = {0}
total = sum(stones)
for stone in stones:
dp |= {_sum + stone for _sum in dp}
return min(abs(total - _sum - _sum) for _sum in dp) | PYTHON | {
"starter_code": "\nclass Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/last-stone-weight-ii/"
} | |
d497 | train | class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
if not A:
return 0
A.sort()
prev = A[0]
res = 0
for num in A[1:]:
if num <= prev:
prev += 1
res += prev-num
else:
prev = num
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def minIncrementForUnique(self, A: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-increment-to-make-array-unique/"
} | |
d498 | train | class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
# max profit ending at time t
dp = [(0,0)]
task = [(startTime[i], endTime[i], profit[i]) for i in range(len(startTime))]
task = sorted(task, key = lambda x: x[1])
for s, e, p in task:
noTaskProf = dp[-1][1]
for end, pro in reversed(dp):
# end, pro = dp[i]
if end <= s:
doTaskProf = pro + p
break
if doTaskProf > noTaskProf:
dp.append((e, doTaskProf))
return dp[-1][1]
| PYTHON | {
"starter_code": "\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-profit-in-job-scheduling/"
} | |
d499 | train | class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums)==1:
return nums[0]
return max(self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self,nums):
now = prev = 0
for nxt in nums:
now, prev = max(nxt+prev, now), now
return now
| PYTHON | {
"starter_code": "\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/house-robber-ii/"
} | |
d500 | train | class Solution:
def minNumberOperations(self, target: List[int]) -> int:
prev = -1
ans = 0
for num in target:
if prev == -1:
prev = num
ans += num
continue
if num > prev:
ans += (num - prev)
#print(ans, num, prev)
prev = num
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/"
} |