_id
stringlengths 2
5
| partition
stringclasses 2
values | text
stringlengths 5
289k
| language
stringclasses 1
value | meta_information
dict | title
stringclasses 1
value |
---|---|---|---|---|---|
d1901 | train | class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
s=1
a=[[root,1]]
while 1:
b=[]
for p in a:
if p[0].left:
b.append([p[0].left,2*p[1]-1])
if p[0].right:
b.append([p[0].right,2*p[1]])
a=b
if a:
s=max(s,a[-1][1]-a[0][1]+1)
else:
break
return s | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def widthOfBinaryTree(self, root: TreeNode) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-width-of-binary-tree/"
} | |
d1902 | train | class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(len(grid)):
grid[i].insert(0, 0)
grid[i].append(0)
grid.insert(0, [0 for i in range(len(grid[0]))])
grid.append([0 for i in range(len(grid[0]))])
islands = []
max_length = 1
for i in range(1, len(grid) - 1):
for j in range(1, len(grid[0]) - 1):
if grid[i][j] != 1:
continue
island_id = len(islands)
length = 0
connect_length = 0
queue = [(i, j)]
grid[i][j] = 2 + island_id
while queue:
x, y = queue.pop()
for dx, dy in directions:
this_grid = grid[x + dx][y + dy]
if this_grid == 1:
grid[x + dx][y + dy] = 2 + island_id
queue.append((x + dx, y + dy))
elif isinstance(this_grid, list):
new_connect = 0
already = False
for old_island_id in this_grid:
if old_island_id != island_id:
new_connect += islands[old_island_id]
else:
already = True
if not already:
connect_length = max(connect_length, new_connect)
this_grid.append(island_id)
else:
grid[x + dx][y + dy] = [island_id]
length += 1
islands.append(length)
max_length = max(max_length, length + connect_length + 1)
return min(max_length, (len(grid) - 2) * (len(grid[0]) - 2)) | PYTHON | {
"starter_code": "\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/making-a-large-island/"
} | |
d1903 | train | class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
l=len(str(low))
f=len(str(high))
s=len(str(low)[0])
a=[]
for i in range(l,f+1):
while True:
t=''
if i+s>10:
break
for j in range(s,i+s):
t+=str(j)
if int(t)>high:
break
if int(t)<low:
s+=1
continue
s+=1
a.append(t)
s=1
return a | PYTHON | {
"starter_code": "\nclass Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n ",
"url": "https://leetcode.com/problems/sequential-digits/"
} | |
d1904 | train | class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
dist = [float(\"inf\")] * n
remain = set()
for i in range(0,n):
remain.add(i)
dist[0] = 0
remain.discard(0)
curr = 0
res = 0
while len(remain) > 0:
lo = float(\"inf\")
loind = -1
# curr is the next lowest
a,b = points[curr]
for r in remain:
x,y = points[r]
tempdist = abs(x-a) + abs(y-b)
if tempdist < dist[r]:
dist[r] = tempdist
tempdist = dist[r]
if tempdist < lo:
lo = tempdist
loind = r
res += lo
curr = loind
# remove curr from remain
remain.discard(curr)
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/min-cost-to-connect-all-points/"
} | |
d1905 | train | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
points.sort(key = lambda x: x[0]*x[0] + x[1]*x[1])
return points[:K] | PYTHON | {
"starter_code": "\nclass Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n ",
"url": "https://leetcode.com/problems/k-closest-points-to-origin/"
} | |
d1906 | train | from math import sqrt
class Solution:
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort()
l, prev = {}, {} # length, previous number(largest divisor in nums)
max_l, end_number = 0, None
for i in nums:
tmp_l, tmp_prev = 0, None
for j in range(1, 1 + int(sqrt(i))):
if i % j == 0:
tmp = i // j
if tmp in prev and l[tmp] > tmp_l:
tmp_l, tmp_prev = l[tmp], tmp
if j in prev and l[j] > tmp_l:
tmp_l, tmp_prev = l[j], j
tmp_l += 1
prev[i], l[i] = tmp_prev, tmp_l
if tmp_l > max_l:
max_l, end_number = tmp_l, i
ans = []
while end_number is not None:
ans.append(end_number)
end_number = prev[end_number]
return ans | PYTHON | {
"starter_code": "\nclass Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/largest-divisible-subset/"
} | |
d1907 | train | class Solution:
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key = lambda x: (-x[0], x[1]))
queue = []
for p in people:
queue.insert(p[1], p)
return queue
| PYTHON | {
"starter_code": "\nclass Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n ",
"url": "https://leetcode.com/problems/queue-reconstruction-by-height/"
} | |
d1908 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def getnode(root):
if not root:
return None
elif root.val == target.val:
return root
else:
return getnode(root.left) or getnode(root.right)
return getnode(cloned) | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n ",
"url": "https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/"
} | |
d1909 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
node = root
depth = 0
while node:
depth += 1
node = node.left
if depth <= 1:
return depth
lo, hi = 0, 2**(depth-2)
while lo < hi:
l = depth-3
mi = (lo+hi)//2
node = root
while l >= 0:
d = mi & 2**l
node = node.right if d > 0 else node.left
l -= 1
if node.left and node.right:
lo = mi+1
elif not node.left and not node.right:
hi = mi
else:
break
l, node = depth-3, root
while l >= 0:
d = mi & 2**l
node = node.right if d > 0 else node.left
l -= 1
return 2**(depth-1)-1 + 2*mi + int(node.left is not None) + int(node.right is not None) | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def countNodes(self, root: TreeNode) -> int:\n ",
"url": "https://leetcode.com/problems/count-complete-tree-nodes/"
} | |
d1910 | train | class Solution:
def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
memo = [[0 for j in range(cols)] for i in range(rows)]
ans = 0
if grid[0][0] == 1:
memo[0][0] = (1,1)
ans = 1
else:
memo[0][0] = (0,0)
for i in range(1,rows):
if grid[i][0] == 0:
memo[i][0] = (0,0)
else:
memo[i][0] = (memo[i-1][0][0]+1,1)
ans = 1
for j in range(1,cols):
if grid[0][j] == 0:
memo[0][j] = (0,0)
else:
memo[0][j] = (1,memo[0][j-1][1]+1)
ans = 1
for i in range(1,rows):
for j in range(1,cols):
if grid[i][j] == 0:
memo[i][j] = (0,0)
else:
memo[i][j] = (memo[i-1][j][0]+1, memo[i][j-1][1]+1)
ans = 1
for i in range(rows-1,0,-1):
for j in range(cols-1,0,-1):
l_min = min(memo[i][j][0],memo[i][j][1])
while l_min>ans:
if memo[i][j-l_min+1][0]>=l_min and memo[i-l_min+1][j][1]>=l_min:
ans = l_min
l_min -= 1
return ans*ans
| PYTHON | {
"starter_code": "\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/largest-1-bordered-square/"
} | |
d1911 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def kth(self, v, k):
for i in range(k-1):
if not v:
return None
v=v.next
return v
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k==1:
return head
kthnode=self.kth(head, k)
v=head
head=kthnode if kthnode else head
i=0
tmphead=v
while kthnode:
vprev=kthnode.next
for i in range(k):
v.next, v, vprev = vprev, v.next, v
kthnode=None if not kthnode else kthnode.next
tmphead.next=kthnode if kthnode else v
tmphead=v
return head | PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n ",
"url": "https://leetcode.com/problems/reverse-nodes-in-k-group/"
} | |
d1912 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
arr = []
p = head
while p:
arr.append(p.val)
p = p.next
arr.sort()
p = head
for el in arr:
p.val = el
p = p.next
return head | PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def sortList(self, head: ListNode) -> ListNode:\n ",
"url": "https://leetcode.com/problems/sort-list/"
} | |
d1913 | train | class Solution:
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
if ord(letters[-1]) <= ord(target):
return letters[0]
li = 0
ri = len(letters) - 1
while li <= ri:
if li == ri:
return letters[li]
mi = li + (ri - li)//2
if ord(letters[mi]) > ord(target):
ri = mi
else:
li = mi + 1 | PYTHON | {
"starter_code": "\nclass WordFilter:\n def __init__(self, words: List[str]):\n def f(self, prefix: str, suffix: str) -> int:\n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(prefix,suffix)",
"url": "https://leetcode.com/problems/prefix-and-suffix-search/"
} | |
d1914 | train | class Solution:
def prevPermOpt1(self, A: List[int]) -> List[int]:
n = len(A)
if n == 1: return A
tidx = -1
for i in range(n-2, -1, -1):
if A[i] > A[i+1]:
tidx = i
break
if tidx < 0: return A
sidx = -1
for j in range(n-1, tidx, -1):
if A[j] == A[j-1]: continue
if A[j] < A[tidx]:
sidx = j
break
A[tidx], A[sidx] = A[sidx], A[tidx]
return A | PYTHON | {
"starter_code": "\nclass Solution:\n def prevPermOpt1(self, A: List[int]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/previous-permutation-with-one-swap/"
} | |
d1915 | train | class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
dcosts = sorted(costs, key=lambda i: i[0] - i[1])
n = len(costs) // 2
acost = sum(c[0] for c in dcosts[:n])
bcost = sum(c[1] for c in dcosts[n:])
return acost + bcost | PYTHON | {
"starter_code": "\nclass Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/two-city-scheduling/"
} | |
d1916 | train | '''
\"aabcaca\"
0123456
x
devide conquer
先找到第一个stamp把string分成左右两部分(必须要)(On
然后从长到短用stamp的头match左边的部分,直到match到最头 如果不能到最头则退出
从长到短用stamp的尾巴match右边,直到match到尾巴,如果不能match到最尾巴 则 继续找下一个stamp
能把他分成左右
这时的左边有个offset了,比如****b** offset是3,只要stamp的长度不超过头且能match上,就可以
这个解法可以有nwin*M^2 其中m平方是在用stamp去match的时候最坏能从stamp最长match到1
可以给出最短match路径
'''
class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
ans = []
offset = 0
while target!='':
x = target.find(stamp)
if x==-1:
return []
ans.append(x+offset)
can_stamp,indices = self.moveLeft(stamp,target[:x],offset)
if not can_stamp:
return []
ans.extend(indices)
offset,target,indices = self.moveRight(stamp,target[x+len(stamp):],
offset+x+len(stamp))
ans.extend(indices)
return ans[::-1]
def moveLeft(self,stamp,s,offset):
ans = []
while s:
for ind in range(1,len(stamp)):
additional = 0
if ind>len(s):
if offset == 0:
continue
additional = ind - len(s)
if stamp[additional:ind]==s[-ind:]:
ans.append(offset+len(s)-ind)
s=s[:-ind]
break
else:
return False,[]
return True,ans
def moveRight(self,stamp,s,offset):
ans = []
while s:
for ind in range(1,len(stamp)):
if stamp[-ind:]==s[:ind]:
ans.append(offset+ind-len(stamp))
offset+=ind
s=s[ind:]
break
else:
return offset,s,ans
return offset,s,ans
| PYTHON | {
"starter_code": "\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n ",
"url": "https://leetcode.com/problems/stamping-the-sequence/"
} | |
d1917 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def currentmax(self,root):
leftval = 0
if root.left != None:
leftval = self.currentmax(root.left)
leftval = 0 if leftval < 0 else leftval
rightval = 0
if root.right != None:
rightval = self.currentmax(root.right)
rightval = 0 if rightval < 0 else rightval
currentnode = leftval + rightval + root.val
if self.flag == 0:
self.ans = currentnode
self.flag = 1
else:
self.ans = self.ans if self.ans > currentnode else currentnode
return root.val + (leftval if leftval > rightval else rightval)
def maxPathSum(self, root):
self.ans = 0
self.flag = 0
self.currentmax(root)
return self.ans | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def maxPathSum(self, root: TreeNode) -> int:\n ",
"url": "https://leetcode.com/problems/binary-tree-maximum-path-sum/"
} | |
d1918 | train | class Solution(object):
loc=0
lastloc=-1
f=''
def getNext(self,formular,locked=False):
stype=0 # 0:null, 1:numeric, 2/20: Elem, 3: parenthesis
ret=0
if self.loc==self.lastloc: return (0,0)
i=self.loc
while i <len(formular):
if stype in (0,1) and formular[i].isnumeric():
ret=int(formular[i])+ret*10
stype=1
elif stype==0 and formular[i].isupper():
stype=20
ret=formular[i]
elif stype in (20,2) and formular[i].islower():
stype=2
ret+=formular[i]
elif stype==0 and formular[i] in "()":
stype=3+"()".index(formular[i])
ret=formular[i]
else: break
i+=1
if not locked:
self.lastloc=self.loc
self.loc=i
return (stype,ret)
def countOfAtoms(self, formula):
stk=[]
cnt={}
r=''
self.loc=0
n=self.getNext(formula)
while n!=(0,0):
if n[0] in (2,3,20):
stk.append([n[1],1])
elif n[0]==1:
stk[-1][1]=n[1]
elif n[0]==4:
time=1
i=-1
if self.getNext(formula,True)[0]==1:
time=self.getNext(formula)[1]
while stk[i][0]!='(':
stk[i][1]*=time
i-=1
stk[i][0]='$'
n=self.getNext(formula)
while any(stk):
n=stk.pop()
if n[0]!='$':
cnt[n[0]]=cnt.get(n[0],0)+n[1]
for i in sorted(cnt.keys()):
r+="%s%d"%(i,cnt[i]) if cnt[i]>1 else i
return r | PYTHON | {
"starter_code": "\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n ",
"url": "https://leetcode.com/problems/number-of-atoms/"
} | |
d1919 | train | from collections import defaultdict
class Solution:
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = defaultdict(list)
for from_, to_ in tickets:
graph[from_].append(to_)
for each in graph:
graph[each].sort()
res = []
self.dfs(graph, "JFK", res)
return res[::-1]
def dfs(self, graph, from_, results):
while graph[from_]:
curr = graph[from_].pop(0)
self.dfs(graph, curr, results)
results.append(from_) | PYTHON | {
"starter_code": "\nclass Solution:\n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/reconstruct-itinerary/"
} | |
d1920 | train | class Solution:
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
n = numCourses
graph = {}
for post, pre in prerequisites:
if pre in graph:
graph[pre].append(post)
else:
graph[pre] = [post]
WHITE = 0 # never explored. NOT CHECKED
GREY = 1 # in the stack, exploring. CHECKING
BLACK = 2 # finished explored and we know for a fact there's no loop originated from this. CHECKED
state = [WHITE for _ in range(0, n)]
res = []
def dfs(i):
state[i] = GREY
for child in graph.get(i, []):
if state[child] == GREY:
return False
elif state[child] == WHITE:
if not dfs(child):
return False
state[i] = BLACK
res.insert(0, i)
return True
for i in range(0, n):
if state[i] != BLACK:
if not dfs(i):
return []
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/course-schedule-ii/"
} | |
d1921 | train | class TimeMap:
def __init__(self):
\"\"\"
Initialize your data structure here.
\"\"\"
self.store = {}
self.times = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.store:
self.store[key] = [value]
self.times[key] = [timestamp]
else:
self.store[key].append(value)
self.times[key].append(timestamp)
def get(self, key: str, timestamp: int) -> str:
if key not in self.store: return \"\"
else:
lst = self.times[key]
if timestamp < lst[0]: return \"\"
elif timestamp >=lst[-1]: return self.store[key][-1]
else:
l = 0
r = len(lst)-1
while l < r:
mid = (l+r)//2
if lst[mid] < timestamp: r = mid
elif lst[mid] == timestamp: return self.store[key][mid]
else: l = mid
return self.store[key][r]
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp) | PYTHON | {
"starter_code": "\nclass TimeMap:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n def set(self, key: str, value: str, timestamp: int) -> None:\n def get(self, key: str, timestamp: int) -> str:\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)",
"url": "https://leetcode.com/problems/time-based-key-value-store/"
} | |
d1922 | train | from heapq import heapify, heappush, heappop
class DinnerPlates:
# index * cap -> access start of stack at index
# index * cap + (cap - 1) -> access last element of stack at index
def __init__(self, capacity: int):
self.stack = [] # just one array to simulate all the stacks
self.cap = capacity
self.idx = [] # min-heap to track empty indicies
def push(self, val: int) -> None:
if len(self.idx) > 0:
while len(self.idx) > 0:
i = heappop(self.idx)
# Given that we just push index but don't validate the cache while
# poping we need to check if this index is within current limits
if i < len(self.stack):
self.stack[i] = val
return
# we didn't find empty spaces so we add to the end
self.stack.append(val)
def pop(self) -> int:
n = len(self.stack) - 1
if n < 0:
return -1
while n > -1:
if self.stack[n] != -1:
v = self.stack[n]
self.stack[n] = -1
# Add the empty index to the heap
heappush(self.idx , n)
return v
else:
# Because those appear at the end the list we free those memory spaces so
# later pop operations are optimized
del(self.stack[n])
n -= 1
# All stacks are empty
return -1
def popAtStack(self, index: int) -> int:
# additional check that is [optional] just to skip any effort
# if index is already out of current limits
count = len(self.stack) // self.cap
if index > count:
return -1
# capture the boundaries of this stack
leftptr = (index * self.cap)
rightptr = leftptr + self.cap - 1
if rightptr > (len(self.stack) - 1): # edge case
rightptr = (len(self.stack) - 1)
# traverse within the stack at this index until we empty it or we find an occupied location
while self.stack[rightptr] == -1 and rightptr >= leftptr:
rightptr -=1
# if it isn't empty it means we found occupied position
if rightptr >= leftptr:
v = self.stack[rightptr]
self.stack[rightptr] = -1
# Add the empty index to the heap
heappush(self.idx , rightptr)
return v
else:
return -1
| PYTHON | {
"starter_code": "\nclass DinnerPlates:\n def __init__(self, capacity: int):\n def push(self, val: int) -> None:\n def pop(self) -> int:\n def popAtStack(self, index: int) -> int:\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)",
"url": "https://leetcode.com/problems/dinner-plate-stacks/"
} | |
d1923 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
def dfs(node):
if not node:
return 2
left = dfs(node.left)
right = dfs(node.right)
if left == 0 or right == 0:
self.res += 1
return 1
if left == 1 or right == 1:
return 2
else:
return 0
self.res = 0
return (dfs(root) == 0) + self.res
| PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n ",
"url": "https://leetcode.com/problems/binary-tree-cameras/"
} | |
d1924 | train | class Solution:
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
s = sorted(nums)
c = []
for n in nums:
p = bisect.bisect_left(s, n)
c.append(p)
s.pop(p)
return c
| PYTHON | {
"starter_code": "\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/count-of-smaller-numbers-after-self/"
} | |
d1925 | train | class Transaction:
def __init__(self, name, time, amount, city):
self.name = name
self.time = int(time)
self.amount = int(amount)
self.city = city
def array(self):
return f\"{self.name},{self.time},{self.amount},{self.city}\"
from collections import defaultdict
class Solution:
def invalidTransactions(self, transactions):
transactions = [Transaction(*transaction.split(',')) for transaction in transactions]
transactions.sort(key=lambda t: t.time) # O(nlogn) time
trans_indexes = defaultdict(list)
for i, t in enumerate(transactions): # O(n) time
trans_indexes[t.name].append(i)
res = []
for name, indexes in trans_indexes.items(): # O(n) time
left = right = 0
for i, t_index in enumerate(indexes):
t = transactions[t_index]
if (t.amount > 1000):
res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))
continue
while left <= t_index and transactions[indexes[left]].time < t.time - 60: # O(60) time
left += 1
while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time
right += 1
for i in range(left,right+1): # O(120) time
if transactions[indexes[i]].city != t.city:
res.append(t.array())
break
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/invalid-transactions/"
} | |
d1926 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
# time O(n); space O(n)
vals = deque(preorder)
def build(min_val, max_val):
if vals and min_val < vals[0] < max_val:
val = vals.popleft()
node = TreeNode(val)
node.left = build(min_val, val)
node.right = build(val, max_val)
return node
return build(float('-inf'), float('inf')) | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n ",
"url": "https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/"
} | |
d1927 | train | import collections
import itertools
def prime_factors(n):
i = 2
while i * i <= n:
if n % i == 0:
n /= i
yield i
else:
i += 1
if n > 1:
yield n
def prod(iterable):
result = 1
for i in iterable:
result *= i
return result
def get_divisors(n):
pf = prime_factors(n)
pf_with_multiplicity = collections.Counter(pf)
powers = [
[factor ** i for i in range(count + 1)]
for factor, count in list(pf_with_multiplicity.items())
]
for prime_power_combo in itertools.product(*powers):
yield prod(prime_power_combo)
class Solution:
def closestDivisors(self, num: int) -> List[int]:
d1 = sorted(list(get_divisors(num+1)))
d2 = sorted(list(get_divisors(num+2)))
if len(d1) % 2 == 1:
mid = d1[int((len(d1) - 1)/2)]
return [int(mid), int(mid)]
if len(d2) % 2 == 1:
mid = d2[int((len(d2) - 1)/2)]
return [int(mid), int(mid)]
l1, r1 = d1[int(len(d1)/2)],d1[int(len(d1)/2)-1]
l2, r2 = d2[int(len(d2)/2)],d2[int(len(d2)/2)-1]
if abs(l1-r1) < abs(l2-r2):
return [int(l1),int(r1)]
else:
return [int(l2),int(r2)]
| PYTHON | {
"starter_code": "\nclass Solution:\n def closestDivisors(self, num: int) -> List[int]:\n ",
"url": "https://leetcode.com/problems/closest-divisors/"
} | |
d1928 | train | class Solution:
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
l=len(asteroids)
if l<2:
return asteroids
ans=[]
stack=[]
for a in asteroids:
if a>0:
stack.append(a)
else:
a=-a
equal_flag=False
while stack:
cur=stack.pop()
if cur==a:
equal_flag=True
break
elif cur>a:
stack.append(cur)
break
if equal_flag:
continue
if not stack:
ans.append(-a)
return ans+stack
| PYTHON | {
"starter_code": "\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/asteroid-collision/"
} | |
d1929 | train | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution:
def deserialize(self, s):
"""
:type s: str
:rtype: NestedInteger
"""
root_ni = NestedInteger()
ni_stack = collections.deque()
current_ni = root_ni
active_number = None
is_positive = True
for i, c in enumerate(s):
if c == '-':
is_positive = False
active_number = 0
elif c.isdigit():
# Check if the previous was a digit as well.
if active_number is None:
active_number = int(c)
else:
active_number = int(c) + active_number * 10
else:
if active_number is not None:
if not is_positive:
active_number *= -1
current_ni.add(active_number)
active_number = None
is_positive = True
if c == '[' and i > 0:
ni_stack.append(current_ni)
current_ni = NestedInteger()
elif c == ']' and len(ni_stack) > 0:
ni_stack[-1].add(current_ni)
current_ni = ni_stack.pop()
if active_number is not None:
if not is_positive:
active_number *= -1
if not current_ni.getList():
current_ni.setInteger(active_number)
else:
current_ni.add(active_number)
return root_ni
| PYTHON | {
"starter_code": "\n# \"\"\"\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class NestedInteger:\n# def __init__(self, value=None):\n# \"\"\"\n# If value is not specified, initializes an empty list.\n# Otherwise initializes a single integer equal to value.\n# \"\"\"\n#\n# def isInteger(self):\n# \"\"\"\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# \"\"\"\n#\n# def add(self, elem):\n# \"\"\"\n# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.\n# :rtype void\n# \"\"\"\n#\n# def setInteger(self, value):\n# \"\"\"\n# Set this NestedInteger to hold a single integer equal to value.\n# :rtype void\n# \"\"\"\n#\n# def getInteger(self):\n# \"\"\"\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# \"\"\"\n#\n# def getList(self):\n# \"\"\"\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# \"\"\"\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n ",
"url": "https://leetcode.com/problems/mini-parser/"
} | |
d1930 | train | class StreamChecker:
def __init__(self, words: List[str]):
#reverse trie
self.trie = {}
self.stream = deque([])
for word in set(words):
node = self.trie
for ch in word[::-1]:
if not ch in node:
node[ch] = {}
node = node[ch]
node['$'] = word
def query(self, letter: str) -> bool:
self.stream.appendleft(letter)
node = self.trie
for ch in self.stream:
if '$' in node:
return True
if not ch in node:
return False
node = node[ch]
return '$' in node
# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker(words)
# param_1 = obj.query(letter)
| PYTHON | {
"starter_code": "\nclass StreamChecker:\n def __init__(self, words: List[str]):\n def query(self, letter: str) -> bool:\n# Your StreamChecker object will be instantiated and called as such:\n# obj = StreamChecker(words)\n# param_1 = obj.query(letter)",
"url": "https://leetcode.com/problems/stream-of-characters/"
} | |
d1931 | train | class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.n = n
self.count = 0
self.discount = discount
self.products = {}
for i in range(0, len(products)):
self.products[products[i]] = prices[i]
def getBill(self, product: List[int], amount: List[int]) -> float:
self.count += 1
subtotal = 0
for i in range(0, len(product)):
subtotal += self.products[product[i]] * amount[i]
if self.count == self.n:
subtotal = subtotal - (self.discount * subtotal) / 100
self.count = 0
return subtotal
# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)
| PYTHON | {
"starter_code": "\nclass Cashier:\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n def getBill(self, product: List[int], amount: List[int]) -> float:\n# Your Cashier object will be instantiated and called as such:\n# obj = Cashier(n, discount, products, prices)\n# param_1 = obj.getBill(product,amount)",
"url": "https://leetcode.com/problems/apply-discount-every-n-orders/"
} | |
d1932 | train | class Solution(object):
def isSubPath(self, h, r0):
h_vals = []
while h:
h_vals.append(str(h.val))
h = h.next
h_str = ('-'.join(h_vals)) + '-' # serialized list
st = [(r0, '-')] # DFS stack
while st:
r, pre = st.pop()
if not r:
continue
pre = pre + str(r.val) + '-'
if pre.endswith(h_str):
return True
st.append((r.left, pre))
st.append((r.right, pre))
return False | PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def isSubPath(self, head: ListNode, root: TreeNode) -> bool:\n ",
"url": "https://leetcode.com/problems/linked-list-in-binary-tree/"
} | |
d1933 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
def count(node):
if not node:
return 0
return 1 + count(node.left) + count(node.right)
xNode = [0, 0]
def process(node):
if node:
if node.val == x:
xNode[0] = count(node.left)
xNode[1] = count(node.right)
else:
process(node.left)
process(node.right)
return
process(root)
player2 = max(xNode[0], xNode[1], n - (xNode[0] + xNode[1] + 1)) # the maximum nodes I can color
return player2 > n // 2 | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n ",
"url": "https://leetcode.com/problems/binary-tree-coloring-game/"
} | |
d1934 | train | class Solution:
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = a.split('+')
b = b.split('+')
a[1] = a[1][:-1]
b[1] = b[1][:-1]
a = list(map(int, a))
b = list(map(int, b))
print((a, b))
r = a[0]*b[0] - a[1]*b[1]
i = a[1]*b[0] + a[0]*b[1]
print((r, i))
return "{0}+{1}i".format(r, i)
| PYTHON | {
"starter_code": "\nclass Solution:\n def complexNumberMultiply(self, a: str, b: str) -> str:\n ",
"url": "https://leetcode.com/problems/complex-number-multiplication/"
} | |
d1935 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
res = []
level_num = 1
level = [root]
while len(level) != 0:
level_size = len(level)
level_res = [None]*level_size
for i in range(level_size):
curr = level.pop(0)
level_res[i] = curr.val
if curr.left is not None:
level.append(curr.left)
if curr.right is not None:
level.append(curr.right)
if level_num % 2:
res.append(level_res)
else:
level_res.reverse()
res.append(level_res)
level_num += 1
return res
| PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n ",
"url": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/"
} | |
d1936 | train | class Solution:
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
if not matrix:
return False
colSize = len(matrix[0]) - 1
for row in range(len(matrix) - 1):
if matrix[row][:colSize] != matrix[row+1][1:colSize+1]:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n ",
"url": "https://leetcode.com/problems/swap-adjacent-in-lr-string/"
} | |
d1937 | train | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
res = []
level = 0
nodes_count = 0
while nodes_count < label:
nodes_count += 2**level
level += 1
while label != 0:
res.append(label)
level_max = (2**level) - 1
level_min = 2**(level-1)
label = (level_max + level_min - label) // 2
level -= 1
return res[::-1]
| PYTHON | {
"starter_code": "\nclass Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n ",
"url": "https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/"
} | |
d1938 | train | class ThroneInheritance:
def __init__(self, kingName: str):
self.graph = collections.defaultdict(list)
self.deaths = set()
self.root = kingName
def birth(self, parentName: str, childName: str) -> None:
self.graph[parentName].append(childName)
def death(self, name: str) -> None:
self.deaths.add(name)
def inorder(self, root, res):
if root not in self.deaths:
res.append(root)
children = self.graph[root]
for child in children:
self.inorder(child, res)
def getInheritanceOrder(self) -> List[str]:
res = []
self.inorder(self.root, res)
return res
# Your ThroneInheritance object will be instantiated and called as such:
# obj = ThroneInheritance(kingName)
# obj.birth(parentName,childName)
# obj.death(name)
# param_3 = obj.getInheritanceOrder()
| PYTHON | {
"starter_code": "\nclass ThroneInheritance:\n def __init__(self, kingName: str):\n def birth(self, parentName: str, childName: str) -> None:\n def death(self, name: str) -> None:\n def getInheritanceOrder(self) -> List[str]:\n# Your ThroneInheritance object will be instantiated and called as such:\n# obj = ThroneInheritance(kingName)\n# obj.birth(parentName,childName)\n# obj.death(name)\n# param_3 = obj.getInheritanceOrder()",
"url": "https://leetcode.com/problems/throne-inheritance/"
} | |
d1939 | train | class Solution:
def rectangleArea(self, rectangles: List[List[int]]) -> int:
def getArea(width):
res = 0
prev_low = 0
for low, high in intervals:
low = max(prev_low, low)
if high > low:
res += (high - low)*width
prev_low = high
return res
MOD = 10**9 + 7
# convert list of rectangles to events
events = []
for x1, y1, x2, y2 in rectangles:
events.append((x1, 0, y1, y2)) #in
events.append((x2, 1, y1, y2)) #out
events.sort(key = lambda x : (x[0], x[1]))
# sweep to calculate area
intervals = []
area = 0
prev_x = 0
for event in events:
cur_x, type, low, high = event
area += getArea(cur_x - prev_x)
if type == 1:
intervals.remove((low, high))
else:
intervals.append((low, high))
intervals.sort()
prev_x = cur_x
return area % MOD | PYTHON | {
"starter_code": "\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/rectangle-area-ii/"
} | |
d1940 | train | class Solution:
def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
original = set(wordlist)
insensitive = {w.lower(): w for w in reversed(wordlist)}
vowels = {}
for c in reversed(wordlist):
w = c.lower()
t = w.replace('a', '_').replace('e', '_').replace('i', '_').replace('o', '_').replace('u', '_')
vowels[t] = c
results = []
for q in queries:
if q in original:
results.append(q)
continue
low = q.lower()
if low in insensitive:
results.append(insensitive[low])
continue
# vowel replace
t = low.replace('a', '_').replace('e', '_').replace('i', '_').replace('o', '_').replace('u', '_')
if t in vowels:
results.append(vowels[t])
continue
results.append(\"\")
return results | PYTHON | {
"starter_code": "\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/vowel-spellchecker/"
} | |
d1941 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
if head==None:
return 0
temp=head
arr=[]
stack=[]
while temp:
arr.append(temp.val)
temp=temp.__next__
output=[0]*len(arr)
for i in range(len(arr)):
while stack and arr[stack[-1]]<arr[i]:
output[stack.pop()]=arr[i]
stack.append(i)
return output
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n ",
"url": "https://leetcode.com/problems/next-greater-node-in-linked-list/"
} | |
d1942 | train | class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
# 1st step
# construct a mask for each word
# note that there may be duplicate mask for different words
# so we need a dict to count the number
orda = ord('a') # 97
mask = defaultdict(int) # word mask
for w in words:
m = 0
for c in w:
m |= 1 << (ord(c) - orda)
mask[m] += 1
# 2nd step
# for each puzzle, construct the corresponding mask for each possible valid word, check whether the word is in mask
res = []
for p in puzzles:
ones = []
# separate current puzzle into ones, 'bdeg' -> 0b1011010 -> [0b10(b), 0b1000(d), 0b10000(e), 0b1000000(g)]
for c in p:
ones.append(1 << (ord(c) - orda))
# generate all valid words for the current puzzle
# equivalent to generate all subsets of ones[1:]
# reuse code from [78. Subsets]
valid = [ones[0]] # valid word must contains the first char of current puzzle
for i in range(1,7): # bfs to generate all valid words
valid.extend([ones[i] + v for v in valid])
# for each valid word, check whether it's in mask
novw = 0 # number of valid words for current puzzle
for v in valid:
if v in mask:
novw += mask[v]
res.append(novw)
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/"
} | |
d1943 | train | class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
result = []
fcSet = [set(fc) for fc in favoriteCompanies]
n = len(favoriteCompanies)
for i, fcs1 in enumerate(fcSet):
for j, fcs2 in enumerate(fcSet):
if i==j:
continue
if fcs1<fcs2:
break
else:
result.append(i)
return result | PYTHON | {
"starter_code": "\nclass Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/"
} | |
d1944 | train | class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
result = []
i = j = 0
while i < len(A) and j < len(B):
low = max(A[i][0], B[j][0])
high = min(A[i][1], B[j][1])
if low <= high:
result.append([low, high])
if A[i][1] > B[j][1]:
j += 1
elif A[i][1] < B[j][1]:
i += 1
else:
i += 1
j += 1
return result | PYTHON | {
"starter_code": "\nclass Solution:\n def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n ",
"url": "https://leetcode.com/problems/interval-list-intersections/"
} | |
d1945 | train | class Solution:
def calc(self, part):
part += "+" ## added tmp symbol in the end to sum last item within the loop
start = x = n = 0
coeff = 1
for end, char in enumerate(part):
# print("charIdx:", equation[end], "char: ", char, char == "+" or char == "-", "slice: ", equation[start:end])
if char == "+" or char == "-":
var = part[start:end]
if var == "":
continue
if "x" in var:
var = var[:-1]
if var in ["", "+"]:
var = 1
elif var == "-":
var = -1
x += int(var) * coeff
start = end
else:
n += int(var) * coeff
start = end
return x, n
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
# how big is N
# time vs. space complexity?
# split by "=" to left and right; time complexity: O(N)
# sums Xs and consts on both sides (left and right)
# take a difference b/w the sides' sums
# simplify dividing by X's coeff
# if x==0 and n==0 on the other - infinite
# if x==0 and a constant on the other - no solution
# if x on one side, and a constant on the other - solution
# test: 2-x+2x-x-x+1=x
# test2: "x+5-3+x=6+x-2"
# test2: "+5-3+x=6+x-2"
# -x=-1
left, right = equation.split("=")
x1, n1 = self.calc(left) # O(leftN)
x2, n2 = self.calc(right) # O(rightN)
x, n = x1 - x2, n1 - n2
n = n / x if (x != 0) else n
x = 1 if (x != 0) else x
if x == 0 and n != 0:
return "No solution"
if x == 0 and n == 0:
return "Infinite solutions"
return "x={}".format(int(-n))
# time complexity O(N)
| PYTHON | {
"starter_code": "\nclass Solution:\n def solveEquation(self, equation: str) -> str:\n ",
"url": "https://leetcode.com/problems/solve-the-equation/"
} | |
d1946 | train | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
dict_ = {}
for row in matrix:
curr_tuple = tuple(row)
dict_[curr_tuple] = 1 + dict_.get(curr_tuple,0)
visited = set()
max_same = 0
for row in matrix:
curr_tuple = tuple(row)
if curr_tuple in visited:
continue
visited.add(curr_tuple)
inverse = [1] * len(row)
for i in range (len(row)):
if row[i]:
inverse[i] = 0
curr_inv = tuple(inverse)
visited.add(curr_inv)
curr_sum = 0
curr_sum = dict_[curr_tuple]
if curr_inv in dict_:
curr_sum += dict_[curr_inv]
if curr_sum > max_same:
max_same = curr_sum
return max_same
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/"
} | |
d1947 | train | from collections import defaultdict, deque
from heapq import merge
from itertools import islice
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.id2tweets = defaultdict(deque)
self.id2follows = defaultdict(set)
self.uid = 0
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.id2tweets[userId].appendleft((self.uid, tweetId))
self.uid -= 1
#print(userId, 'POST', tweetId, self.id2tweets)
def getNewsFeed(self, userId):
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
:type userId: int
:rtype: List[int]
"""
#print('GET', userId, self.id2tweets, self.id2follows)
tweets = heapq.merge(*(self.id2tweets[u] for u in self.id2follows[userId] | {userId}))
return [tweet_id for _, tweet_id in islice(tweets, 10)]
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.id2follows[followerId].add(followeeId)
#print(followerId, 'FOLLOW', followeeId, self.id2follows)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.id2follows[followerId].discard(followeeId)
#print(followerId, 'UNFOLLOW', followeeId, self.id2follows)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId) | PYTHON | {
"starter_code": "\nclass Twitter:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n def postTweet(self, userId: int, tweetId: int) -> None:\n \"\"\"\n Compose a new tweet.\n \"\"\"\n def getNewsFeed(self, userId: int) -> List[int]:\n \"\"\"\n Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.\n \"\"\"\n def follow(self, followerId: int, followeeId: int) -> None:\n \"\"\"\n Follower follows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n def unfollow(self, followerId: int, followeeId: int) -> None:\n \"\"\"\n Follower unfollows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n# Your Twitter object will be instantiated and called as such:\n# obj = Twitter()\n# obj.postTweet(userId,tweetId)\n# param_2 = obj.getNewsFeed(userId)\n# obj.follow(followerId,followeeId)\n# obj.unfollow(followerId,followeeId)",
"url": "https://leetcode.com/problems/design-twitter/"
} | |
d1948 | train | class Solution:
def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
s = set(A)
letters_required = {}
for i in B:
for j in i:
count = i.count(j)
if j not in letters_required or count > letters_required[j]:
letters_required[j] = count
for i in A:
for j in letters_required:
if i.count(j) < letters_required[j]:
s.remove(i)
break
return list(s) | PYTHON | {
"starter_code": "\nclass Solution:\n def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/word-subsets/"
} | |
d1949 | train | class Solution:
def numPoints(self, points: List[List[int]], r: int) -> int:
ans = 1
for x, y in points:
angles = []
for x1, y1 in points:
if (x1 != x or y1 != y) and (d:=sqrt((x1-x)**2 + (y1-y)**2)) <= 2*r:
angle = atan2(y1-y, x1-x)
delta = acos(d/(2*r))
angles.append((angle-delta, +1)) #entry
angles.append((angle+delta, -1)) #exit
angles.sort(key=lambda x: (x[0], -x[1]))
val = 1
for _, entry in angles:
ans = max(ans, val := val+entry)
return ans
#https://www.geeksforgeeks.org/angular-sweep-maximum-points-can-enclosed-circle-given-radius/
# class Solution {
# public int numPoints(int[][] points, int r) {
# int count = 1;
# for(int i = 0; i < points.length; i++) {
# Map<Double, Integer> angles = new HashMap<>();
# for(int j = 0; j < points.length; j++) {
# if (i != j) {
# if (points[i][0] != points[j][0] || points[i][1] != points[j][1]) {
# int d = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);
# double angle = Math.atan2(points[j][1] - points[i][1], points[j][0] - points[i][0]);
# double delta = acos(d / (2 * r));
# double entry = angle - delta;
# double exit = angle + delta;
# map.put(entry, map.getOrDefault(entry, 0) + 1);
# map.put(exit, map.getOrDefault(exit, 0) - 1);
# }
# }
# }
# Map<String, Integer> result = angles.entrySet().stream()
# .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
# .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
# (oldValue, newValue) -> oldValue, LinkedHashMap::new));
#
# }
# return count;
# }
#}
| PYTHON | {
"starter_code": "\nclass Solution:\n def numPoints(self, points: List[List[int]], r: int) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/"
} | |
d1950 | train | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
height = len(grid)
width = len(grid[0])
max_path = 0
# generator for legal indices to check
def index_gen(index):
i,j = index
if i > 0 and grid[i-1][j] > 0:
yield (i-1, j)
if i < height - 1 and grid[i+1][j] > 0:
yield (i+1, j)
if j > 0 and grid[i][j-1] > 0:
yield (i, j-1)
if j < width - 1 and grid[i][j+1] > 0:
yield (i, j+1)
# if a node branches off in 2 directions it can't be a leaf
def is_viable(index):
non_zero = 0
neighbors = [grid[a][b] for a,b in index_gen(index)]
for x in neighbors:
if x != 0:
non_zero += 1
return non_zero < 2
def dfs(index, count):
nonlocal max_path
count += grid[index[0]][index[1]]
max_path = max(max_path, count)
grid[index[0]][index[1]] *= -1 # clever idea from George Zhou to mark visited
for direction in index_gen(index):
dfs(direction, count)
grid[index[0]][index[1]] *= -1 # unmark node when done with this path
for i in range(height):
for j in range(width):
if grid[i][j] != 0 and is_viable((i,j)):
dfs((i,j), 0)
# if there are no 'leaf' nodes, then every node is accessible
return max_path if max_path > 0 else sum(sum(row) for row in grid )
| PYTHON | {
"starter_code": "\nclass Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/path-with-maximum-gold/"
} | |
d1951 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
fakehead = ListNode(0)
fakehead.next = head
prev = fakehead
slow = head
fast = head.next
while fast:
if fast.val == slow.val:
while fast and fast.val == slow.val:
fast = fast.next
slow = prev
else:
prev = slow
slow = slow.next
slow.val = fast.val
fast = fast.next
slow.next = None
return fakehead.next
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n ",
"url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/"
} | |
d1952 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
if root and root.val > val:
root.right = self.insertIntoMaxTree(root.right, val)
return root
node = TreeNode(val)
node.left = root
return node | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:\n ",
"url": "https://leetcode.com/problems/maximum-binary-tree-ii/"
} | |
d1953 | train | class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if head is None or head.__next__ is None or m == n: return head
h = ListNode(-1)
h.next = head
fast = slow = h
for _ in range(n - m + 1):
fast = fast.__next__
for _ in range(m - 1):
fast = fast.__next__
slow = slow.__next__
prev = fast.__next__
curr = slow.__next__
while prev != fast:
temp = curr.__next__
curr.next = prev
prev = curr
curr = temp
slow.next = prev
return h.__next__
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n ",
"url": "https://leetcode.com/problems/reverse-linked-list-ii/"
} | |
d1954 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
dummy=ListNode(0); dummy.next=head
p1=p2=dummy
for i in range(n): p1=p1.next
while p1.next:
p1=p1.next; p2=p2.next
p2.next=p2.next.next
return dummy.next
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n ",
"url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/"
} | |
d1955 | train | class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
def fulfill_skills(skills, person):
remaining_skills = deque()
for skill in skills:
if skill not in people[person]:
remaining_skills.appendleft(skill)
return remaining_skills
# BFS by # of people
# can reduce expansion by searching rarest skills first
# map required skills to people
# has_skill[\"java\"] == a list of people (int index into people) who have that skill
has_skill = dict()
for person, skills in enumerate(people):
for skill in skills:
experts = has_skill.get(skill, [])
experts.append(person)
has_skill[skill] = experts
# sort skills by rarity
rare_skills = [(len(people), skill) for (skill, people) in list(has_skill.items())]
rare_skills.sort()
rare_skills = [skill for _, skill in rare_skills]
for i in range(1, 17):
# stack holds pairs:
# (skills, team)
stack = [ (deque(rare_skills), []) ]
while stack:
skills, team = stack.pop()
# print(skills, team)
if not skills:
return team
if len(team) + 1 > i:
continue
# choose a member to fulfill next rarest skill
skill = skills[0]
for person in has_skill[skill]:
remaining_skills = fulfill_skills(skills, person)
stack.append( (remaining_skills, team + [person]) )
# print(f\"i {i} failed\")
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/smallest-sufficient-team/"
} | |
d1956 | train | class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
pr=[i for i in range(len(s))]
def union(x,y):
p1=find(x)
p2=find(y)
if p1!=p2:
pr[p1]=p2
def find(x):
while pr[x]!=x:
pr[x]=pr[pr[x]]
x=pr[x]
return x
for i in pairs:
union(i[0],i[1])
from collections import defaultdict
dp=defaultdict(list)
for i in range(len(s)):
ld=find(i)
dp[ld].append(i)
ans=[0]*len(s)
for i in dp:
dp[i].sort()
st=''
for j in dp[i]:
st+=s[j]
st=sorted(st)
c=0
for j in dp[i]:
ans[j]=st[c]
c+=1
return ''.join(ans)
| PYTHON | {
"starter_code": "\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n ",
"url": "https://leetcode.com/problems/smallest-string-with-swaps/"
} | |
d1957 | train | class Solution:
def FindValid(self):
a="123456789"
d,val={},{}
for i in range(9):
for j in range(9):
temp=self.board[i][j]
if temp!='.':
d[("r",i)]=d.get(("r",i),[])+[temp]
d[("c",j)]=d.get(("c",j),[])+[temp]
d[(i//3,j//3)]=d.get((i//3,j//3),[])+[temp]
else:
val[(i,j)]=[]
for (i,j) in list(val.keys()):
invalid=d.get(("r",i),[])+d.get(("c",j),[])+d.get((i//3,j//3),[])
val[(i,j)]=[ele for ele in a if ele not in invalid]
return val
def CheckingSolution(self,ele,Pos,Updata):
self.board[Pos[0]][Pos[1]]=ele
del self.val[Pos]
i,j=Pos
for invalid in list(self.val.keys()):
if ele in self.val[invalid]:
if invalid[0]==i or invalid[1]==j or (invalid[0]//3,invalid[1]//3)==(i//3,j//3):
Updata[invalid]=ele
self.val[invalid].remove(ele)
if len(self.val[invalid])==0:
return False
return True
def Sudo(self,Pos,Updata):
self.board[Pos[0]][Pos[1]]="."
for i in Updata:
if i not in self.val:
self.val[i]=Updata[i]
else:
self.val[i].append(Updata[i])
def FindSolution(self):
if len(self.val)==0:
return True
Pos=min(list(self.val.keys()),key=lambda x:len(self.val[x]))
nums=self.val[Pos]
for ele in nums:
updata={Pos:self.val[Pos]}
if self.CheckingSolution(ele,Pos,updata):
if self.FindSolution():
return True
self.Sudo(Pos,updata)
return False
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.board=board
self.val=self.FindValid()
self.FindSolution()
| PYTHON | {
"starter_code": "\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n ",
"url": "https://leetcode.com/problems/sudoku-solver/"
} | |
d1958 | train | # O(M*N*K)
class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
rows, cols = len(grid), len(grid[0])
steps, min_steps = 0, rows + cols - 2
if k >= min_steps - 1:
return min_steps
visited = [[-1] * cols for _ in range(rows)]
visited[0][0] = k
q = deque([(0, 0, k)])
while q:
steps += 1
prev_min = min_steps
for _ in range(len(q)):
r, c, p = q.popleft()
for dx, dy in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
x, y = c + dx, r + dy
if x < 0 or x >= cols or y < 0 or y >= rows:
continue
kk = p-grid[y][x]
if kk <= visited[y][x]: # have visited here on a better path.
continue
# early stop if there's shortcut (-1 because goal cell != 1)
# But only applies when, comming from
to_target = rows - y + cols - x - 2 # rows-r-1 + cols-c-1
if kk >= to_target-1 and visited[y][x] == -1: #to_target == prev_min-1:
return steps + to_target
q.append((y, x, kk))
visited[y][x] = kk
min_steps = min(min_steps, to_target)
return -1
| PYTHON | {
"starter_code": "\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n ",
"url": "https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/"
} | |
d1959 | train | class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
# mine
# res = collections.defaultdict(list)
# res_return = []
# for i,j in enumerate(groupSizes):
# res[j].append(i)
# for j in res:
# temp = [res[j][0:j]]
# if len(res[j])>j:
# # print(j,res[j][1])
# # sub_nums = int(len(res[j])/j)
# for num in range(j,len(res[j]),j):
# temp = temp + [res[j][num:num+j]]
# # print(temp)
# res[j]=temp
# res_return = res_return+temp
# # print(res)
# # print(res_return)
# return res_return
# other perple
groups = defaultdict(list)
result = []
for index, size in enumerate(groupSizes):
groups[size].append(index)
if len(groups[size]) == size:
result.append(groups.pop(size))
return result | PYTHON | {
"starter_code": "\nclass Solution:\n def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:\n ",
"url": "https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/"
} | |
d1960 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def addValueToList(self, root, lst):
if root is not None:
lst.append(root.val)
self.addValueToList(root.left, lst)
self.addValueToList(root.right, lst)
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
values = []
self.addValueToList(root, values)
sorted_values = sorted(values)
max_diff = sorted_values[-1] - sorted_values[0]
for i in range(len(values)-1):
if sorted_values[i+1] - sorted_values[i] < max_diff:
max_diff = sorted_values[i+1] - sorted_values[i]
return max_diff | PYTHON | {
"starter_code": "\nclass Solution:\n def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:\n ",
"url": "https://leetcode.com/problems/champagne-tower/"
} | |
d1961 | train | class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
if not queries:
return []
p = list(range(1, m+1))
res = []
for i in queries:
z = p.index(i)
res.append(z)
del p[z]
p.insert(0,i)
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n ",
"url": "https://leetcode.com/problems/queries-on-a-permutation-with-key/"
} | |
d1962 | train | class BrowserHistory:
def __init__(self, homepage: str):
self.hashM = {}
self.maxIndex, self.currIndex = 0, 0
self.hashM[self.currIndex] = homepage
def visit(self, url: str) -> None:
self.hashM[self.currIndex + 1] = url
self.currIndex = self.currIndex + 1
self.maxIndex = self.currIndex
return(url)
def back(self, steps: int) -> str:
if self.currIndex - steps < 0:
self.currIndex = 0
else:
self.currIndex = self.currIndex - steps
return(self.hashM[self.currIndex])
def forward(self, steps: int) -> str:
if self.currIndex + steps > self.maxIndex:
self.currIndex = self.maxIndex
else:
self.currIndex = self.currIndex + steps
return(self.hashM[self.currIndex])
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)
| PYTHON | {
"starter_code": "\nclass BrowserHistory:\n def __init__(self, homepage: str):\n def visit(self, url: str) -> None:\n def back(self, steps: int) -> str:\n def forward(self, steps: int) -> str:\n# Your BrowserHistory object will be instantiated and called as such:\n# obj = BrowserHistory(homepage)\n# obj.visit(url)\n# param_2 = obj.back(steps)\n# param_3 = obj.forward(steps)",
"url": "https://leetcode.com/problems/design-browser-history/"
} | |
d1963 | train | class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return 0
m = max(nums)
ind = nums.index(m)
del nums[ind]
m_2 = max(nums)
return ind if m >= 2*m_2 else -1 | PYTHON | {
"starter_code": "\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n ",
"url": "https://leetcode.com/problems/shortest-completing-word/"
} | |
d1964 | train | class Solution:
def shoppingOffers(self, price, special, needs):
"""
:type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int
"""
def dfs(curr, special, needs):
p=curr+sum(p*needs[i] for i,p in enumerate(price))
for si in range(len(special)):
s = special[si]
if all(n>=s[i] for i,n in enumerate(needs)):
p=min(p, dfs(curr+s[-1], special[si:], [n-s[i] for i,n in enumerate(needs)]))
# else: p=min(p, dfs(curr, special[si+1:], needs))
return p
return dfs(0, special, needs) | PYTHON | {
"starter_code": "\nclass Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/shopping-offers/"
} | |
d1965 | train | def get_tree_height(node, parent_node_height):
if node is None:
return 0
node.height = parent_node_height + 1
if node.left is None and node.right is None:
return 1
return max(get_tree_height(node.left, node.height), get_tree_height(node.right, node.height)) + 1
def fill_in_array(result, node, root_index, width):
if node is None:
return
result[node.height - 1][root_index] = str(node.val)
new_width = width // 2
fill_in_array(result, node.left, root_index - new_width // 2 - 1, new_width)
fill_in_array(result, node.right, root_index + new_width // 2 + 1, new_width)
class Solution:
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
height = get_tree_height(root, 0)
rows = height
cols = 0
for i in range(height):
cols = cols * 2 + 1
result = [[""] * cols for _ in range(rows)]
fill_in_array(result, root, cols // 2, cols)
return result | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def printTree(self, root: TreeNode) -> List[List[str]]:\n ",
"url": "https://leetcode.com/problems/print-binary-tree/"
} | |
d1966 | train | class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
if len(edges) == 0:
return 0 if n == 0 else -1
p = [i for i in range(n)]
def getP(ind):
nonlocal p
if p[ind] == ind:
return ind
else:
res = getP(p[ind])
p[ind] = res
return res
cnt = 0
for t,u,v in edges:
if t == 3:
pu,pv = getP(u-1), getP(v-1)
if pu != pv:
p[pv] = pu
cnt += 1
if cnt != (n - 1):
pa = list(p)
for t,u,v in edges:
if t == 1:
pu,pv = getP(u-1), getP(v-1)
if pu != pv:
p[pv] = pu
cnt += 1
targetP = getP(0)
for v in range(n):
if getP(v) != targetP:
return -1
p = pa
for t,u,v in edges:
if t == 2:
pu,pv = getP(u-1), getP(v-1)
if pu != pv:
p[pv] = pu
cnt += 1
targetP = getP(0)
for v in range(n):
if getP(v) != targetP:
return -1
return len(edges) - cnt | PYTHON | {
"starter_code": "\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/"
} | |
d1967 | train | class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
n, m = len(mat), len(mat[0])
heights = [0] * m
res = 0
for i in range(0, n):
stack = []
count = 0
for j in range(0, m):
if mat[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
for index, height in enumerate(heights):
while stack and height < heights[stack[-1]]:
curr = stack.pop()
left = stack[-1] if stack else -1
count -= (heights[curr] - height) * (curr - left)
count += height
res += count
stack.append(index)
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/count-submatrices-with-all-ones/"
} | |
d1968 | train | class Solution(object):
def splitIntoFibonacci(self, S):
\"\"\"
:type S: str
:rtype: List[int]
\"\"\"
n = len(S)
for i in range(1, 11):
for j in range(1, 11):
if i + j >= n:
break
L = self.buildFibo(S, i, j)
if L:
return L
return []
def buildFibo(self, s, i, j):
a = s[:i]
b = s[i:i+j]
if a[0] == '0' and i > 1:
return []
if b[0] == '0' and j > 1:
return []
offset = i + j
n = len(s)
x, y = int(a), int(b)
arr = [x, y]
while offset < n:
z = x + y
if z > 2147483647:
return []
c = str(z)
k = len(c)
if offset + k > n or s[offset:offset+k] != c:
return []
offset += k
arr.append(z)
x, y = y, z
return arr | PYTHON | {
"starter_code": "\nclass Solution:\n def splitIntoFibonacci(self, S: str) -> List[int]:\n ",
"url": "https://leetcode.com/problems/split-array-into-fibonacci-sequence/"
} | |
d1969 | train | class Solution:
def removeSubfolders(self, folder):
folders = folder
folders.sort()
output = []
parent = ' '
for folder in folders:
if not folder.startswith(parent):
output.append(folder)
parent = folder + '/'
return output | PYTHON | {
"starter_code": "\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/"
} | |
d1970 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, cur_num):
if node is None: return 0
my_num = cur_num * 10 + node.val
if node.left is None and node.right is None: return my_num
return dfs(node.left, my_num) + dfs(node.right, my_num)
return dfs(root,0) | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def sumNumbers(self, root: TreeNode) -> int:\n ",
"url": "https://leetcode.com/problems/sum-root-to-leaf-numbers/"
} | |
d1971 | train | class Solution:
def nearestPalindromic(self, num):
"""
:type n: str
:rtype: str
"""
K = len(num)
candidates = set([10**K + 1, 10**(K-1) - 1])
Prefix = int(num[:(K+1)//2])
for start in map(str, [Prefix-1, Prefix, Prefix+1]):
candidates.add(start + [start, start[:-1]][K & 1][::-1])
candidates.discard(num)
return str(min(candidates, key=lambda x: (abs(int(x) - int(num)), int(x))))
| PYTHON | {
"starter_code": "\nclass Solution:\n def nearestPalindromic(self, n: str) -> str:\n ",
"url": "https://leetcode.com/problems/find-the-closest-palindrome/"
} | |
d1972 | train | class Solution:
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
dp = [int(matrix[i][0]) for i in range(m)]
vmax = max(dp)
pre = 0
for j in range(1, n):
pre, dp[0] = int(matrix[0][j-1]), int(matrix[0][j])
for i in range(1, m):
cur = dp[i]
dp[i] = 0 if matrix[i][j] == '0' else (min(dp[i-1], dp[i], pre) + 1)
pre = cur
vmax = max(vmax, max(dp))
return vmax ** 2 | PYTHON | {
"starter_code": "\nclass Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n ",
"url": "https://leetcode.com/problems/maximal-square/"
} | |
d1973 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def splitBST(self, root,target):
"""
:type root: TreeNode
:type V: int
:rtype: List[TreeNode]
"""
def split_bst_recur(root, target):
if not root:
return (None, None)
if not root.left and not root.right:
if root.val <= target:
return (root, None)
else:
return(None, root)
if root.val > target:
l, r = split_bst_recur(root.left, target)
root.left = r
return (l, root)
else:
l, r = split_bst_recur(root.right, target)
root.right = l
return (root, r)
if not root:
return [[],[]]
l, r = split_bst_recur(root, target)
return [l, r]
| PYTHON | {
"starter_code": "\nclass Solution:\n def customSortString(self, S: str, T: str) -> str:\n ",
"url": "https://leetcode.com/problems/custom-sort-string/"
} | |
d1974 | train | class Solution:
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
# tle
# for i in range(len(A)-2):
# if A[i] > min(A[i+2:]):
# return False
# return True
# ac
for i in range(len(A)):
if abs(A[i] - i) > 1:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def numTilings(self, N: int) -> int:\n ",
"url": "https://leetcode.com/problems/domino-and-tromino-tiling/"
} | |
d1975 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root==None:
return []
stack=[]
stack_left=[1]
while stack_left!=[]:
stack.append(root.val)
if root.left!=None and root.right==None:
root=root.left
elif root.left==None and root.right!=None:
root=root.right
elif root.left!=None and root.right!=None:
stack_left.append(root.left)
root=root.right
else:
if stack_left==[1]:
stack_left=[]
else:
root=stack_left.pop()
#print(stack)
stack.reverse()
return stack
| PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def postorderTraversal(self, root: TreeNode) -> List[int]:\n ",
"url": "https://leetcode.com/problems/binary-tree-postorder-traversal/"
} | |
d1976 | train | class CustomStack:
def __init__(self, maxSize: int):
self.stack = []
self.add = []
self.limit = maxSize
def push(self, x: int) -> None:
if len(self.stack) < self.limit:
self.stack.append(x)
self.add.append(0)
def pop(self) -> int:
if len(self.stack) == 0:
return -1
result = self.stack.pop()
left = self.add.pop()
if len(self.add) > 0:
self.add[-1] += left
return result + left
def increment(self, k: int, val: int) -> None:
if len(self.stack) > 0:
if k > len(self.stack):
self.add[-1] += val
return
self.add[k-1] += val
# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)
| PYTHON | {
"starter_code": "\nclass CustomStack:\n def __init__(self, maxSize: int):\n def push(self, x: int) -> None:\n def pop(self) -> int:\n def increment(self, k: int, val: int) -> None:\n# Your CustomStack object will be instantiated and called as such:\n# obj = CustomStack(maxSize)\n# obj.push(x)\n# param_2 = obj.pop()\n# obj.increment(k,val)",
"url": "https://leetcode.com/problems/design-a-stack-with-increment-operation/"
} | |
d1977 | train | class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.l = []
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
self.l= dict
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
def diffnumber(a,b):
count = 0
for i in range(len(a)):
if a[i] !=b[i]:
count +=1
return count
for x in self.l:
if len(x) == len(word) and diffnumber(x,word) ==1:
return True
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)
| PYTHON | {
"starter_code": "\nclass MagicDictionary:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n def buildDict(self, dictionary: List[str]) -> None:\n def search(self, searchWord: str) -> bool:\n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dictionary)\n# param_2 = obj.search(searchWord)",
"url": "https://leetcode.com/problems/implement-magic-dictionary/"
} | |
d1978 | train | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
count = 0
for i in range(1,len(grid)-1):
for j in range(1,len(grid[0])-1):
if grid[i][j] ==0 and self.dfs(grid,i,j):
count+=1
return count
def dfs(self,grid,i,j):
if grid[i][j]==1:
return True
if i<=0 or j<=0 or i>=len(grid)-1 or j>= len(grid[0])-1:
return False
grid[i][j]=1
up= self.dfs(grid,i+1,j)
down= self.dfs(grid,i-1,j)
left= self.dfs(grid,i,j-1)
right= self.dfs(grid,i,j+1)
return up and down and left and right | PYTHON | {
"starter_code": "\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/number-of-closed-islands/"
} | |
d1979 | train | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
out = []
for word in words:
pat_dict = dict()
used = set()
if len(word) == len(pattern):
can_be = True
for i in range(len(word)):
if word[i] not in pat_dict:
if pattern[i] not in used:
pat_dict[word[i]] = pattern[i]
used.add(pattern[i])
else:
can_be = False
break
else:
if pat_dict[word[i]] != pattern[i]:
can_be = False
break
if can_be == True:
out.append(word)
return out | PYTHON | {
"starter_code": "\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n ",
"url": "https://leetcode.com/problems/find-and-replace-pattern/"
} | |
d1980 | train | class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
max_time = -1
# enumerate all possibilities, with the permutation() func
for h, i, j, k in itertools.permutations(A):
hour = h*10 + i
minute = j*10 + k
if hour < 24 and minute < 60:
max_time = max(max_time, hour * 60 + minute)
if max_time == -1:
return \"\"
else:
return \"{:02d}:{:02d}\".format(max_time // 60, max_time % 60) | PYTHON | {
"starter_code": "\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n ",
"url": "https://leetcode.com/problems/largest-time-for-given-digits/"
} | |
d1981 | train | class Skiplist:
def __init__(self):
self.skip_list={}
def search(self, target: int) -> bool:
if(target in self.skip_list):
if(self.skip_list[target]>0):
return True
return False
def add(self, num: int) -> None:
if(num in self.skip_list):
self.skip_list[num]+=1
else:
self.skip_list[num]=1
def erase(self, num: int) -> bool:
if(num in self.skip_list):
if(self.skip_list[num]>0):
self.skip_list[num]-=1
return True
return False | PYTHON | {
"starter_code": "\nclass Skiplist:\n def __init__(self):\n def search(self, target: int) -> bool:\n def add(self, num: int) -> None:\n def erase(self, num: int) -> bool:\n# Your Skiplist object will be instantiated and called as such:\n# obj = Skiplist()\n# param_1 = obj.search(target)\n# obj.add(num)\n# param_3 = obj.erase(num)",
"url": "https://leetcode.com/problems/design-skiplist/"
} | |
d1982 | train | class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
count = [0] * (len(nums) + 1)
for start, end in requests:
count[start] += 1
count[end + 1] -= 1
for i in range(1, len(nums) + 1):
count[i] += count[i - 1]
count.pop()
res = 0
for n, times in zip(sorted(nums), sorted(count)):
res += n * times
return res % (10 ** 9 + 7)
| PYTHON | {
"starter_code": "\nclass Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/"
} | |
d1983 | train | class Solution:
def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
if not dislikes:
return True
group = [None] * (N + 1)
group[dislikes[0][0]] = 1
group[dislikes[0][1]] = -1
group1 = set([1])
group2 = set()
counter = 2
for i, j in dislikes[1:]:
if group[i] and group[j]:
if group[i] == group[j]:
return False
if group[i] in group1:
if group[j] in group1 or -group[j] in group2:
return False
group2.add(group[j])
elif group[i] in group2:
if group[j] in group2 or -group[j] in group1:
return False
group1.add(group[j])
elif group[j] in group1:
if group[i] in group1 or -group[i] in group2:
return False
group2.add(group[i])
elif group[j] in group2:
if group[i] in group2 or -group[i] in group1:
return False
group1.add(group[i])
elif not group[i] and not group[j]:
group[i], group[j] = counter, -counter
counter += 1
elif group[i]:
group[j] = -group[i]
elif group[j]:
group[i] = -group[j]
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:\n ",
"url": "https://leetcode.com/problems/possible-bipartition/"
} | |
d1984 | train | import math
class ProductOfNumbers:
def __init__(self):
self.numbers = [1]
self.lastZero = 0
def add(self, num: int) -> None:
if num != 0:
self.numbers.append(self.numbers[-1] * num)
else:
self.numbers = [1]
def getProduct(self, k: int) -> int:
if k < len(self.numbers):
return self.numbers[-1] // self.numbers[-k - 1]
else:
return 0
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
| PYTHON | {
"starter_code": "\nclass ProductOfNumbers:\n def __init__(self):\n def add(self, num: int) -> None:\n def getProduct(self, k: int) -> int:\n# Your ProductOfNumbers object will be instantiated and called as such:\n# obj = ProductOfNumbers()\n# obj.add(num)\n# param_2 = obj.getProduct(k)",
"url": "https://leetcode.com/problems/product-of-the-last-k-numbers/"
} | |
d1985 | train | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
def build(stop):
if preorder and inorder[-1] != stop:
root = TreeNode(preorder.pop())
root.left = build(root.val)
inorder.pop()
root.right = build(stop)
return root
return None # can be skipped
preorder.reverse()
inorder.reverse()
return build(None) | PYTHON | {
"starter_code": "\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n ",
"url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/"
} | |
d1986 | train | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
row, col = 0, n-1
while row < m and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False
| PYTHON | {
"starter_code": "\nclass Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n ",
"url": "https://leetcode.com/problems/search-a-2d-matrix-ii/"
} | |
d1987 | train | class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
res = [i ^ (i >> 1) for i in range(1 << n)]
idx = res.index(start)
return res[idx:] + res[:idx] | PYTHON | {
"starter_code": "\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n ",
"url": "https://leetcode.com/problems/circular-permutation-in-binary-representation/"
} | |
d1988 | train | import heapq
class Solution(object):
def pourWater(self, heights, V, K):
"""
:type heights: List[int]
:type V: int
:type K: int
:rtype: List[int]
"""
heap = []
heapq.heappush(heap, (heights[K], -1, 0))
l, r = K - 1, K + 1
lh, rh = [], []
for i in range(V):
while l >= 0 and heights[l] <= heights[l + 1]:
heapq.heappush(lh, (heights[l], -l))
l -= 1
while r < len(heights) and heights[r] <= heights[r - 1]:
heapq.heappush(rh, (heights[r], r))
r += 1
if lh and lh[0][0] < heights[K]:
h, i = heapq.heappop(lh)
heights[-i] += 1
heapq.heappush(lh, (h + 1, i))
continue
if rh and rh[0][0] < heights[K]:
h, i = heapq.heappop(rh)
heights[i] += 1
heapq.heappush(rh, (h + 1, i))
continue
heights[K] += 1
return heights
| PYTHON | {
"starter_code": "\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n ",
"url": "https://leetcode.com/problems/pyramid-transition-matrix/"
} | |
d1989 | train | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
G = [[[], []] for i in range(n)]
for i, j in red_edges: G[i][0].append(j)
for i, j in blue_edges: G[i][1].append(j)
res = [[0, 0]] + [[n * 2, n * 2] for i in range(n - 1)]
bfs = [[0, 0], [0, 1]]
for i, c in bfs:
# print(i, c)
for j in G[i][c]:
if res[j][c] == n * 2:
res[j][c] = res[i][1 - c] + 1
bfs.append([j, 1 - c])
# print(bfs)
return [x if x < n * 2 else -1 for x in map(min, res)] | PYTHON | {
"starter_code": "\nclass Solution:\n def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/shortest-path-with-alternating-colors/"
} | |
d1990 | train | class Solution:
def longestAwesome(self, s: str) -> int:
cum = [0]
firsts = {0: -1}
lasts = {0: -1}
for i, c in enumerate(s):
cum.append(cum[-1] ^ (1 << (ord(c) - 48)))
if cum[-1] not in firsts:
firsts[cum[-1]] = i
lasts[cum[-1]] = i
mx = 1
for k in firsts:
mx = max(mx, lasts[k] - firsts[k])
for off in range(10):
o = k ^ (1 << off)
if o in firsts:
mx = max(mx, lasts[o] - firsts[k])
return mx | PYTHON | {
"starter_code": "\nclass Solution:\n def longestAwesome(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/find-longest-awesome-substring/"
} | |
d1991 | train | class Solution:
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs = sorted(pairs,key=lambda x:x[1])
res = 1
first = pairs[0]
for i in pairs[1:]:
if first[-1] < i[0]:
res += 1
first = i
return res
| PYTHON | {
"starter_code": "\nclass Solution:\n def findLongestChain(self, pairs: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/maximum-length-of-pair-chain/"
} | |
d1992 | train | class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
n = len(locations)
sloc = sorted([(x,i) for i,x in enumerate(locations)])
froutes = [[0]*n for _ in range(fuel+1) ]
st,fn = -1,-1
for i in range(n):
if sloc[i][1] == start:
st = i
if sloc[i][1] == finish:
fn = i
froutes[fuel][st] = 1
f0 = fuel
while fuel > 0:
for i, cnt in enumerate(froutes[fuel]):
if cnt > 0:
for j in range(i-1, -1, -1):
dist = sloc[i][0] - sloc[j][0]
if dist <= fuel:
froutes[fuel - dist][j] += cnt
else:
break
for j in range(i+1, n):
dist = sloc[j][0] - sloc[i][0]
if dist <= fuel:
froutes[fuel - dist][j] += cnt
else:
break
fuel -= 1
res = 0
for i in range(f0+1):
res += froutes[i][fn]
return res % (10**9+7) | PYTHON | {
"starter_code": "\nclass Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n ",
"url": "https://leetcode.com/problems/count-all-possible-routes/"
} | |
d1993 | train | class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.nextCombIt = combinations(characters, combinationLength)
self.nextComb = next(self.nextCombIt, None)
def __next__(self) -> str:
nextComb = self.nextComb
self.nextComb = next(self.nextCombIt, None)
return ''.join(nextComb)
def hasNext(self) -> bool:
return self.nextComb is not None
| PYTHON | {
"starter_code": "\nclass CombinationIterator:\n def __init__(self, characters: str, combinationLength: int):\n def next(self) -> str:\n def hasNext(self) -> bool:\n# Your CombinationIterator object will be instantiated and called as such:\n# obj = CombinationIterator(characters, combinationLength)\n# param_1 = obj.next()\n# param_2 = obj.hasNext()",
"url": "https://leetcode.com/problems/iterator-for-combination/"
} | |
d1994 | train | import re
class Solution:
def removeComments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
lines = re.sub('//.*|/\*(.|\n)*?\*/', '', '\n'.join(source)).split('\n')
return [line for line in lines if line]
| PYTHON | {
"starter_code": "\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n ",
"url": "https://leetcode.com/problems/remove-comments/"
} | |
d1995 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
s=set(G)
prev_in=False
c=0
while head:
if head.val in s:
if not prev_in:
c+=1
prev_in=True
else:
prev_in=False
head=head.__next__
return c
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def numComponents(self, head: ListNode, G: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/linked-list-components/"
} | |
d1996 | train | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = defaultdict(int)
for a, b, c in trips:
d[b] += a
d[c] -= a
k = 0
for t in sorted(d.keys()):
k += d[t]
if k > capacity:
return False
return True | PYTHON | {
"starter_code": "\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n ",
"url": "https://leetcode.com/problems/car-pooling/"
} | |
d1997 | train | class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
\"\"\"
Just move along unvisited (-1) nodes and remark them as 0 on the queue while visiting others on the path and finish them as 1. If you meet them again on the queue while visiting (being 0) it means you completed a cycle, in other words it is not safe and return back without adding.
\"\"\"
visited, result = [-1] * len(graph), []
def explore(i):
visited[i] = 0
for v in graph[i]:
if visited[v] == 0 or (visited[v]==-1 and explore(v)): return True
visited[i] = 1
result.append(i)
return False
for i in range(len(graph)):
if visited[i] == -1: explore(i)
return sorted(result)
| PYTHON | {
"starter_code": "\nclass Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n ",
"url": "https://leetcode.com/problems/find-eventual-safe-states/"
} | |
d1998 | train | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], -x[1]))
prev_end = result = 0
for _, end in intervals:
if end > prev_end:
result += 1; prev_end = end
return result | PYTHON | {
"starter_code": "\nclass Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n ",
"url": "https://leetcode.com/problems/remove-covered-intervals/"
} | |
d1999 | train | import collections
solved_boards = {((1,2,3),(4,5,0)): 0}
class Solution:
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
asked = tuple(tuple(row) for row in board)
queue = collections.deque([((1,2,3),(4,5,0))])
while queue:
tboard = queue.popleft()
for next_board in next_boards(tboard):
if next_board in solved_boards:
continue
solved_boards[next_board] = solved_boards[tboard] + 1
queue.append(next_board)
return solved_boards.get(asked, -1)
def next_boards(board):
board = [list(row) for row in board]
zy, zx = find_zero(board)
for dy, dx in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nzy, nzx = zy + dy, zx +dx
if nzy in range(2) and nzx in range(3):
board[zy][zx],board[nzy][nzx] = board[nzy][nzx],board[zy][zx]
yield tuple(tuple(row) for row in board)
board[zy][zx],board[nzy][nzx] = board[nzy][nzx],board[zy][zx]
def find_zero(board):
for y, row in enumerate(board):
for x, e in enumerate(row):
if e == 0:
return y,x | PYTHON | {
"starter_code": "\nclass Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:\n ",
"url": "https://leetcode.com/problems/cheapest-flights-within-k-stops/"
} | |
d2000 | train | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
seen={}
seen[0]=dummy=ListNode(0)
dummy.next=head
prev=0
while head:
prev+=head.val
seen[prev]=head
head=head.__next__
head=dummy
prev=0
while head:
prev+=head.val
head.next=seen[prev].__next__
head=head.__next__
return dummy.__next__
| PYTHON | {
"starter_code": "\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: ListNode) -> ListNode:\n ",
"url": "https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/"
} |