sol_id stringlengths 6 6 | problem_id stringlengths 6 6 | problem_text stringlengths 322 4.55k | solution_text stringlengths 137 5.74k |
|---|---|---|---|
ff718e | e03afc | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a con... | INF = 1 << 60
class Solution:
def minSubarray(self, A: List[int], p: int) -> int:
idx = {}
n = len(A)
S = [0] * (n + 1)
for i in range(n):
S[i + 1] = S[i] + A[i]
s = S[-1] % p
if s == 0:
return 0
ans = INF
for i, v in e... |
c8e796 | e03afc | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a con... | class Solution(object):
def minSubarray(self, nums, p):
"""
:type nums: List[int]
:type p: int
:rtype: int
"""
s = sum(nums) % p
if s==0: return 0
lp = {0:-1}
n = len(nums)
i, c=0, 0
rc = -1
while i<n:
c += n... |
bdea0d | 02d433 | Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
Every song is played at least once.
A song can only be played again only if k other songs have been played.
Given n, goal, and k, return th... | class Solution(object):
def numMusicPlaylists(self, N, L, K):
"""
:type N: int
:type L: int
:type K: int
:rtype: int
"""
M = 10**9 + 7
# ways(t, p) = ways to play p different songs in t time
# ways(t, p) = ways(t-1, p-1) * (N-p) [NEW SONG]
... |
01abb5 | 02d433 | Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
Every song is played at least once.
A song can only be played again only if k other songs have been played.
Given n, goal, and k, return th... | class Solution:
def numMusicPlaylists(self, N, L, K):
"""
:type N: int
:type L: int
:type K: int
:rtype: int
"""
mod = 10 ** 9 + 7
dp = [[0 for _ in range(N + 1)] for _ in range(L + 1)]
dp[0][0] = 1
for i in range(1, L + 1):
... |
7bacc4 | 3211bc | You are given a 0-indexed integer array nums of length n.
A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime.
For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime,... | M = 10 ** 6
primes = []
is_prime = [True] * (M + 1)
min_prime = list(range(M + 1))
for i in range(2, M + 1):
if is_prime[i]:
primes.append(i)
for p in primes:
if i * p > M:
break
is_prime[i * p] = False
min_prime[i * p] = p
if i % p == 0:
break
de... |
ce06cb | 3211bc | You are given a 0-indexed integer array nums of length n.
A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime.
For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime,... | class Solution(object):
def findValidSplit(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m, n = defaultdict(int), defaultdict(int)
for i in range(len(nums)):
x = nums[i]
for j in range(2, int(sqrt(x)) + 1):
while not x ... |
6b73eb | 24c104 | There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.
Implement the Graph class:
Graph(int n, int[]... | class Graph:
def __init__(self, n: int, edges: List[List[int]]):
self.n = n
self.graph = defaultdict(list)
for edge in edges:
self.addEdge(edge)
def addEdge(self, edge: List[int]) -> None:
x, y, z = edge
self.graph[x].append((y, z))
def shortes... |
123965 | 24c104 | There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.
Implement the Graph class:
Graph(int n, int[]... | class Graph(object):
def __init__(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
"""
nei = [set() for _ in range(n)]
for a, b, c in edges:
nei[a].add((b,c))
self.nei = nei
self.dd = [0]*n
self.n = n
def addEdg... |
82e7a8 | 9336a6 | You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team with the... | class Solution(object):
def maxPerformance(self, N, S, E, K): #n, speed, efficiency, k):
"""
:type n: int
:type speed: List[int]
:type efficiency: List[int]
:type k: int
:rtype: int
"""
MOD = 10**9 + 7
# max (sum S_i) * (min E_i) , at most ... |
904f2d | 9336a6 | You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team with the... | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
# minimum efficiency among their engineers
ses = [(s, e) for s, e in zip(speed, efficiency)]
ses.sort(key=lambda x : (-x[1], x[0]))
speed_sum = 0
window = []
mx =... |
415993 | 6e9a1b | There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].
Given the encoded array, return the origi... | class Solution(object):
def decode(self, A):
n = len(A) + 1
a = 0
for i in xrange(1, n + 1):
a ^= i
for i in A[::-2]:
a ^= i
res = [a]
for a in A:
res.append(res[-1] ^ a)
return res |
7fb7f4 | 6e9a1b | There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].
Given the encoded array, return the origi... | class Solution:
def decode(self, a: List[int]) -> List[int]:
n=len(a)+1
s=0
for i in range(1,n+1):
s^=i
p=0
for i in range(n-1):
p^=a[i]
a[i]=p
s^=a[i]
# print(n,a)
# print(s)
b=[s]
for x in a:
... |
9a4929 | 22e3c5 | You are given a positive integer k. You are also given:
a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
The two arrays contain integers from 1 to k.
You have to build a k x k matrix that cont... | def toposort(graph):
res, found = [], [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# ... |
3fac99 | 22e3c5 | You are given a positive integer k. You are also given:
a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
The two arrays contain integers from 1 to k.
You have to build a k x k matrix that cont... | class Solution(object):
def buildMatrix(self, k, rowConditions, colConditions):
"""
:type k: int
:type rowConditions: List[List[int]]
:type colConditions: List[List[int]]
:rtype: List[List[int]]
"""
def s(c):
g, p, q, i, r = [[] for _ in range(k + ... |
0c03cf | 627b0d | You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.
In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the ... | from collections import defaultdict
class Solution(object):
def minOperations(self, target, arr):
"""
:type target: List[int]
:type arr: List[int]
:rtype: int
"""
# sort arr by target order to transform
# longest common subsequence -> longest increasing subseq... |
9950d3 | 627b0d | You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.
In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the ... | class Solution:
def minOperations(self, target: List[int], arr: List[int]) -> int:
dic = {}
for i, num in enumerate(target):
dic[num] = i
n = len(arr)
narr = []
for i in range(n):
if arr[i] in dic:
narr.append(dic[arr[i]])
... |
646482 | 2744e4 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diago... | class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
n = len(grid)
zv = [-1] * n
for i in range(n):
for j in range(n):
if grid[i][j] > 0:
zv[i] = j
for idx, val in enumerate(sorted(zv)):
if val > idx:
... |
a7b042 | 2744e4 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diago... | class Solution(object):
def minSwaps(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
a = [0]*n
for i, row in enumerate(grid):
for j in reversed(row):
if j == 1: break
a[i] += 1
r = ... |
20cebd | 3b1f75 | Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, s... | class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
kstack=[-1]
sstack=[""]
k=0
for i in xrange(len(s)):
if s[i]>='0' and s[i]<='9':
k=k*10+int(s[i])
elif s[i]=='[':
... |
6a9899 | 8d9c13 | You need to construct a binary tree from a string consisting of parenthesis and integers.
The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same stru... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def str2tree(self, s):
if not s: return None
if '(' in s:
ix = s.index('(')
root ... |
559918 | 1a9e1a | Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.
The line could be horizontal, vertical, diagonal, or anti-diagonal.
Example 1:
Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3
Example 2:
Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
Output: 4
Co... | class Solution(object):
def longestLine(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M or not M[0]: return 0
def f(stream):
curr = best = 0
for c in stream:
curr = (curr + 1) if c else 0
best = m... |
7b3235 | c287be | You are given an integer array nums and an integer threshold.
Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.
Return the size of any such subarray. If there is no such subarray, return -1.
A subarray is a contiguous non-empty sequence of elements within an ar... | class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
n = len(nums)
parent = [i for i in range(n)]
sz = [1 for i in range(n)]
def root(x):
if x == parent[x]:
return x
parent[x] = root(parent[x])
... |
f9767e | c287be | You are given an integer array nums and an integer threshold.
Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.
Return the size of any such subarray. If there is no such subarray, return -1.
A subarray is a contiguous non-empty sequence of elements within an ar... | class Solution(object):
def validSubarraySize(self, nums, threshold):
"""
:type nums: List[int]
:type threshold: int
:rtype: int
"""
n=len(nums)
if n>threshold:
return n
l=[[float('-inf'),-1]]
for i in range(n):
while l[... |
5c77a1 | 047405 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be ... | class Solution(object):
def containVirus(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = 0
self.walls = {}
while True:
lst = self.findRegions(grid)
if not lst: return res
for i, j in lst:... |
03f663 | 047405 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be ... |
from copy import deepcopy
class Solution:
def containVirus(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
a = grid
for i in range(m):
for j in range(n):
if a[i][j] == 0:
... |
09b69e | 382246 | You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases ar... | class Solution(object):
def minNumberOperations(self, A):
res = 0
for a,b in zip([0] + A, A):
res += max(0, b - a)
return res
|
e7d5c2 | 382246 | You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases ar... | class Solution:
def minNumberOperations(self, target: List[int]) -> int:
target.append(0)
return sum([target[i]-target[i-1] for i in range(len(target)) if target[i]>target[i-1]]) |
114526 | beae67 | Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "0110", n = 3
Output: true
Example 2:
Input: s = "0110",... | class Solution:
def queryString(self, S: str, N: int) -> bool:
if N > (len(S) * (len(S) + 1) // 2):
return False
ok = [False] * (N + 1)
ok[0] = True
for i in range(len(S)):
num = 0
for j in range(i, len(S)):
num = num * 2 + int(S[j]... |
d5b67f | beae67 | Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "0110", n = 3
Output: true
Example 2:
Input: s = "0110",... | class Solution(object):
def queryString(self, S, N):
"""
:type S: str
:type N: int
:rtype: bool
"""
seen = set()
S = map(int, S)
n = len(S)
for i in range(n):
c = 0
for j in range(i, n):
c *= 2
... |
67095e | d9c799 | Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].
The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:
The rank is an integer starting from 1.
If two elements p and q are in the sam... | # https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0Ek
# https://www.youtube.com/watch?v=VLwVU3Bi0E... |
62673c | d9c799 | Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].
The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:
The rank is an integer starting from 1.
If two elements p and q are in the sam... | from collections import defaultdict, Counter, deque
class Solution(object):
def matrixRankTransform(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
arr = matrix
n, m = len(arr), len(arr[0])
loc = defaultdict(list)
adj = def... |
26f102 | 778561 | Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
The average value of a tree is the sum of its values, divided by the number of nodes.
Exampl... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maximumAverageSubtree(self, root: TreeNode) -> float:
ans = 0
def dfs(node):
nonlocal ans
... |
350d92 | 778561 | Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
The average value of a tree is the sum of its values, divided by the number of nodes.
Exampl... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maximumAverageSubtree(self, root):
"""
:type root: TreeNode
:rtype: float
"""
... |
0a1cc5 | 4a6420 | A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
A subsequence is derived from another sequenc... | class Solution(object):
def lenLongestFibSubseq(self, A):
"""
:type A: List[int]
:rtype: int
"""
if len(A) < 3: return 0
s = set(A)
def f(i, j):
r = 2
a = A[i]
b = A[j]
while a + b in s: a, b, r = b, a + b, r + 1... |
1bbb39 | 4a6420 | A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
A subsequence is derived from another sequenc... | class Solution:
def lenLongestFibSubseq(self, A):
"""
:type A: List[int]
:rtype: int
"""
ans=0
dp=[{} for _ in range(len(A))]
for i in range(1,len(A)):
for j in range(i):
tmp=A[i]-A[j]
if tmp in dp[j]:
... |
b99730 | a59f35 | You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
Return all lonely numbers in nums. You may return the answer in any order.
Example 1:
Input: nums = [10,6,5,8]
Output: [10,8]
Explanation:
- 10 is a lonely number s... | class Solution:
def findLonely(self, nums: List[int]) -> List[int]:
cnt = collections.Counter(nums)
ans = []
for num in cnt:
if cnt[num] == 1 and (num - 1) not in cnt and (num + 1) not in cnt:
ans.append(num)
return ans |
ddd31d | a59f35 | You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
Return all lonely numbers in nums. You may return the answer in any order.
Example 1:
Input: nums = [10,6,5,8]
Output: [10,8]
Explanation:
- 10 is a lonely number s... | from collections import Counter
class Solution(object):
def findLonely(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
c = Counter(nums)
return [k for k, v in c.iteritems()
if v==1 and (k-1) not in c and (k+1) not in c] |
ab6938 | 9c014d | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pa... | class Solution:
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
def helper(layer):
if len(layer) <= 1:
return True
new_set = [""]
for i in rang... |
91e6ea | 9c014d | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pa... | class Solution(object):
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
colors = [[0 for i in xrange(7)] for j in xrange(7)]
for pair in allowed:
a, b, c = [x for x in pair]
... |
0fc51a | 344904 | You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
The first element in s[k] starts with the selection of the element nums[k] of index = k.... | class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
vis = [False] * n
cycle = [None] * n
longest = 1
for i in range(n):
x = i
cur = 0
whi... |
1e8679 | 344904 | You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
The first element in s[k] starts with the selection of the element nums[k] of index = k.... | class Solution:
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
visited = [False] * len(nums)
for i in range(len(nums)):
if visited[i]:
continue
j = i
count = 0
... |
65e3a1 | c31942 | You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
You can place the boxes anywhere on the floor.
If box x is placed on top of t... | class Solution(object):
def minimumBoxes(self, n):
"""
:type n: int
:rtype: int
"""
s = 1
count = 0
res = 0
while count < n:
for i in range(1,s+1):
count += i
res += 1
# print s,i,count,res
... |
8bd2f6 | c31942 | You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
You can place the boxes anywhere on the floor.
If box x is placed on top of t... | class Solution:
def minimumBoxes(self, n: int) -> int:
base, m = 0, 0
for i in range(1, 9999999) :
if m + (base + i) <= n :
base += i
m += base
else :
break
new_base = 0
for j in range(1, i+1) :
if m ... |
8700e2 | 9a061d | Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.
A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following... | import re
TAG_RE = re.compile(r'\A[A-Z]{1,9}\Z')
class Solution(object):
def isValid(self, code):
"""
:type code: str
:rtype: bool
"""
s = []
h = False
i, n = 0, len(code)
while i < n:
j = code.find('<', i)
if j < 0... |
a1cb42 | 9a061d | Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.
A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following... | def is_valid_ending_with(s, i, j, tag):
closed_tag = '</' + tag + '>'
if not s.endswith(closed_tag, i, j):
return False
# Skip parsing the tag.
i += len(tag) + 2
max_i = j - len(closed_tag)
tag_stack = []
while i != max_i:
if s[i].isspace() or s[i].isalnum() or s[i] in '>/![]... |
ec78c3 | 2e80d2 | A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting posit... | class Solution:
def minRefuelStops(self, target, startFuel, stations):
"""
:type target: int
:type startFuel: int
:type stations: List[List[int]]
:rtype: int
"""
d = collections.defaultdict(int)
d[0] = startFuel
for dist, fuel in stations:
... |
800535 | 2e80d2 | A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting posit... | class Solution(object):
def minRefuelStops(self, target, startFuel, stations):
"""
:type target: int
:type startFuel: int
:type stations: List[List[int]]
:rtype: int
"""
cur = startFuel
hq = []
ans = 0
for x in stations:
if ... |
c95e3e | 8a5a6c | Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.
The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
A subarray is a c... | class Solution(object):
def maxSumTwoNoOverlap(self, A, L, M):
"""
:type A: List[int]
:type L: int
:type M: int
:rtype: int
"""
pre = [0]
n = len(A)
for i in range(n):
pre.append(pre[i] + A[i])
def is_ok(i,j):
... |
41385b | 8a5a6c | Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.
The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
A subarray is a c... | class Solution:
def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
def f(a, b):
ret = 0
for i in range(a - 1, n - b):
for j in range(i + b, n):
ret = max(ret, ps[i + 1] - ps[i + 1 - a] + ps[j + 1] - ps[j + 1 - b])
... |
4ac8ef | 5b9f9e | We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
(... | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def employeeFreeTime(self, avails):
"""
:type avails: List[List[Interval]]
:rtype: List[Interval]
"""
schedule ... |
084bb3 | 5b9f9e | We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
(... | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def employeeFreeTime(self, avails):
"""
:type avails: List[List[Interval]]
:rtype: List[Interval]
"""
it = heapq.merge(*avails,... |
214726 | 9892be | Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner:
lower[i] = arr[i] - k, for every index i where 0 <= i < n
higher[i] = arr[i] + k, for every index i where 0 <= i < n
Unfor... | from collections import Counter
class Solution(object):
def recoverArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
a = sorted(nums)
n = len(a) // 2
def check(k):
c = Counter()
r = []
for val in a:
... |
a11355 | 9892be | Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner:
lower[i] = arr[i] - k, for every index i where 0 <= i < n
higher[i] = arr[i] + k, for every index i where 0 <= i < n
Unfor... | class Solution:
def recoverArray(self, nums: List[int]) -> List[int]:
nums = sorted(nums)
start = nums[0]
for nstart in nums[1:] :
if (nstart - start) % 2 == 1 or nstart == start:
continue
dt = (nstart - start) // 2
counter = collections.Co... |
ce6574 | 1ae06f | Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A subarray is a contiguous non-empty sequence of elements within an ar... | class Solution(object):
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
ans = set([A[0]])
prev = set([A[0]])
for i in range(1, len(A)):
newSet = set(num|A[i] for num in prev)
newSet.add(A[i])
ans |= n... |
7cd965 | 1ae06f | Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A subarray is a contiguous non-empty sequence of elements within an ar... | class Solution:
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
n = len(A)
q = []
s = {-1}
for x in A:
q += [x]
q = [x | y for y in q]
q = list(set(q))
#print(q)
#s.uni... |
9d8024 | 28a478 | Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer... | class Solution(object):
def smallestDivisor(self, A, T):
N = len(A)
def f(d):
s = 0
for x in A:
s += (x-1) // d + 1
return s <= T
lo, hi = 1, 10**20
while lo<hi:
mi = (lo+hi) // 2
if f(mi):
... |
c4e77a | 28a478 | Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer... | class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
l, r, ans = 1, max(nums) + 1, None
while l <= r:
mid = (l + r) // 2
cur = sum(x // mid + (1 if x % mid != 0 else 0) for x in nums)
if cur <= threshold:
ans = mid
... |
f90dd4 | f8a923 | Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
Pick a non-empty suffix from the string s where all the characters in this suff... | class Solution(object):
def minimumLength(self, s):
"""
:type s: str
:rtype: int
"""
st=0
end=len(s)-1
while s[st]==s[end] and st<end:
i=st
while s[st]==s[i] and st<end:
st+=1
while s[end]==s[i] and st<=end:
... |
6b546c | f8a923 | Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
Pick a non-empty suffix from the string s where all the characters in this suff... | class Solution:
def minimumLength(self, s: str) -> int:
i = 0
j = len(s) - 1
while i < j and s[i] == s[j]:
c = s[i]
while i < j and s[i] == c:
i += 1
while i <= j and s[j] == c:
j -= 1
return j - i + 1 |
10a23c | f8a9ad | You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.
For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum nu... | class Solution:
def maximumEvenSplit(self, f: int) -> List[int]:
if f%2:
return []
f //= 2
s = 0
c = []
x = 1
while x+s <= f:
c.append(x)
s += x
x += 1
c[-1] += f-s
return [i*2 for i in c]
|
c69f97 | f8a9ad | You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.
For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum nu... | class Solution(object):
def maximumEvenSplit(self, finalSum):
"""
:type finalSum: int
:rtype: List[int]
"""
if finalSum & 1 == 1:
return []
else:
res = []
n = int(math.sqrt(finalSum))
t = n * (n + 1)
if t <= ... |
d193bb | 85a4cf | You are given a string text. You can swap two of the characters in the text.
Return the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated characte... | class Solution(object):
def maxRepOpt1(self, s):
s = 'AB' + s + 'YZ'
n = len(s)
cnt = collections.Counter(s)
pre = [0] * n
cur = 0
for i in range(1, n):
if s[i] == s[i - 1]:
cur += 1
else:
... |
d28de1 | 85a4cf | You are given a string text. You can swap two of the characters in the text.
Return the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated characte... | class Solution:
def maxRepOpt1(self, text: str) -> int:
stack = [['!',0]]
for i in text:
if i != stack[-1][0]:
stack += [[i,1]]
else:
stack[-1][1] += 1
stack = stack[1:]
res = 0
cnt = collections.defaultdict(int)
... |
c22f1f | cbcad3 | You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum numbe... | class Solution(object):
def minDays(self, bloomDay, M, K):
"""
:type bloomDay: List[int]
:type m: int
:type k: int
:rtype: int
"""
events = []
for i, t in enumerate(bloomDay, 1):
events.append((t, i))
events.sort()
... |
e43682 | cbcad3 | You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum numbe... | class Solution:
def minDays(self, a: List[int], mm: int, k: int) -> int:
if mm*k>len(a):
return -1
def chk(d):
ans=0
cnt=0
for x in a:
if x>d:
cnt=0
continue
cnt+=1
... |
7b0545 | 3e0aca | Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we d... | from functools import lru_cache
class Solution:
def minInsertions(self, s: str) -> int:
INF = float('inf')
@lru_cache(None)
def dp(i, j):
if i > j:
return INF
elif i == j:
return 0
elif i == j-1:
re... |
c5abd5 | 3e0aca | Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we d... | class Solution(object):
def minInsertions(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
f = [[0]*(n+1), [0]*n]
for k in xrange(2, n+1):
f.append([f[k-2][i+1] if s[i]==s[i+k-1]
else 1 + min(f[k-1][i], f[k-1][i+1])
... |
2c6741 | 11bdb9 | A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to... | class Solution:
def maximumInvitations(self, f: List[int]) -> int:
# functional graph
# either table consists of one cycle
# or multiple (two chains + cycle of two)
# bidirectional edges
edges = defaultdict(list)
n = len(f)
for i in range(n):
edge... |
7ebbc7 | 11bdb9 | A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to... | from collections import Counter
class Solution(object):
def maximumInvitations(self, favorite):
"""
:type favorite: List[int]
:rtype: int
"""
a = favorite
n = len(a)
hl = [None]*n
cl = [None]*n
cs = [None]*n
ctl = Counter()
for ... |
828be2 | c605d7 | You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [... | class Solution:
def intersectionSizeTwo(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
def verifyTwo(start, end):
found_one = False
found_two = False
for i in result:
if i >= start and i <= end:
... |
23d1d6 | c605d7 | You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [... | class Solution(object):
def intersectionSizeTwo(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key=lambda x: x[1])
s = [intervals[0][1] - 1, intervals[0][1]]
for i in xrange(1, len(intervals)):
st, e = interva... |
697dd7 | 6015d1 | In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the mi... | class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
low, high = 1, 10**7
while low != high:
mid = (low+high) >> 1
a = mid*(mid+1)*(2*mid+1)*2
if a < neededApples:
low = mid+1
else:
high = mid
re... |
89330c | 6015d1 | In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the mi... | class Solution(object):
def minimumPerimeter(self, neededApples):
"""
:type neededApples: int
:rtype: int
"""
cur = 1
while True:
apples = 2 * cur
apples *= cur + 1
apples *= (2 * cur + 1)
if apples >= neededApples:
... |
f3e8c1 | 2b0886 | You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]:
Choosing to remove index 1 results in nums = [6,7,4,1].
Choosing to remove index 2 results in nums = [6,1,4,1... | class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
sums = [0]
for i,n in enumerate(nums):
sums.append(sums[-1]-n if i%2 else sums[-1]+n)
# print(sums)
cnt = 0
for i,n in enumerate(nums):
if sums[i] == sums[-1]-sums[i+1]:
... |
299f10 | 2b0886 | You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]:
Choosing to remove index 1 results in nums = [6,7,4,1].
Choosing to remove index 2 results in nums = [6,1,4,1... | class Solution(object):
def waysToMakeFair(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
odd_pre = [0] * n
even_pre = [0] * n
odd_suf = [0] * n
even_suf = [0] * n
for i in range(n):
if i % 2 == 1:
... |
22bc13 | 994ae0 | You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers.
Return an integ... | class Solution(object):
def fullBloomFlowers(self, flowers, persons):
"""
:type flowers: List[List[int]]
:type persons: List[int]
:rtype: List[int]
"""
events = []
for fs, fe in flowers:
events.append((fs, 1, -1))
events.append((fe + 1,... |
f59fbf | 994ae0 | You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers.
Return an integ... | class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
to_ret = [None]*len(persons)
persons = sorted([[t, i] for i, t in enumerate(persons)])
flowers = sorted(flowers)
heap = []
pf = 0
for t, it in persons :
... |
bac86c | a93d84 | Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return i... | class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
# 背包问题
self.cost = cost
from functools import lru_cache
@lru_cache(None)
def mylarge(target: int) -> str:
if target<0: return None
if target==0: return ''
... |
a4d703 | a93d84 | Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return i... | class Solution(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
cost=[0]+cost
a,s,d=[0]*(target+1),[0]*(target+1),[0]*(target+1)
d[0]=1
for i in range(1,target+1):
for j in ... |
45195b | ea5f85 | Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32... | class Solution:
def maxSumAfterPartitioning(self, A: List[int], K: int) -> int:
ans = []
for i, n in enumerate(A):
if i < K:
ans.append(max(A[:i + 1]) * (i + 1))
else:
cur = 0
for j in range(i - K + 1, i + 1):
... |
f3bc22 | ea5f85 | Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32... | class Solution(object):
def maxSumAfterPartitioning(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
max_range = dict()
n = len(A)
for i in xrange(n):
for j in xrange(i, n):
if j == i:
max... |
64f48a | 11feb0 | You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already ... |
MAX_N = 2 * 10 ** 5 + 1
MOD = 10 ** 9 + 7
assert MAX_N < MOD
def modInverse(a, p=MOD):
return pow(a, p - 2, p)
# Precompute all factorials: i!
fact = [1]
for i in range(1, MAX_N + 1):
fact.append((fact[-1] * i) % MOD)
# Precompute all inverse factorials: 1 / i!
invFact = [0] * (MAX_N + 1)
invFact[MAX_N] =... |
a1d4e7 | 11feb0 | You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already ... | class Solution(object):
def fsm(self, a, b, c):
ans = 1
while b > 0:
if b & 1:
ans = ans * a % c
a = a * a % c
b = b >> 1
return ans
def C(self, n, m):
return self.frac[n] * self.revfrac[m] % self.mo * sel... |
2283d1 | eb8f49 | There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected.
You can add at most two additional edges (possibly none) to this graph so that there... | import sys
sys.setrecursionlimit(10 ** 9)
"""
// END NO SAD
// REMEMBER CLEAR GLOBAL STATE
// REMEMBER READ THE PROBLEM STATEMENT AND DON'T SOLVE A DIFFERENT PROBLEM
// REMEMBER LOOK FOR RANDOM UNINTUITIVE DETAILS IN THE PROBLEM
// remember hidden T factor of 1e2
// read the bounds for stupid cases
// did you restart y... |
c1fae8 | eb8f49 | There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected.
You can add at most two additional edges (possibly none) to this graph so that there... | class Solution(object):
def isPossible(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
d, g, o = [0] * (n + 1), defaultdict(set), []
for e, f in edges:
d[e], d[f] = d[e] + 1, d[f] + 1
g[e].add(f)
... |
a4c19e | 6b98b1 | You are given a stream of points on the X-Y plane. Design an algorithm that:
Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
Given a query point, counts the number of ways to choose three points from the data structure such that the three p... | from collections import defaultdict
from typing import List
class DetectSquares:
def __init__(self):
self.x = defaultdict(set)
self.cnt = defaultdict(int)
def add(self, point: List[int]) -> None:
x, y = point
self.x[x].add(y)
self.cnt[(x, y)] += 1
def count(self,... |
539049 | 6b98b1 | You are given a stream of points on the X-Y plane. Design an algorithm that:
Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
Given a query point, counts the number of ways to choose three points from the data structure such that the three p... | from collections import Counter
class DetectSquares(object):
def __init__(self):
self._c = Counter()
def add(self, point):
"""
:type point: List[int]
:rtype: None
"""
self._c[tuple(point)] += 1
def count(self, point):
"""
:type point: List[i... |
1a10ce | ef5d54 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictl... | class Solution(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
a = [score for _, score in sorted((age, score) for age, score in zip(ages, scores))]
n = len(a)
f = a[:]
for i in x... |
910541 | ef5d54 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictl... | class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
n = len(scores)
arr = [(ages[i], scores[i]) for i in range(n)]
arr.sort()
dp = [0 for i in range(n)]
for i in range(n):
for j in range(0, i):
if arr[j][1] <= arr[i]... |
c3fa69 | 996a9d | You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.
The length of a jump is the abso... | class Solution:
def maxJump(self, stones: List[int]) -> int:
to_ret = stones[1]-stones[0]
for i in range(2, len(stones)) :
to_ret = max(to_ret, stones[i]-stones[i-2])
return to_ret |
333cd9 | 996a9d | You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.
The length of a jump is the abso... | class Solution(object):
def maxJump(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
re=stones[1]-stones[0]
for i in range(len(stones)-2):
re=max(re,stones[i+2]-stones[i])
return re |
671baa | c20426 | You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.
You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.
... | class Solution:
def connectSticks(self, s: List[int]) -> int:
heapq.heapify(s)
ret = 0
while len(s) > 1:
a, b = heapq.heappop(s), heapq.heappop(s)
ret += a + b
heapq.heappush(s, a + b)
return ret |
5afa8b | c20426 | You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.
You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.
... | import heapq
class Solution(object):
def connectSticks(self, sticks):
"""
:type sticks: List[int]
:rtype: int
"""
heapq.heapify(sticks)
res = 0
while len(sticks)>1:
p1 = heapq.heappop(sticks)
p2 = heapq.heappop(sticks)
res+... |
ef0bc1 | 390936 | You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).
The ith rectangle has its bottom-left corner point at the coordinat... | class Solution(object):
def countRectangles(self, rectangles, points):
"""
:type rectangles: List[List[int]]
:type points: List[List[int]]
:rtype: List[int]
"""
rectangles.sort()
rectangles.reverse()
queries = []
for i, p in enumerate(points):
... |
8af571 | 390936 | You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).
The ith rectangle has its bottom-left corner point at the coordinat... | class Solution:
def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:
to_ret = [None]*len(points)
points = sorted([t+[i] for i, t in enumerate(points)])
rectangles = sorted(rectangles)
# print(points)
# print(rectangles)
... |
d78906 | a71856 | You are given an array tasks where tasks[i] = [actuali, minimumi]:
actuali is the actual amount of energy you spend to finish the ith task.
minimumi is the minimum amount of energy you require to begin the ith task.
For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. Howeve... | class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
tasks.sort(key = lambda x: x[1]-x[0])
cur = 0
for dec,req in tasks:
cur+=dec
if cur<req:cur = req
return cur |
3a5df7 | a71856 | You are given an array tasks where tasks[i] = [actuali, minimumi]:
actuali is the actual amount of energy you spend to finish the ith task.
minimumi is the minimum amount of energy you require to begin the ith task.
For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. Howeve... | class Solution(object):
def minimumEffort(self, tasks):
tasks.sort(key=lambda t: t[0] - t[1])
ans = R = max(r for a,r in tasks)
for a,r in tasks:
if R < r:
d = r-R
ans += d
R += d
R -= a
ret... |
1fc522 | e736ec | There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D ... | class Solution:
def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
low, high = 0, row*col
a = [[0 for i in range(col)] for j in range(row)]
for i in range(row*col):
a[cells[i][0]-1][cells[i][1]-1] = i+1
while low != high:
mid = (low... |
dd4583 | e736ec | There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D ... | class Solution(object):
def latestDayToCross(self, row, col, cells):
"""
:type row: int
:type col: int
:type cells: List[List[int]]
:rtype: int
"""
f = [[-1]*col for _ in xrange(row)]
for t in xrange(row*col):
r, c = cells[t]
f[... |
0bc704 | 37ab89 | You are given two numeric strings num1 and num2 and two integers max_sum and min_sum. We denote an integer x to be good if:
num1 <= x <= num2
min_sum <= digit_sum(x) <= max_sum.
Return the number of good integers. Since the answer may be large, return it modulo 109 + 7.
Note that digit_sum(x) denotes the sum of the d... | class Solution:
def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int:
def f(size, digit_sum):
@cache
def dp(i, curr, lower):
if curr > digit_sum:
return 0
if i == len(size):
return 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.