_id
stringlengths
2
5
partition
stringclasses
2 values
text
stringlengths
5
289k
language
stringclasses
1 value
meta_information
dict
title
stringclasses
1 value
d101
train
n = int(input()) for _ in range(n): a, b, c = list(map(int, input().split())) print(min((a+b+c)//2, a+b, a+c, b+c))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1263/A" }
d102
train
import os from io import BytesIO # input = BytesIO(os.read(0, os.fstat(0).st_size)).readline for i in range(int(input())): a, b, c, r = list(map(int, input().split())) a, b = min(a, b), max(a, b) left = max(c - r, a) right = min(c + r, b) if right >= a and left <= right: print(b - a - (right - left)) else: print(b - a)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1282/A" }
d103
train
s = [] for i in range(1, 10): k = 0 for l in range(1, 10): k *= 10 k += i s.append(k) s.sort() q = int(input()) while q: n = int(input()) l = 0 r = len(s) while l + 1 < r: m = (l + r) // 2 if s[m] <= n: l = m else: r = m print(r) q -= 1
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1259/A" }
d104
train
t = int(input()) for _ in range(t): n, m = [int(x) for x in input().split()] grid = [[int(x) for x in input().split()] for _ in range(n)] rows = sum(1 for x in grid if all(y == 0 for y in x)) cols = sum(1 for j in range(m) if all(grid[i][j] == 0 for i in range(n))) res = min(rows, cols) print("Ashish" if res % 2 else "Vivek")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1365/A" }
d105
train
from sys import stdin input = stdin.readline q = int(input()) for rwerew in range(q): n = int(input()) p = list(map(int,input().split())) c = list(map(int,input().split())) for i in range(n): p[i] -= 1 przyn = [0] * n grupa = [] i = 0 while i < n: if przyn[i] == 1: i += 1 else: nowa_grupa = [i] j = p[i] przyn[i] = 1 while j != i: przyn[j] = 1 nowa_grupa.append(j) j = p[j] grupa.append(nowa_grupa) grupacol = [] for i in grupa: cyk = [] for j in i: cyk.append(c[j]) grupacol.append(cyk) #print(grupacol) mini = 234283742834 for cykl in grupacol: dziel = [] d = 1 while d**2 <= len(cykl): if len(cykl)%d == 0: dziel.append(d) d += 1 dodat = [] for d in dziel: dodat.append(len(cykl)/d) dziel_ost = list(map(int,dziel + dodat)) #print(dziel_ost, len(cykl)) for dzielnik in dziel_ost: for i in range(dzielnik): indeks = i secik = set() chuj = True while indeks < len(cykl): secik.add(cykl[indeks]) indeks += dzielnik if len(secik) > 1: chuj = False break if chuj: mini = min(mini, dzielnik) print(mini)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1327/D" }
d106
train
import math t = int(input()) for test in range(t): n,k = map(int,input().split()) A = list(map(int,input().split())) A.sort() ans = 0 for i in range(1,n): if(A[i]>k): ans = 0 break rem = k-A[i] ans+=rem//A[0] print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1417/A" }
d107
train
t = int(input()) for ti in range(t): n = int(input()) lri = [None for _ in range(n)] for _ in range(n): li, ri = list(map(int, input().split())) lri[_] = (li, ri, _) lri.sort() t = [None for _ in range(n)] ct, t[lri[0][2]], eg = 1, 1, lri[0][1] for i in range(1, n): if lri[i][0] <= eg: t[lri[i][2]] = ct eg = max(eg, lri[i][1]) else: ct = 3 - ct t[lri[i][2]] = ct eg = lri[i][1] if all(ti == 1 for ti in t): print(-1) else: print(*t)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1101/C" }
d108
train
t = int(input()) for _ in range(t): a, b, c, d = [int(i) for i in input().split(" ")] sgn = (a+b)%2 small = False large = False if a == 0 and d == 0: small = True if b == 0 and c == 0: large = True okay = [True] * 4 if sgn == 0: okay[0] = False okay[1] = False else: okay[2] = False okay[3] = False if small: okay[0] = False okay[3] = False if large: okay[1] = False okay[2] = False print(" ".join(["Ya" if okay[i] else "Tidak" for i in range(4)]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1425/H" }
d109
train
for _ in range(int(input())): n=int(input()) li=list(map(int,input().split())) ans=0 for i in range(n): if li[i]>=i: ans+=1 else: break for i in range(n): if li[n-1-i]>=i: ans+=1 else: break if ans>n: print("Yes") else: print("No")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1291/B" }
d110
train
import sys import math from collections import defaultdict from collections import deque from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : list(map(int, input().split())) go = lambda : 1/0 def write(*args, sep="\n"): for i in args: sys.stdout.write("{}{}".format(i, sep)) INF = float('inf') MOD = int(1e9 + 7) YES = "YES" NO = -1 for _ in range(int(input())): try: n, m = read() arr = read() x = [0] * 65 if sum(arr) < n: print(NO) go() for i in arr: x[int(math.log2(i))] += 1 ans = 0 for i in range(65): if (1 << i) & n: if x[i] != 0: x[i] -= 1 continue total = 0 for j in range(i): total += (1 << j) * x[j] if total >= (1 << i): temp = 1 << i for j in reversed(range(i)): while temp - (1 << j) >= 0 and x[j] > 0: temp -= 1 << j x[j] -= 1 continue j = i while j < 65 and x[j] == 0: j += 1 if j == 65: print(NO) go() else: x[j] -= 1 for k in range(i, j): x[k] += 1 ans += (j - i) print(ans) except ZeroDivisionError: continue except Exception as e: print(e) continue
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1303/D" }
d111
train
for _ in range(int(input())): n, k = tuple(map(int, input().split())) arr = list(map(int, input().split())) peaks = [0 for i in range(n)] for i in range(1, n - 1): if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: peaks[i] = 1 cnt = 0 max_peaks = 0 answer = 0 for i in range(k - 1): cnt += peaks[i] max_peaks += peaks[i] for i in range(k - 1, n - 1): cnt -= peaks[i - k + 2] cnt += peaks[i] if cnt > max_peaks: max_peaks = cnt answer = i - k + 2 print(max_peaks + 1, answer + 1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1341/B" }
d112
train
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt from sys import stdin def run(n, m, pixels): ans = 1 << 30 acc = [[0] * (m + 1) for _ in range(n + 1)] for i in range(n): for j in range(m): acc[i + 1][j + 1] = acc[i + 1][j] + int(pixels[i][j]) for j in range(m): acc[i + 1][j + 1] += acc[i][j + 1] # print(acc) for k in range(2, max(n, m) + 1): r, c = (n + k - 1) // k, (m + k - 1) // k res = 0 for i in range(r): for j in range(c): x, y = i * k, j * k x2, y2 = min(x + k - 1, n - 1), min(y + k - 1, m - 1) zero = acc[x2 + 1][y2 + 1] - acc[x][y2 + 1] - acc[x2 + 1][y] + acc[x][y] # print(x, y, k, zero, k * k - zero) res += min(zero, k * k - zero) # print(k, res) ans = min(ans, res) print(ans) def main(): n, m = [int(x) for x in stdin.readline().split()] pixels = [] for i in range(n): pixels.append(stdin.readline().strip()) run(n, m, pixels) def __starting_point(): import os if os.path.exists('tmp.in'): stdin = open('tmp.in') main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/838/A" }
d113
train
import math def lexComp(a, b): if a[0] != b[0]: return -1 if a[0] < b[0] else 1 if a[1] != b[1]: return -1 if a[1] < b[1] else 1 return 0 def turn(a, b, c): return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) def dist2(a, b): return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 def solve(n): a = [list(map(int, input())) for _ in range(n)] points = [] for i in range(n): for j in range(n): if a[i][j] == 1: curPoints = [] for dx in range(0, 2): for dy in range(0, 2): ok = True for ddx in range(0, 2): for ddy in range(0, 2): x, y = i - 1 + dx + ddx, j - 1 + dy + ddy if 0 <= x < n and 0 <= y < n and a[x][y] == 0: ok = False if ok: curPoints.append((i + dx, j + dy)) points.append(curPoints[0]) points = list(set(points)) for i in range(1, len(points)): if lexComp(points[0], points[i]) > 0: points[0], points[i] = points[i], points[0] points[1:] = sorted(points[1:], key=lambda p: (math.atan2(p[1] - points[0][1], p[0] - points[0][0]), dist2(p, points[0]))) hull = [] for p in points: while len(hull) >= 2 and turn(hull[-2], hull[-1], p) <= 0: hull.pop() hull.append(p) hull = [(p[1], n - p[0]) for p in hull] hull = hull[::-1] start = 0 for i in range(1, len(hull)): if lexComp(hull[i], hull[start]) < 0: start = i newHull = hull[start:] newHull.extend(hull[:start]) hull = newHull print(len(hull)) for p in hull: print(p[0], p[1]) while True: n = int(input()) if n == 0: break solve(n)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/690/B2" }
d114
train
import math from decimal import Decimal import heapq from collections import deque def na(): n = int(input()) b = [int(x) for x in input().split()] return n,b def nab(): n = int(input()) b = [int(x) for x in input().split()] c = [int(x) for x in input().split()] return n,b,c def dv(): n, m = list(map(int, input().split())) return n,m def dva(): n, m = list(map(int, input().split())) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] return n,m,b def eratosthenes(n): sieve = list(range(n + 1)) for i in sieve: if i > 1: for j in range(i + i, len(sieve), i): sieve[j] = 0 return sorted(set(sieve)) def lol(lst,k): k=k%len(lst) ret=[0]*len(lst) for i in range(len(lst)): if i+k<len(lst) and i+k>=0: ret[i]=lst[i+k] if i+k>=len(lst): ret[i]=lst[i+k-len(lst)] if i+k<0: ret[i]=lst[i+k+len(lst)] return(ret) def nm(): n = int(input()) b = [int(x) for x in input().split()] m = int(input()) c = [int(x) for x in input().split()] return n,b,m,c def dvs(): n = int(input()) m = int(input()) return n, m def fact(a, b): c = [] ans = 0 f = int(math.sqrt(a)) for i in range(1, f + 1): if a % i == 0: c.append(i) l = len(c) for i in range(l): c.append(a // c[i]) for i in range(len(c)): if c[i] <= b: ans += 1 if a / f == f and b >= f: return ans - 1 return ans t = int(input()) for i in range(t): a ,b = list(map(int, input().split())) if a == b: print(0) else: d = abs(a - b) k1 = d//5 d -= k1 *5 k2 = d // 2 d -= k2 * 2 print(d + k1 + k2)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1255/A" }
d115
train
import sys input = sys.stdin.readline import bisect t=int(input()) for testcases in range(t): n=int(input()) A=list(map(int,input().split())) m=int(input()) PS=[tuple(map(int,input().split())) for i in range(m)] PS.sort() K=[PS[-1]] for a,b in PS[::-1][1:]: if b<=K[-1][1]: continue else: K.append((a,b)) K.reverse() ANS=1 count=0 countmax=n+1 LEN=len(K) for a in A: x=bisect.bisect_left(K,(a,0)) if x==LEN: print(-1) break elif K[x][1]>=count+1 and countmax>=count+1: count+=1 countmax=min(countmax,K[x][1]) else: ANS+=1 count=1 countmax=K[x][1] #print(a,count,countmax,ANS) else: print(ANS)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1257/D" }
d116
train
class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return import sys,heapq,random input=sys.stdin.readline n=int(input()) spell=[tuple(map(int,input().split())) for i in range(n)] S=set([]) for i in range(n): S.add(abs(spell[i][1])) S=list(S) S.sort(reverse=True) comp={i:e+1 for e,i in enumerate(S)} N=len(S) x_exist=BIT(N) y_exist=BIT(N) power=BIT(N) X,Y,S=0,0,0 Xmax=[] Ymin=[] x_data=[0]*(N+1) y_data=[0]*(N+1) for i in range(n): t,d=spell[i] S+=d if d<0: id=comp[-d] if t==0: X-=1 x_exist.update(id,-1) power.update(id,d) x_data[id]-=1 else: Y-=1 y_exist.update(id,-1) power.update(id,d) y_data[id]-=1 else: id=comp[d] if t==0: X+=1 x_exist.update(id,1) power.update(id,d) heapq.heappush(Xmax,-d) x_data[id]+=1 else: Y+=1 y_exist.update(id,1) power.update(id,d) heapq.heappush(Ymin,d) y_data[id]+=1 if X==0: if Y==0: print(0) else: while not y_data[comp[Ymin[0]]]: heapq.heappop(Ymin) print(2*S-Ymin[0]) else: if Y==0: print(S) else: start=0 end=N while end-start>1: test=(end+start)//2 if x_exist.query(test)+y_exist.query(test)<=Y: start=test else: end=test if y_exist.query(start)!=Y: print(S+power.query(start)) else: while not y_data[comp[Ymin[0]]]: heapq.heappop(Ymin) while not x_data[comp[-Xmax[0]]]: heapq.heappop(Xmax) print(S+power.query(start)-Ymin[0]-Xmax[0])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1398/E" }
d117
train
for nt in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=sum(l) e=l[0] for i in range(1,n): e=e^l[i] if s==2*e: print(0) print () else: print(2) print(e,s+e)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1270/C" }
d118
train
from sys import stdin input = stdin.readline tests = int(input()) for test in range(tests): n, m = list(map(int, input().split())) a = [[0] * m for _ in range(n)] r = [[int(i) for i in input().split()] for _ in range(n)] c = [[int(i) for i in input().split()] for _ in range(m)] z = [[-1, -1] for _ in range(n * m + 1)] for i in range(n): for j in range(m): z[r[i][j]][0] = j for i in range(m): for j in range(n): z[c[i][j]][1] = j for i in range(1, n * m + 1): a[z[i][1]][z[i][0]] = i for i in a: print(' '.join([str(j) for j in i]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1413/B" }
d119
train
__MULTITEST = True ## solve def solve(): n, x = map(int, input().split()) a = list(map(int, input().split())) a.sort() group = 0 ptr = n-1 members = 0 currentMin = int(1e10) while ptr > -1: currentMin = min(currentMin, a[ptr]) members += 1 if currentMin * members >= x: group += 1 members = 0 currentMin = int(1e10) ptr -= 1 print(group) ## main def __starting_point(): t = (int(input()) if __MULTITEST else 1) for tt in range(t): solve(); __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1380/C" }
d120
train
import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 pnt = [max(deg[i]-1,1) for i in range(n+1)] root = 1 stack = [root] dist = [0]*(n+1) dist[root] = pnt[root] while stack: x = stack.pop() for y in graph[x]: if dist[y] == 0: dist[y] = dist[x]+pnt[y] stack.append(y) far = dist.index(max(dist)) root = far stack = [root] dist = [0]*(n+1) dist[root] = pnt[root] while stack: x = stack.pop() for y in graph[x]: if dist[y] == 0: dist[y] = dist[x]+pnt[y] stack.append(y) print(max(dist))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1238/F" }
d121
train
import sys input = sys.stdin.readline t=int(input()) def calc(x): return x*(x+1)//2 for test in range(t): n,m=list(map(int,input().split())) ANS=calc(n) k=n-m q,mod=divmod(k,m+1) ANS-=calc(q+1)*mod+calc(q)*(m+1-mod) print(ANS)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1301/C" }
d122
train
for _ in range(int(input())): n = int(input()) ar = list(map(int, input().split())) ar.sort() print(abs(ar[n] - ar[n - 1]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1300/B" }
d123
train
class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: max_score = 0 curr_score= 0 init_hand = cardPoints[len(cardPoints)-k:] max_score = sum(init_hand) curr_score = max_score for i in range(k): curr_score -= init_hand[i] curr_score += cardPoints[i] if curr_score > max_score: max_score = curr_score return max_score
PYTHON
{ "starter_code": "\nclass Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/" }
d124
train
import math class Solution: def numMusicPlaylists(self, N: int, L: int, K: int) -> int: s=0 c=0 r=0 x=math.factorial(N) while(True): c=x*((N-r-K)**(L-K))*(-1)**(r)//(math.factorial(N-r-K)*math.factorial(r)) if(c!=0): s=(s+c)%(10**9+7) r+=1 else: return s
PYTHON
{ "starter_code": "\nclass Solution:\n def numMusicPlaylists(self, N: int, L: int, K: int) -> int:\n ", "url": "https://leetcode.com/problems/number-of-music-playlists/" }
d125
train
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ return target in nums
PYTHON
{ "starter_code": "\nclass Solution:\n def search(self, nums: List[int], target: int) -> bool:\n ", "url": "https://leetcode.com/problems/search-in-rotated-sorted-array-ii/" }
d126
train
class Solution: def superPow(self, a, b): result = 1 fermatb = (int(''.join(map(str, b)))) % 570 while fermatb: if fermatb & 1: result = (result * a) % 1337 a = (a * a) % 1337 fermatb >>= 1 return result
PYTHON
{ "starter_code": "\nclass Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/super-pow/" }
d127
train
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: n = len(s) count = collections.Counter(s[i : i + minSize] for i in range(0, n - minSize + 1)) res = 0 for k, v in count.items(): if len(set(k)) <= maxLetters: res = max(res, v) return res
PYTHON
{ "starter_code": "\nclass Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/" }
d128
train
class Solution: def profitableSchemes(self, G: int, P: int, group: List[int], profit: List[int]) -> int: MOD = 10**9 + 7 group_len, profit_len = len(group),len(profit) dp = [[0]*(G+1) for _ in range(P+1)] dp[0][0] = 1 for pro, gro in zip(profit,group): dp2 = [x[:] for x in dp] for p1 in range(P+1): p = min(pro + p1,P) for g1 in range(G+1-gro): g = g1 + gro dp2[p][g] += dp[p1][g1] dp2[p][g] %= MOD dp = dp2 return sum(dp[-1]) %MOD
PYTHON
{ "starter_code": "\nclass Solution:\n def profitableSchemes(self, G: int, P: int, group: List[int], profit: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/profitable-schemes/" }
d129
train
class Solution: def calculate(self, s): """ :type s: str :rtype: int """ res = 0 num = 0 sign = 1 stk = [] for c in s: if c.isdigit(): num = 10 * num + (ord(c) - ord('0')) elif c == '+': res += sign * num num = 0 sign = 1 elif c == '-': res += sign * num num = 0 sign = -1 elif c == '(': stk.append(res) stk.append(sign) res = 0 sign = 1 elif c == ')': res += sign * num res *= stk.pop() res += stk.pop() num = 0 sign = 1 if num: res += sign * num return res
PYTHON
{ "starter_code": "\nclass Solution:\n def calculate(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/basic-calculator/" }
d130
train
class Solution: def maxScoreSightseeingPair(self, A: List[int]) -> int: curmaxsight = A[0] - 1 curmaxpair = 0 for sight in A[1:]: if sight + curmaxsight > curmaxpair: curmaxpair = sight + curmaxsight if sight > curmaxsight: curmaxsight = sight curmaxsight -= 1 return curmaxpair
PYTHON
{ "starter_code": "\nclass Solution:\n def maxScoreSightseeingPair(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/best-sightseeing-pair/" }
d131
train
class Solution: def numberOfArrays(self, s: str, k: int) -> int: dp = [-1] * len(s) return self.dfs(s, k, 0, dp) def dfs(self, s: str, k: int, start: int, dp: List[int]) -> int: if start == len(s): return 1 if s[start] == '0': return 0 if dp[start] != -1: return dp[start] res, num = 0, 0 for i in range(start, len(s)): num = num * 10 + (ord(s[i]) - ord('0')) if num > k: break res += self.dfs(s, k, i + 1, dp) res %= 10**9 + 7 dp[start] = res return res
PYTHON
{ "starter_code": "\nclass Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n ", "url": "https://leetcode.com/problems/restore-the-array/" }
d132
train
class Solution(object): def parse(self,expression,d,i): count = 0 start = i if expression[i] == "(": count += 1 i += 1 while count != 0: if expression[i] == "(": count += 1 elif expression[i] == ")": count -= 1 i += 1 val = self.evaluate(expression[start:i],d) else: while i < len(expression) and expression[i] != " " and expression[i] != ")": i += 1 val = expression[start:i] if self.isnumber(val): val = int(val) return i,val def get_left_right(self,expression,d): i = 0 count = 0 i,left = self.parse(expression,d,0) if i == len(expression) or expression[i] == ")": return left,None,i i += 1 i,right = self.parse(expression,d,i) return left,right,i def isnumber(self,s): for c in s: if ord("0") <= ord(c) <= ord("9") or c == "+" or c == "-": continue else: return False return True def evaluate(self, expression,d = {}): """ :type expression: str :rtype: int """ if self.isnumber(expression): return int(expression) newd = {} for key in d: newd[key] = d[key] expression = expression[1:len(expression)-1] oper = "" if expression[0:3] == "add" or expression[:3] == "let": oper = expression[0:3] expression = expression[4:] else: oper = "mult" expression = expression[5:] if oper == "mult" or oper == "add": left,right,_ = self.get_left_right(expression,newd) if isinstance(left,str): left = newd[left] if isinstance(right,str): right = newd[right] if oper == "mult": return left*right else: return left + right i = 0 while True: left,right,i = self.get_left_right(expression,newd) expression = expression[i+1:] if right == None: if isinstance(left,str): return newd[left] return left if isinstance(right,str): right = newd[right] newd[left] = right # s = Solution() # print(s.evaluate("(let x 2 (mult x (let x 3 y 4 (add x y))))"))
PYTHON
{ "starter_code": "\nclass Solution:\n def evaluate(self, expression: str) -> int:\n ", "url": "https://leetcode.com/problems/parse-lisp-expression/" }
d133
train
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: dp = [0] + [-1 for i in range(days[-1])] for day in days: dp[day] = 0 for i in range(1, len(dp)): if dp[i] == -1: dp[i] = dp[i-1] else: dp[i] = min( dp[i-1] + costs[0], dp[max(i-7, 0)] + costs[1], dp[max(i-30, 0)] + costs[2], ) return dp[-1]
PYTHON
{ "starter_code": "\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/minimum-cost-for-tickets/" }
d134
train
class Solution: def balancedString(self, s: str) -> int: # minimum window so that outside is possible if len(s) //4 != len(s) / 4: return -1 ans, lb, n_cnt = len(s), 0, collections.Counter(s) i = 0 while i < len(s): n_cnt[s[i]] -= 1 while lb < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'): ans = min(ans, abs(i - lb + 1)) if ans == 0: return 0 n_cnt[s[lb]] += 1 lb += 1 # here is actually a swap? if lb > i: i, lb = lb, i i +=1 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def balancedString(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/replace-the-substring-for-balanced-string/" }
d135
train
class Solution: def numDupDigitsAtMostN(self, N: int) -> int: # N -> total numbers less than or equal to N # We will calculate the integers with all different digits (which are less than/equal to N) # Then the answer would be: N - nums_with_different_digits # Calculate the number of digits in N NN, dd = N, 0 nums = [] # store the digits while(NN): dd += 1 nums.append(NN % 10) NN //= 10 nums.reverse() # numbers with less digits than that of N numbers = 0 for i in range(dd-1): numbers += 9 * (math.factorial(9) // math.factorial(9-i)) # find the N-digit numbers (all-different) already_visited_digits = set() def fac2(n, k): return math.factorial(n) // math.factorial(n-k) for i,n in enumerate(nums): k = 0 for j in range((1 if i==0 else 0), (n+1 if i==dd-1 else n)): if(j in already_visited_digits): continue k += 1 numbers += k * fac2(10-i-1, dd-i-1) if n in already_visited_digits: # All the numbers with this prefix will have at least one common digit break already_visited_digits.add(n) return N - numbers
PYTHON
{ "starter_code": "\nclass Solution:\n def numDupDigitsAtMostN(self, N: int) -> int:\n ", "url": "https://leetcode.com/problems/numbers-with-repeated-digits/" }
d136
train
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: j = 0 l = [] for i in pushed: l.append(i) while l and (l[-1] == popped[j]): l.pop() j += 1 if l: return False return True
PYTHON
{ "starter_code": "\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/validate-stack-sequences/" }
d137
train
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: # Pad with inf to make implementation easier INF = -10_000 n = len(grid) total = 0 max_rows = [max(row, default=INF) for row in grid] # Transpose the grid to make max less cumbersome max_cols = [max(col, default=INF) for col in zip(*grid)] for i, best_row in enumerate(max_rows): for j, best_col in enumerate(max_cols): new_height = min(best_row, best_col) total += new_height - grid[i][j] return total
PYTHON
{ "starter_code": "\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n ", "url": "https://leetcode.com/problems/max-increase-to-keep-city-skyline/" }
d138
train
class Solution: def minimumOneBitOperations(self, n: int) -> int: s = 0 m = n while m: s += m & 1 m >>= 1 k = 1 while s: s -= bool(n & k) n ^= (s & 1) and k k <<= 1 return n
PYTHON
{ "starter_code": "\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/" }
d139
train
class Solution: def getMaxLen(self, nums: List[int]) -> int: maxx = 0 nums.append(0) # starting position # where we find a 0 i = -1 minusarr = [] for j,n in enumerate(nums): if n == 0: # now figure out previous ones tot = j-i-1 if not minusarr or len(minusarr)%2 == 0: maxx = max(maxx, tot) else: # drop the first or last 0 left = minusarr[0]-i right = j-minusarr[-1] maxx = max(maxx, tot - min(left, right)) # reinitiate minusarr = [] i = j elif n < 0: minusarr.append(j) return maxx
PYTHON
{ "starter_code": "\nclass Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/" }
d140
train
class Solution: def minDeletionSize(self, A: List[str]) -> int: def isSorted(arr, i, j): return all(arr[k] <= arr[k+1] for k in range(i, j)) ans = 0 ranges = [[0, len(A)-1]] for col in zip(*A): if not ranges: break if all(isSorted(col, i, j) for i, j in ranges): tmp = [] for i, j in ranges: start = i for k in range(i, j+1): if col[k] != col[start]: if k - start > 1: tmp.append([start, k-1]) start = k if j + 1 - start > 1: tmp.append([start, j]) start = k ranges[:] = tmp else: ans += 1 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ", "url": "https://leetcode.com/problems/delete-columns-to-make-sorted-ii/" }
d141
train
class Solution: def findMaximumXOR(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 for bit in range(31, -1, -1) : ans = (ans << 1) + 1 pre = set() for n in nums : p = (n >> bit) & ans if p in pre : break pre.add(ans - p) else : ans -= 1 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/" }
d142
train
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo = 0 hi = len(people) - 1 count = 0 while lo <= hi: count += 1 if people[lo] + people[hi] <= limit: lo += 1 hi -= 1 return count
PYTHON
{ "starter_code": "\nclass Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n ", "url": "https://leetcode.com/problems/boats-to-save-people/" }
d143
train
class Solution: def findLUSlength(self, strs): """ :type strs: List[str] :rtype: int """ def isSubseq(s1, s2): i, m=0, len(s1) for c in s2: if i==m: return True if s1[i]==c: i+=1 return i==m strs.sort(key=len, reverse=True) for i, s1 in enumerate(strs): if all(not isSubseq(s1, s2) for j, s2 in enumerate(strs) if i!=j): return len(s1) return -1
PYTHON
{ "starter_code": "\nclass Solution:\n def findLUSlength(self, strs: List[str]) -> int:\n ", "url": "https://leetcode.com/problems/longest-uncommon-subsequence-ii/" }
d144
train
class Solution: def totalFruit(self, tree: List[int]) -> int: prior_fruit = tree[0] prior_fruit_counter = 0 fruits_in_basket = [tree[0]] fruits_in_basket_counter = 0 max_fib = -1 for fruit in tree: if prior_fruit == fruit: prior_fruit_counter += 1 fruits_in_basket_counter += 1 elif prior_fruit != fruit: if fruit in fruits_in_basket: fruits_in_basket_counter += 1 else: fruits_in_basket, fruits_in_basket_counter = [prior_fruit, fruit], prior_fruit_counter + 1 prior_fruit, prior_fruit_counter = fruit, 1 if fruits_in_basket_counter > max_fib: max_fib = fruits_in_basket_counter return max_fib
PYTHON
{ "starter_code": "\nclass Solution:\n def totalFruit(self, tree: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/fruit-into-baskets/" }
d145
train
class Solution: def minSteps(self, n): """ :type n: int :rtype: int """ primeFactors=[] for i in range(2,int(n**.5)+1): while n%i==0: primeFactors.append(i) n=n//i if n>1: primeFactors.append(n) return sum(primeFactors)
PYTHON
{ "starter_code": "\nclass Solution:\n def minSteps(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/2-keys-keyboard/" }
d146
train
class Solution(object): def judgePoint24(self, nums): bad = '떢븻각걎냇갅갸꺚뵟숣욄뵴뵞뤼갈갌뤔떌옊메늄숭캸긶꺛옖갍뇐쩢곴듇걯궄옕왹눞솴걃끗긬땉궿가쌀낐걄숤뺴늘걘꽸숢걂갋갃쫐꼔솾쩡쇔솿끛뤜간븺쩬웨딴옠뤛갂뵪덠놤빐옋귒늂갰갖놥궾갆옌뼘묰거갎긷낤겼' return chr(int(''.join(map(str, sorted(nums)))) + 42921) not in bad
PYTHON
{ "starter_code": "\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/24-game/" }
d147
train
class Solution: def decodeString(self, s): """ :type s: str :rtype: str """ stack = [] stack.append(["", 1]) num = "" for ch in s: if ch.isdigit(): num += ch elif ch == '[': stack.append(["", int(num)]) num = "" elif ch == ']': st, k = stack.pop() stack[-1][0] += st*k else: stack[-1][0] += ch return stack[0][0]
PYTHON
{ "starter_code": "\nclass Solution:\n def decodeString(self, s: str) -> str:\n ", "url": "https://leetcode.com/problems/decode-string/" }
d148
train
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: mod = 10**9+7 order = sorted(range(n), key=lambda i: efficiency[i], reverse=True) heap = [] filled = 0 rec = 0 speed_sum = 0 for i in order: if filled < k: heapq.heappush(heap, speed[i]) filled += 1 speed_sum += speed[i] else: removed = heapq.heappushpop(heap, speed[i]) speed_sum += speed[i] - removed rec = max(rec, speed_sum*efficiency[i]) return rec %mod
PYTHON
{ "starter_code": "\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-performance-of-a-team/" }
d149
train
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: ws = sorted(worker, reverse=True) dp = sorted(zip(difficulty, profit), key=lambda x: x[1], reverse=True) # print(list(dp)) i = 0 total = 0 for w in ws: while dp[i][0] > w: i = i + 1 if i >= len(dp): return total total = total + dp[i][1] return total
PYTHON
{ "starter_code": "\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/most-profit-assigning-work/" }
d150
train
class Solution: def removeDuplicates(self, s: str, k: int) -> str: st=[['*',0]] for c in s: if c!=st[-1][0]: st.append([c,1]) else: st[-1][1]+=1 if st[-1][1]==k: st.pop() res='' for c,v in st: res+=c*v return res
PYTHON
{ "starter_code": "\nclass Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n ", "url": "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/" }
d151
train
class Solution: def partitionDisjoint(self, A: List[int]) -> int: biggest = A[0] newbiggest = A[0] lenL = 1 total = 1 for itr in A[1:]: total += 1 if itr < biggest: lenL = total biggest = newbiggest else: if itr > newbiggest: newbiggest = itr return lenL
PYTHON
{ "starter_code": "\nclass Solution:\n def partitionDisjoint(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/partition-array-into-disjoint-intervals/" }
d152
train
class Solution: def strongPasswordChecker(self, s): """ :type s: str :rtype: int """ def length_requirement(password): length = len(password) # positive means addition, negative means deletion if length < 6: return 6 - length elif length > 20: return 20 - length else: return 0 def category_requirement(password): # input string = set(password) lowercase = set('qwertyuiopasdfghjklzxcvbnm') uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM') digit = set('1234567890') condition = [lowercase, uppercase, digit] # output positive for addition missing = 0 for s in condition: if not s & string: missing += 1 return missing def repeat_requirement(password): # store the repeated character and counts its occurrence count = 1 repeat = None weak_pair = [] for c in password: if c == repeat: # the same character count += 1 else: # new character if count >= 3: weak_pair.append([repeat, count]) count = 1 repeat = c # add last pair if count >= 3: weak_pair.append([repeat, count]) # length of 'aaaaaa' divide by 3 returns the time of change change = 0 one = 0 two = 0 for _, length in weak_pair: change += length // 3 if length % 3 == 0: one += 1 elif length % 3 == 1: two += 1 return change, one, two def minimum_change(password): print(password, end=' ') length = length_requirement(password) category = category_requirement(password) repeat, one, two = repeat_requirement(password) # length: delete or insert # category: insert or replace # repeat: delete or replace, or insert print(length, category, repeat, one, two, end=' * ') # insert or replace is effective if length >= 0: return max(length, category, repeat) else: # delete required delete = - length repeat -= min(delete, one) repeat -= min(max(delete - one, 0), two * 2) // 2 repeat -= max(delete - one - 2 * two, 0) // 3 return delete + max(category, repeat) return minimum_change(s)
PYTHON
{ "starter_code": "\nclass Solution:\n def strongPasswordChecker(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/strong-password-checker/" }
d153
train
class Solution: def maxDistance(self, position: List[int], m: int) -> int: position.sort() max_distance_between = (position[-1] - 1) // (m - 1) min_distance_between = 1 if self.isDistancePossible(max_distance_between, position, m): return max_distance_between while max_distance_between > min_distance_between + 1: middle_distance = (min_distance_between + max_distance_between) // 2 if self.isDistancePossible(middle_distance, position, m): min_distance_between = middle_distance else: max_distance_between = middle_distance return min_distance_between def isDistancePossible(self, distance, position, m): used_ball_count = 0 previous_used_position = float('-inf') for pos in position: if pos - previous_used_position >= distance: used_ball_count += 1 previous_used_position = pos return used_ball_count >= m
PYTHON
{ "starter_code": "\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n ", "url": "https://leetcode.com/problems/magnetic-force-between-two-balls/" }
d154
train
class Solution: def makesquare(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) < 4: return False length = sum(nums) if length % 4: return False length = (int) (length / 4) nums.sort(reverse=True) #print(nums) if length < nums[0]: return False elif length == nums[0]: stack = list([(set([0]), 1, length, 1)]) else: stack = list([(set([0]), 1, length - nums[0], 2)]) # (usedIndexSet, searchStartFromIndex, target, remainRounds) while stack: usedSet, startIndex, target, remainRounds = stack.pop() #print(usedSet, set(range(0, len(nums))) - usedSet, target, remainRounds) for i in range(len(nums) - 1, startIndex - 1, -1): if i in usedSet: continue num = nums[i] if num < target and i + 1 < len(nums): stack.append((usedSet | {i}, i+1, target - num, remainRounds)) elif num == target: if remainRounds == 0: return True else: stack.append((usedSet | {i}, 1, length, remainRounds - 1)) # Else not valid path, continue return False
PYTHON
{ "starter_code": "\nclass Solution:\n def makesquare(self, nums: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/matchsticks-to-square/" }
d155
train
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: mod = int(1e9)+7 return ( ( self.getMax(horizontalCuts, h) % mod ) * ( self.getMax(verticalCuts, w) % mod ) ) % mod def getMax(self, cuts, size): if len(cuts) == 1: return max(cuts[0], size - cuts[0]) cuts.sort() max_cut_size = max(cuts[0], size - cuts[-1]) for index in range(1, len(cuts)): if cuts[index] - cuts[index - 1] > max_cut_size: max_cut_size = cuts[index] - cuts[index - 1] return max_cut_size
PYTHON
{ "starter_code": "\nclass Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/" }
d156
train
class Solution: def maxJumps(self, arr: List[int], d: int) -> int: dp = [1] * (len(arr) + 1) stack = [] for i, n in enumerate(arr + [1000000]): while stack and arr[stack[-1]] < n: same_height_idx = [stack.pop()] while stack and arr[stack[-1]] == arr[same_height_idx[0]]: same_height_idx.append(stack.pop()) for j in same_height_idx: # jump to left if i - j <= d: dp[i] = max(dp[i], dp[j] + 1) # jump to right if stack and j - stack[-1] <= d: dp[stack[-1]] = max(dp[stack[-1]], dp[j] + 1) stack.append(i) return max(dp[:-1])
PYTHON
{ "starter_code": "\nclass Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n ", "url": "https://leetcode.com/problems/jump-game-v/" }
d157
train
import sys def dp(s1, s2, i, j, mem): if (i, j) in mem: return mem[(i, j)] elif i >= len(s1) and j >= len(s2): res = '' elif i >= len(s1): res = s2[j:] elif j >= len(s2): res = s1[i:] else: if s1[i] == s2[j]: res = s1[i] + dp(s1, s2, i+1, j+1, mem) else: left = s1[i] + dp(s1, s2, i+1, j, mem) right = s2[j] + dp(s1, s2, i, j+1, mem) if len(left) < len(right): res = left else: res = right mem[(i, j)] = res return res class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: if len(str1) == len(str2) and len(str1) == 1000: return 'xjatuwbmvsdeogmnzorndhmjoqnrqjnhmfueifqwleggfbctttiqkezrltzyeqvqemfoikpzgotfyghxkyzdenhftafiepwrvmrovwtpzzsyuiseumzmywongllqmtvsdsoptwammerovabtgemkhpowndejvbuwbporfyroknrjoekdgqhqlgzxifiswevpepegmyhnxagjtsqlradgcciaecsvbpgqjzwtdebctmtallzyuvxkdztoavfxysgejqgrqkliixuvnagwzmassthjecvkfzmyongloclemvjnxkcwqqvgrzpsnsrwnigjmxyokbthtkesuawirecfugzrbydifsupuqanetgunwolqmupndhcapzxvduqwmzidatefhvpfmaqmzzzfjapdxgmddsdlhyoktbdeugqoyepgbmjkhmfjztsxpgojqbfspedhzrxavmpjmwmhngtnlduynskpapvwlprzruadbmeeqlutkwdvgyzghgprqcdgqjjbyefsujnnssfmqdsvjhnvcotynidziswpzhkdszbblmrustoxwtilhkoawcrpatbypvkmajumsthbebdxqqrpphuncthosljxxvfaeidbozayekxrolwezqtfzlifyzqcvvxmmnehrcskstepwshupglzgmbretpmyehtavnwzyunsxegmbtzjflnqmfghsvwpbknqhczdjlzibhrlmnouxrljwabwpxkeiedzoomwhoxuhffpfinhnairblcayygghzqmotwrywqaxdwetyvvgohmujneqlzurxcpnwdhipldofyqvfdhrggurbszqeqoxdurlofkqqnunrjomszjimrxbqyzyagyoptfzakolkieayzojwkryidtctemtesuhbzczzvhlbbhacnubdifjjocporuzuevsofbuevuxhgiexsmckibyfntnfcxhqgaoqyhfwqdakyobcooubdvypxjjtsrqarqagogrnaxeugzdmapyaggknksrfdrmuwqnoxrctnqspsztnyszhwqgdqjxxechxrsmbyhdlkwkvtlkdbjnmzgvdmhvbllqqlcemkqxopyixdlldcomhnmvnsaftphjdqkyjrrjqqqpkdgnmmelrdcscbwhtyhugieuppqqtwychtpjmlaeoxsckdlhlzyitomjczympqqmnisxzztlliydwtxhddvtvpleqdwamfbnhhkszsfgfcdvakysqmmausdvihopbvygqdktcwesudmhffagxmuayoalovskvcgetapucehntotdqbfxlqhkrolvxfzrtrmrfvjqoczkfaexwxsvujizcficzeuqflegwpbuuoyfuoovycmahhpzodstmpvrvkzxxtrsdsxjuuecpjwimbutnvqtxiraphjlqvesaxrvzywxcinlwfslttrgknbpdlscvvtkfqfzwudspewtgjposiixrfkkeqmdbvlmpazzjnywxjyaquilxrqnpdvinaegpccnnweuobqvgxnomulzoejantsalzyjjpnsrqkxemyivcatemoluhqngifychonbnizcjrlmuywxtlezdwnkkztancarphldmwhnkdguheloqyywrxrzjganyevjtrzofmtpuhifoqnokglbdeyshpodpmdcnhbccqtzxmimp' sys.setrecursionlimit(10**6) return dp(str1, str2, 0, 0, {})
PYTHON
{ "starter_code": "\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n ", "url": "https://leetcode.com/problems/shortest-common-supersequence/" }
d158
train
class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ '''维护两个下标,逐个比较,如果pj为*,则记录*的位置,将*后一个元素与si进行比较,如果不相等,则将i从记录的位置+1,重新比较''' i=0 j=0 star=-1 lenp=len(p) while i<len(s): if j<lenp and (s[i]==p[j] or p[j]=='?'): i+=1 j+=1 elif j<lenp and p[j]=='*': star=j mi=i j+=1 elif star!=-1: mi+=1 i=mi j=star+1 else: return False while j<lenp and p[j]=='*': j+=1 return j==lenp
PYTHON
{ "starter_code": "\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ", "url": "https://leetcode.com/problems/wildcard-matching/" }
d159
train
class Solution: def kSimilarity(self, A: str, B: str) -> int: a = '' b = '' for i in range(len(A)): if A[i] != B[i]: a+=A[i] b+=B[i] return self.dfs(a,b) def dfs(self,a,b): if not a: return 0 one = [] two = [] for i in range(len(a)): if a[0] == b[i]: one.append(i) if b[0] == a[i]: two.append(i) if two: i = two[0] c = a[1:i] + a[i+1:] d = b[1:i] + b[i+1:] return self.dfs(c,d) + 1 else: res = float('inf') for i in one: c = a[i] + a[1:i] + a[i+1:] d = b[:i]+b[i+1:] res= min(res,self.dfs(c,d)+1) return res
PYTHON
{ "starter_code": "\nclass Solution:\n def kSimilarity(self, A: str, B: str) -> int:\n ", "url": "https://leetcode.com/problems/k-similar-strings/" }
d160
train
from collections import deque class Solution: def constrainedSubsetSum(self, nums, k): N, queue = len(nums), deque() dp = [val for val in nums] for i, val in enumerate(nums): if queue and (i - queue[0] > k): queue.popleft() if queue and dp[queue[0]] > 0: dp[i] += dp[queue[0]] while queue and dp[i] >= dp[queue[-1]]: queue.pop() queue.append(i) return max(dp)
PYTHON
{ "starter_code": "\nclass Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n ", "url": "https://leetcode.com/problems/constrained-subsequence-sum/" }
d161
train
class Solution: def stoneGame(self, piles: List[int]) -> bool: return True
PYTHON
{ "starter_code": "\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n", "url": "https://leetcode.com/problems/stone-game/" }
d162
train
class Solution(object): def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ # remember how many empty slots we have # non-null nodes occupy one slot but create two new slots # null nodes occupy one slot p = preorder.split(',') #initially we have one empty slot to put the root in it slot = 1 for node in p: # no empty slot to put the current node if slot == 0: return False # a null node? if node == '#': # ocuppy slot slot -= 1 else: # create new slot slot += 1 #we don't allow empty slots at the end return slot==0
PYTHON
{ "starter_code": "\nclass Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n ", "url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/" }
d163
train
class Solution: def longestCommonSubsequence(self, a: str, b: str) -> int: last, current = [0] * (len(b) + 1), [0] * (len(b) + 1) for i in range(len(a) - 1, -1, -1): for j in range(len(b) - 1, -1, -1): if a[i] == b[j]: current[j] = 1 + last[j + 1] else: current[j] = max(last[j], current[j + 1]) last = current current = [0] * (len(b) + 1) return last[0]
PYTHON
{ "starter_code": "\nclass Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n ", "url": "https://leetcode.com/problems/longest-common-subsequence/" }
d164
train
class Solution: def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return False for i in s: if i in t: index = t.find(i) t = t[index + 1:] else: return False return True
PYTHON
{ "starter_code": "\nclass Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n ", "url": "https://leetcode.com/problems/is-subsequence/" }
d165
train
class Solution: def minInteger(self, num: str, k: int) -> str: n=len(num) if k<=0: return num if k>n*(n-1)//2: return ''.join(sorted(list(num))) for i in range(10): idx = num.find(str(i)) if idx>=0 and idx<=k: return num[idx]+self.minInteger(num[:idx]+num[idx+1:],k-idx)
PYTHON
{ "starter_code": "\nclass Solution:\n def minInteger(self, num: str, k: int) -> str:\n ", "url": "https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/" }
d166
train
class Solution: def findLongestWord(self, s, d): """ :type s: str :type d: List[str] :rtype: str """ result = '' for word in d: lo = 0 for l in word: lo = s.find(l, lo)+1 if lo == 0: break if lo > 0 and len(word) >= len(result): if len(word) == len(result): result = word if word < result else result else: result = word return result
PYTHON
{ "starter_code": "\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n ", "url": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/" }
d167
train
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: flips = 0 print(bin(a)) print(bin(b)) print(bin(c)) while a or b or c: # print(a, b, c) if c % 2: if not (a % 2 or b % 2): flips += 1 else: flips += a % 2 + b % 2 a //= 2 b //= 2 c //= 2 return flips
PYTHON
{ "starter_code": "\nclass Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n ", "url": "https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/" }
d168
train
class Solution: def superEggDrop(self, K: int, N: int) -> int: def f(t): a=0 r=1 for i in range(1, K+1): r *= (t-i+1) r//=i a+=r if a>=N: break return a l, h= 1, N while l<h: m=(l+h)//2 if f(m)<N: l=m+1 else: h=m return l
PYTHON
{ "starter_code": "\nclass Solution:\n def superEggDrop(self, K: int, N: int) -> int:\n ", "url": "https://leetcode.com/problems/super-egg-drop/" }
d169
train
from collections import Counter class Solution: def canConstruct(self, s: str, k: int) -> bool: if k > len(s): #return False return False counter = Counter(s) odd_counts = 0 for char in counter: if counter[char] % 2 == 1: odd_counts += 1 return odd_counts <= k
PYTHON
{ "starter_code": "\nclass Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n ", "url": "https://leetcode.com/problems/construct-k-palindrome-strings/" }
d170
train
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if n==2:return 1 if n==3:return 2 res=1 while n>4: n=n-3 res*=3 return res*n
PYTHON
{ "starter_code": "\nclass Solution:\n def integerBreak(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/integer-break/" }
d171
train
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: n = len(arr) if n<=1: return 0 l,r = n,-1 for i in range(1,n): if arr[i]<arr[i-1]: l = i break # monotonicially increasing if l == n: return 0 for j in range(n-2,-1,-1): if arr[j]>arr[j+1]: r = j break # you can delete all to the left of r (including r) # you can also delete all to the right of l (including l) ans = min(r+1,n-l) i = 0 # sliding window, find the rightmost i for each j # note at all time i must be less than l for j in range(r+1,n): while i<l and arr[i] <= arr[j]: i += 1 ans = min(ans,j-i) return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/" }
d172
train
class Solution: def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ def prod(nums): #function to calculate product prod = 1 for i in nums: prod*=i return prod def listsplit(ls1,index): result = [] st = -1 for i in index: if i == 0: st = i else: result.append(ls1[st+1:i]) st = i if st<len(ls1)-1: result.append(ls1[st+1:]) return result #main starts here if not nums: return 0 if len(nums) == 1: return nums[0] #find zeros: if zeros are included the result would be zeros only result=[] if 0 in nums: zeros = [i for i in range(len(nums)) if nums[i] ==0] sublist = listsplit(nums,zeros) result.append(0) else: sublist = [nums] #find negative numbers. consider even or odd sublist = [i for i in sublist if i] for i in sublist: if prod(i) <0: #there is negative number in the list negative = [j for j in range(len(i)) if i[j] < 0] left,right = negative[0],negative[-1] if len(i) == 1: result_t = i[0] elif left == 0 or right == len(i) -1: result_t = max(prod(i[left+1:]),prod(i[:right])) else: left_p,right_p = prod(i[:left]),prod(i[right+1:]) if left_p <= right_p: result_t = prod(i[left+1:]) else: result_t = prod(i[:right]) else: result_t = prod(i) result.append(result_t) return max(result)
PYTHON
{ "starter_code": "\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-product-subarray/" }
d173
train
class Solution: def maxDiff(self, num: int) -> int: if num < 10: return 8 a = b = str(num) i = 0 while i < len(a): if a[i] == '9': i += 1 else: a = a.replace(a[i], '9') break if b[0] != '1': b = b.replace(b[0], '1') else: i = 1 while i < len(b): if b[i] == '1' or b[i] == '0': i += 1 else: b = b.replace(b[i], '0') break #print(a,b) return int(a) - int(b)
PYTHON
{ "starter_code": "\nclass Solution:\n def maxDiff(self, num: int) -> int:\n ", "url": "https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/" }
d174
train
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: freq = [0] * k for n in arr: freq[n%k] += 1 if freq[0] % 2: return False for i in range(1, (k//2)+1): if freq[i] != freq[k-i]: return False if k%2 is 0: if freq[k//2]%2: return False return True
PYTHON
{ "starter_code": "\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n ", "url": "https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/" }
d175
train
class Solution: def lengthLongestPath(self, input): """ :type input: str :rtype: int """ dict={0:0} maxlen=0 line=input.split("\n") for i in line: name=i.lstrip('\t') print(name) print((len(name))) depth=len(i)-len(name) if '.' in name: maxlen=max(maxlen, dict[depth]+len(name)) else: dict[depth+1]=dict[depth]+len(name)+1 return maxlen
PYTHON
{ "starter_code": "\nclass Solution:\n def lengthLongestPath(self, input: str) -> int:\n ", "url": "https://leetcode.com/problems/longest-absolute-file-path/" }
d176
train
class Solution: def findIntegers(self, num): """ :type num: int :rtype: int """ dp=[1,2] for i in range(2,32): dp.append(dp[i-1]+dp[i-2]) bnum=bin(num)[2:] size=len(bnum) ans=dp[size] for i in range(1,size): if bnum[i-1]==bnum[i]=='1': #关键 娥娥 对 因为他就是一个二进制数在这儿循环呢 #所以他可以这样 break if bnum[i-1]==bnum[i]=='0': ans-=dp[size-i]-dp[size-i-1] #其实问题就是在于这儿 是在干什么 为什么会有这么一部 算了 先记住 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def findIntegers(self, num: int) -> int:\n ", "url": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/" }
d177
train
class Solution: def isScramble(self, A, B): if len(A) != len(B) or sorted(A) != sorted(B): return False if len(A) == 1 or A == B: return True for i in range(1, len(A)): if self.isScramble(A[:i], B[:i]) and self.isScramble(A[i:], B[i:]): return True elif self.isScramble(A[:i], B[-i:]) and self.isScramble(A[i:], B[:-i]): return True return False
PYTHON
{ "starter_code": "\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n ", "url": "https://leetcode.com/problems/scramble-string/" }
d178
train
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ left=-1 right = 0 result = "" totalMatch = 0 d = {} for c in t: d[c] = d.get(c, 0) + 1 for right in range(len(s)): c = s[right] d[c] = d.get(c, 0) - 1 # good match if d[c] >=0: totalMatch +=1 #over match 可以不移动left #total match, need to advance left if totalMatch == len(t): totalMatch -= 1 left +=1 while d[s[left]]<0: d[s[left]] += 1 left += 1 # we dec the count here so that next round right need to match one more s[left], d[s[left]] += 1 if result == "" or len(result) > right - left: result = s[left: right+1] return result
PYTHON
{ "starter_code": "\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n ", "url": "https://leetcode.com/problems/minimum-window-substring/" }
d179
train
class Solution: def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 res = [nums[0]] def binarySearch(l,target): left , right = 0 , len(l)-1 while left < right: mid = (left + right)//2 if l[mid] >= target: right = mid else: left = mid + 1 return left for i in range(1,len(nums)): if nums[i] > res[-1]: res.append(nums[i]) else: res[binarySearch(res,nums[i])] = nums[i] return len(res)
PYTHON
{ "starter_code": "\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/longest-increasing-subsequence/" }
d180
train
class Solution: def getLengthOfOptimalCompression(self, s: str, k: int) -> int: n = len(s) def compLen(c): return 1 + len(str(c)) if c > 1 else 1 @lru_cache(None) def dp(i, k): # return {head: (len, -head_count)} if (n - i) <= k: return {} # remove all x, res = s[i], {} # remove if k: res = dp(i + 1, k - 1) # keep keep = dp(i + 1, k) t = [(1 + min((leng for leng, _ in list(keep.values())), default=0), -1)] if x in keep: leng, negc = keep[x] leng, negc = (leng - compLen(-negc) + compLen(-negc + 1), negc - 1) t.append((leng, negc)) if x in res: t.append(res[x]) res[x] = min(t) return res m = dp(0, k) return min((leng for leng, _ in list(m.values())), default = 0)
PYTHON
{ "starter_code": "\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n ", "url": "https://leetcode.com/problems/string-compression-ii/" }
d181
train
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: if startFuel >= target: return 0 heap = [] #record the reachable gas for now stop = 0 #total stops dist = startFuel #reachable distance for d, g in stations: if dist >= target: #if reach target, return return stop while heap and dist < d: #make sure we can reach current station by make minimum stops gas = heapq.heappop(heap) dist += -gas stop += 1 if dist < d: #if not reachable, return -1 return -1 heapq.heappush(heap, (-g)) #add current gas to heap for future stop if dist >= target: return stop while heap: #add the rest gas in heap from max to min to reach the target g = heapq.heappop(heap) stop += 1 dist += -g if dist >= target: return stop return -1
PYTHON
{ "starter_code": "\nclass Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n ", "url": "https://leetcode.com/problems/minimum-number-of-refueling-stops/" }
d182
train
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) if n < 2: return 0 sells = [0] * n buys = [0] * n buys[0] = -prices[0] for i in range(1, n): sells[i] = max(sells[i-1], buys[i-1] + prices[i]) buys[i] = max(buys[i-1], (sells[i-2] if i > 1 else 0) - prices[i]) return sells[n-1]
PYTHON
{ "starter_code": "\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/" }
d183
train
class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if not height: return 0 result = 0 left = 0 right = len(height) - 1 while left < right: if height[left] <= height[right]: tmp = height[left] left += 1 while left < right and height[left] <= tmp: result += tmp - height[left] left += 1 else: tmp = height[right] right -= 1 while left < right and height[right] <= tmp: result += tmp - height[right] right -=1 return result
PYTHON
{ "starter_code": "\nclass Solution:\n def trap(self, height: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/trapping-rain-water/" }
d184
train
class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: # DP(a=index of last, b=index of last) = max of: # DP(a-1, b) # DP(a-1, i) + nums1[a] * max_or_min(nums2[i+1:b+1]) # same for b INF = int(1e9) n, m = len(nums1), len(nums2) DP = [-INF] * (m + 1) NDP = [-INF] * (m + 1) for a in range(n): for b in range(m): el = nums1[a] * nums2[b] diag = DP[b] NDP[b + 1] = max(el, DP[b + 1], NDP[b], diag, diag + el) DP, NDP = NDP, DP return DP[-1]
PYTHON
{ "starter_code": "\nclass Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/max-dot-product-of-two-subsequences/" }
d185
train
class Solution: def maxRepOpt1(self, text: str) -> int: letters = {} for i, char in enumerate(text): if char in letters: letters[char].append(i) else: letters[char] = [i] if len(letters) == 1: return len(text) ans = 0 for letter in letters: cur = 0 prev = 0 discarded = False maxSoFar = 0 arr = letters[letter] for j, pos in enumerate(arr): if not j: cur = 1 elif pos - arr[j-1] == 1: cur += 1 else: if not discarded and prev: discarded = True elif not discarded and pos - arr[j-1] > 2: discarded = True if prev + cur > maxSoFar: maxSoFar = prev+cur if pos - arr[j-1] == 2: prev = cur cur = 1 else: prev = 0 cur = 1 print((prev+cur)) if prev + cur > maxSoFar: maxSoFar = prev+cur if discarded: maxSoFar+=1 if maxSoFar > ans: ans = maxSoFar return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n ", "url": "https://leetcode.com/problems/swap-for-longest-repeated-character-substring/" }
d186
train
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: if len(s) < 2 ** k + k - 1: return False # Cannot be a string, as this is the de brujin length target = 2 ** k seen = set() cur_len = 0 for end in range(k, len(s) + 1): chunk = s[end - k: end] if chunk not in seen: cur_len += 1 seen.add(chunk) if cur_len == target: return True return False
PYTHON
{ "starter_code": "\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n ", "url": "https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/" }
d187
train
class Solution: def largestNumber(self, cost: List[int], target: int) -> str: dp = [0] + [-target]*target for t in range(1, target+1): dp[t] = max([dp[t-i] for i in cost if i<=t]+[dp[t]]) + 1 if dp[-1]<=0: return '0' res = '' for i in range(8, -1, -1): while target>=cost[i] and dp[target-cost[i]]==dp[target]-1: res += str(i+1) target -= cost[i] return res
PYTHON
{ "starter_code": "\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n ", "url": "https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/" }
d188
train
class Solution: def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int: if runningCost >= 4 * boardingCost: return -1 result = sum(customers) // 4 if (sum(customers) % 4) * boardingCost > runningCost: result += 1 for customer in customers: if customer <= 1: result += 1 else: break return result
PYTHON
{ "starter_code": "\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/" }
d189
train
class Solution: V1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] V2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] V3 = ["Thousand", "Million", "Billion"] def numberToWords(self, num): """ :type num: int :rtype: str """ if num == 0: return "Zero" answer = self.convert_hundred(num % 1000) for i in range(3): num //= 1000 if num % 1000 > 0: following = " " + answer if answer else "" answer = self.convert_hundred(num % 1000) + " " + self.V3[i] + following return answer def convert_hundred(self, num): answer = "" a = num // 100 b = num % 100 c = num % 10 if b < 20: answer = self.V1[b] else: following = " " + self.V1[c] if c > 0 else "" answer = self.V2[b // 10] + following if a > 0: following = " " + answer if answer else "" answer = self.V1[a] + " Hundred" + following return answer
PYTHON
{ "starter_code": "\nclass Solution:\n def numberToWords(self, num: int) -> str:\n ", "url": "https://leetcode.com/problems/integer-to-english-words/" }
d190
train
class Solution: def preferences_to_scores(self, preferences): scores = {} for u, up in enumerate(preferences): for s, v in enumerate(up): scores[(u, v)] = s return scores def unhappy_friends(self, scores, a, b): ret = set() for ai, aa in enumerate(a): af = a[1 - ai] for bi, bb in enumerate(b): bf = b[1 - bi] if scores[(aa, bb)] < scores[(aa, af)] and scores[(bb, aa)] < scores[(bb, bf)]: ret.add(aa) ret.add(bb) return ret def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: scores = self.preferences_to_scores(preferences) ret = set() for i, a in enumerate(pairs): for j in range(i): b = pairs[j] ret |= self.unhappy_friends(scores, a, b) return len(ret)
PYTHON
{ "starter_code": "\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n ", "url": "https://leetcode.com/problems/count-unhappy-friends/" }
d191
train
class Solution: def findLength(self, A, B): def check(length): seen = {A[i:i+length] for i in range(len(A) - length + 1)} return any(B[j:j+length] in seen for j in range(len(B) - length + 1)) A = ''.join(map(chr, A)) B = ''.join(map(chr, B)) lo, hi = 0, min(len(A), len(B)) + 1 while lo < hi: mi = int((lo + hi) / 2) if check(mi): lo = mi + 1 else: hi = mi return lo - 1
PYTHON
{ "starter_code": "\nclass Solution:\n def findLength(self, A: List[int], B: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-length-of-repeated-subarray/" }
d192
train
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: count = 0 length = 1 n_str = str(n) while length < len(n_str): count+= len(digits)**length length+=1 digits_sorted = sorted(digits) ## now length should equal to len(n), we compare the number with same length current_digit = 0 while current_digit < length: for digit in digits_sorted: next_round = False if digit < n_str[current_digit]: count+=len(digits)**(length-current_digit-1) elif digit > n_str[current_digit]: return count else: if current_digit == length-1: return count+1 else: current_digit+=1 next_round = True break if not next_round: return count return count
PYTHON
{ "starter_code": "\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n ", "url": "https://leetcode.com/problems/numbers-at-most-n-given-digit-set/" }
d193
train
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() i = 0 j = len(piles) - 1 max_coins = 0 for i in range(len(piles) // 3, len(piles), 2): max_coins += piles[i] return max_coins
PYTHON
{ "starter_code": "\nclass Solution:\n def maxCoins(self, piles: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-number-of-coins-you-can-get/" }
d194
train
from heapq import * from collections import Counter class Solution: def minSetSize(self, arr: List[int]) -> int: counter = Counter(arr) size = len(arr) # unique elements (remove half of them) if len(counter) == size: return (size - 1) // 2 + 1 max_heap = [(-freq, value) for value, freq in list(counter.items())] heapify(max_heap) removed = 0 # number of elements removed removed_size = 0 # size of the remvoved set while removed < size//2: count, value = heappop(max_heap) count = -count # change the count back to +ve removed += count removed_size += 1 return removed_size
PYTHON
{ "starter_code": "\nclass Solution:\n def minSetSize(self, arr: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/reduce-array-size-to-the-half/" }
d195
train
class Solution: def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ target,rem=divmod(sum(nums),k) if rem or max(nums)>target: return False n=len(nums) seen=[0]*n nums.sort(reverse=True) def dfs(k,index,current_sum): if k==1: return True if current_sum==target: return dfs(k-1,0,0) for i in range(index,n): if not seen[i] and current_sum+nums[i]<=target: seen[i]=1 if dfs(k,i+1,current_sum+nums[i]): return True seen[i]=0 return False return dfs(k,0,0)
PYTHON
{ "starter_code": "\nclass Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n ", "url": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets/" }
d196
train
class Solution: def countTriplets(self, A: List[int]) -> int: counters = [0] * (1 << 16) counters[0] = len(A) for num in A: mask = (~num) & ((1 << 16) - 1) sm = mask while sm != 0: counters[sm] += 1 sm = (sm - 1) & mask return sum(counters[num1 & num2] for num1 in A for num2 in A)
PYTHON
{ "starter_code": "\nclass Solution:\n def countTriplets(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/" }
d197
train
class Solution: def maxSubarraySumCircular(self, A: List[int]) -> int: N = len(A) if(N==0): return 0 curr_max = A[0] global_max = A[0] curr_min = A[0] global_min = A[0] flag = 0 if(A[0]>=0): flag=1 for i in range(1, N): if(A[i]>=0): flag=1 if(curr_max >= 0): curr_max = curr_max + A[i] else: curr_max = A[i] if(curr_min >= 0): curr_min = A[i] else: curr_min = curr_min + A[i] if(curr_max > global_max): global_max = curr_max if(curr_min < global_min): global_min = curr_min if(flag==0): return max(A) return max(global_max, sum(A) - global_min)
PYTHON
{ "starter_code": "\nclass Solution:\n def maxSubarraySumCircular(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-sum-circular-subarray/" }
d198
train
class Solution: def isValid(self, s: str) -> bool: if not s: return True return self.isValid(s.replace('abc', '')) if s.replace('abc', '') != s else False
PYTHON
{ "starter_code": "\nclass Solution:\n def isValid(self, s: str) -> bool:\n ", "url": "https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/" }
d199
train
class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: dist = [ abs( ord(s[i]) - ord(t[i]) ) for i in range(len(s))] # i = 0 # cur = 0 # res = 0 # for j in range(len(s)): # cur += dist[j] # while cur>maxCost: # cur -= dist[i] # i += 1 # res = max(res, j-i+1) # return res i = 0 cost = maxCost for j in range(len(s)): cost -= dist[j] if cost < 0: cost += dist[i] i += 1 return j-i+1
PYTHON
{ "starter_code": "\nclass Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n ", "url": "https://leetcode.com/problems/get-equal-substrings-within-budget/" }
d200
train
class Solution: def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ longest_streak = 0 num_set = set(nums) for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak
PYTHON
{ "starter_code": "\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/longest-consecutive-sequence/" }