_id
stringlengths
2
5
partition
stringclasses
2 values
text
stringlengths
5
289k
language
stringclasses
1 value
meta_information
dict
title
stringclasses
1 value
d201
train
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib = [1, 1] # initializing a Fibonacci table with F[0] and F[1] i = 1 # index that will represent the last filled index of table temp = fib[0] + fib[1] # initial value of values to be appended while temp < k: # we keep filling table until temp >= k fib.append(temp) # add the current value to the table i += 1 # increase i by 1 to keep track of the last filled index temp = fib[i] + fib[i-1] # calculate new temp fib.append(temp) # to cover case temp == k, we append the last value >= k ans = 0 # initializing answer value with 0 j = -1 # placeholder to represent last checked Fibonacci table index while k > 0: # keep repeating until k <= 0 temp = fib[j] # get the biggest number available j -= 1 # decrease j by 1 since we tried the last number if temp <= k: ans+=1 k-=temp return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def findMinFibonacciNumbers(self, k: int) -> int:\n ", "url": "https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/" }
d202
train
class Solution: hash = {} def numTrees(self, n): """ :type n: int :rtype: int """ # return base case if n == 0: return 1 if n == 1 or n == 2: return n # try fetching from hash try: return self.hash[n] except KeyError: pass # holds the sum resSum = 0 # iterate i from 1 to n-1 # should add up (0,4), (1,3), (2,2), (3,1), (4,0) for i in range(n): #print(i,n - (i+1)) tempSum = self.numTrees(i) * self.numTrees(n - (i+1)) #print(tempSum) resSum += tempSum # append to hash self.hash[n]=resSum return resSum
PYTHON
{ "starter_code": "\nclass Solution:\n def numTrees(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/unique-binary-search-trees/" }
d203
train
class Solution: def longestMountain(self, A: List[int]) -> int: up=0 down=0 ans=0 for i in range(0,len(A)-1): if A[i]<A[i+1]: if down==0: up+=1 else: up=1 down=0 elif A[i]>A[i+1]: if up>0: down+=1 mountain=up+down+1 if ans<mountain: ans=mountain else: up=0 down=0 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def longestMountain(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/longest-mountain-in-array/" }
d204
train
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ def f(n): ret = 1 for i in range(1, n+1): ret *= i return ret return f(m+n-2)//(f(m-1)*f(n-1))
PYTHON
{ "starter_code": "\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n ", "url": "https://leetcode.com/problems/unique-paths/" }
d205
train
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # left = 0 # right = len(nums) - 1 # while left <= right: # mid = int((left + right)/2) # if nums[mid] == target: # return mid # elif (nums[right] < target) or (nums[mid] > target and nums[right] > target): # right = mid - 1 # else: # left = mid + 1 # return -1 left = 0 right = len(nums) - 1 while left <= right: mid = int((left + right)/2) if nums[mid] == target: return mid if (nums[left] < nums[mid]): if (target < nums[left]) or (target > nums[mid]): left = mid + 1 else: right = mid - 1 elif (nums[left] > nums[mid]): if (target < nums[mid]) or (target >= nums[left]): right = mid - 1 else: left = mid + 1 else: if nums[right] == target: return right else: return -1 return -1
PYTHON
{ "starter_code": "\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n ", "url": "https://leetcode.com/problems/search-in-rotated-sorted-array/" }
d206
train
class Solution: def getMax(self, arr, m, n): res = 0 for e in arr: if m >= e[0] and n >= e[1]: res += 1 m -= e[0] n -= e[1] return res def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ arr = [(s.count('0'), s.count('1')) for s in strs] arr1 = sorted(arr, key=lambda s: -min(m - s[0], n - s[1])) arr2 = sorted(arr, key=lambda s: min(s[0], s[1])) res = max(self.getMax(arr1, m, n), self.getMax(arr2, m, n)) return res
PYTHON
{ "starter_code": "\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n ", "url": "https://leetcode.com/problems/ones-and-zeroes/" }
d207
train
class Solution: def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums: return True n = len(nums) if n & 1 == 0: return True dp = [0] * n for i in range(n-1, -1, -1): for j in range(i, n): if i == j: dp[i] = nums[i] else: dp[j] = max(nums[i] - dp[j], nums[j] - dp[j-1]) return dp[n-1] >= 0
PYTHON
{ "starter_code": "\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/predict-the-winner/" }
d208
train
class Solution: def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ nums = [str(n) for n in nums] nums.sort(reverse=True) for i in range(1, len(nums)): if len(nums[i-1]) > len(nums[i]): ran = len(nums[i]) j = i while j-1 >= 0 and nums[j-1][:ran] == nums[j] and nums[j-1]+nums[j]<=nums[j]+nums[j-1]: nums[j-1], nums[j] = nums[j], nums[j-1] j -= 1 return str(int(''.join(nums)))
PYTHON
{ "starter_code": "\nclass Solution:\n def largestNumber(self, nums: List[int]) -> str:\n ", "url": "https://leetcode.com/problems/largest-number/" }
d209
train
class Solution: def predictPartyVictory(self, senate): """ :type senate: str :rtype: str """ num = 0 # num of Reeding R while ('R' in senate and 'D' in senate): res = [] for i in senate: if i=='R': if num>=0: res.append(i) num+=1 else: if num<=0: res.append(i) num-=1 senate = res return 'Radiant' if 'R' in senate else 'Dire'
PYTHON
{ "starter_code": "\nclass Solution:\n def predictPartyVictory(self, senate: str) -> str:\n ", "url": "https://leetcode.com/problems/dota2-senate/" }
d210
train
class Solution: def mergeStones(self, stones: List[int], K: int) -> int: n = len(stones) if (n - 1) % (K - 1) != 0: return -1 prefix = [0] for s in stones: prefix.append(prefix[-1] + s) @lru_cache(None) def dp(i, j): if j - i + 1 < K: return 0 res = 0 if (j - i) % (K - 1) == 0: res = prefix[j+1] - prefix[i] return res + min(dp(i, mid) + dp(mid+1, j) for mid in range(i, j, K - 1)) return dp(0, n - 1)
PYTHON
{ "starter_code": "\nclass Solution:\n def mergeStones(self, stones: List[int], K: int) -> int:\n ", "url": "https://leetcode.com/problems/minimum-cost-to-merge-stones/" }
d211
train
class Solution: def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if len(nums) < 2 or k <= 0 or t < 0: return False if t == 0: visited = set() for i, n in enumerate(nums): if n in visited: return True visited.add(n) if i >= k: visited.remove(nums[i-k]) return False bucket = {} for i, n in enumerate(nums): b = n // t if b in bucket: return True if b+1 in bucket and abs(bucket[b+1]-n) <= t: return True if b-1 in bucket and abs(bucket[b-1]-n) <= t: return True bucket[b] = n if i >= k: del bucket[nums[i-k]//t] return False
PYTHON
{ "starter_code": "\nclass Solution:\n def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:\n ", "url": "https://leetcode.com/problems/contains-duplicate-iii/" }
d212
train
class Solution: def maxUniqueSplit(self, s: str) -> int: self.x, n = 0, len(s) def maxUniqueSplit_(i=0, S=set()): if s[i:] not in S: self.x = max(self.x, len(S) + 1) for j in range(i + 1, n): if s[i : j] not in S and len(S) + 1 + n - j > self.x: maxUniqueSplit_(j, S.union({s[i : j]})) maxUniqueSplit_() return self.x
PYTHON
{ "starter_code": "\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/" }
d213
train
class Solution: def numFactoredBinaryTrees(self, A: List[int]) -> int: mod = 10**9 + 7 nums_set = set(A) nums = A.copy() nums.sort() counts = {} total = 0 for n in nums: n_count = 1 for d in nums: if d * d > n: break if n % d != 0: continue e = n // d if e not in nums_set: continue subtrees = (counts[d] * counts[e]) % mod if d != e: subtrees = (subtrees * 2) % mod n_count = (n_count + subtrees) % mod counts[n] = n_count % mod total = (total + n_count) % mod return total
PYTHON
{ "starter_code": "\nclass Solution:\n def numFactoredBinaryTrees(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/binary-trees-with-factors/" }
d214
train
class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if abs(n) == 1: if n == 1: return x else: return 1/x if n > 0: a, b = int(n//2), n%2 else: a, b = -int(-n//2), -(n%2) y = self.myPow(x, a) z = self.myPow(x, b) return y*y*z
PYTHON
{ "starter_code": "\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n ", "url": "https://leetcode.com/problems/powx-n/" }
d215
train
class Solution: def movesToMakeZigzag(self, nums): n = len(nums) res0 = 0 for i in range(0, n, 2): nei = min(nums[j] for j in [i - 1, i + 1] if 0 <= j <= n-1) if nums[i] >= nei: res0 += nums[i] - nei + 1 res1 = 0 for i in range(1, n, 2): nei = min(nums[j] for j in [i - 1, i + 1] if 0 <= j <= n-1) if nums[i] >= nei: res1 += nums[i] - nei + 1 return min(res0, res1)
PYTHON
{ "starter_code": "\nclass Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/" }
d216
train
class Solution: def isGoodArray(self, nums: List[int]) -> bool: n = nums[0] for i in nums: n = gcd(i,n) if n==1: return True return False
PYTHON
{ "starter_code": "\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/check-if-it-is-a-good-array/" }
d217
train
class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: # valid string? can be seperated into full croaks: ### dict of letters. c, r, o, a, k should all be equal, nothing else in if len(croakOfFrogs)%5!=0 or croakOfFrogs[0]!='c' or croakOfFrogs[-1]!='k': return -1 letters = { 'c': 0, 'r': 0, 'o': 0, 'a': 0, 'k': 0 } frogs = 0 temp = 0 for l in croakOfFrogs: letters[l] += 1 temp = letters['c'] - letters['k'] if temp > frogs: frogs = temp c_count = letters['c'] for letter in letters: if letters[letter] != c_count: return -1 return frogs
PYTHON
{ "starter_code": "\nclass Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n ", "url": "https://leetcode.com/problems/minimum-number-of-frogs-croaking/" }
d218
train
class Solution: def subarrayBitwiseORs(self, A: List[int]) -> int: res = set() cur = set() for a in A: cur = {a | i for i in cur} cur |= {a} res |= cur return len(res)
PYTHON
{ "starter_code": "\nclass Solution:\n def subarrayBitwiseORs(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/bitwise-ors-of-subarrays/" }
d219
train
class Solution: def orderlyQueue(self, S: str, K: int) -> str: if K >= 2: return ''.join(sorted(S)) length = len(S) S = S + S i, j, k = 0, 1, 0 while j + k < len(S) and k < length: if S[i + k] == S[j + k]: k += 1 continue elif S[i + k] < S[j + k]: j = j + k + 1 else: i = max(i + k + 1, j) j = i + 1 k = 0 return S[i : i + length]
PYTHON
{ "starter_code": "\nclass Solution:\n def orderlyQueue(self, S: str, K: int) -> str:\n ", "url": "https://leetcode.com/problems/orderly-queue/" }
d220
train
class Solution: def longestWPI(self, hours: List[int]) -> int: ans, count, seen = 0, 0, {} for i, hour in enumerate(hours): count = count + 1 if hour > 8 else count - 1 if count > 0: ans = i + 1 else: if count not in seen: seen[count] = i if count - 1 in seen: ans = max(ans, i - seen[count - 1]) return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/longest-well-performing-interval/" }
d221
train
class Solution: def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: # feel like its sliding window max window, max_window = 0, 0 # init first window for i in range(X): if grumpy[i]: window += customers[i] max_window = window # Sliding Window for i in range(X,len(grumpy)): if grumpy[i-X]: window -= customers[i-X] if grumpy[i]: window += customers[i] if window > max_window: max_window = window # sum = 0 for i in range(len(grumpy)): if grumpy[i] == 0: sum += customers[i] return sum + max_window
PYTHON
{ "starter_code": "\nclass Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:\n ", "url": "https://leetcode.com/problems/grumpy-bookstore-owner/" }
d222
train
class Solution: def longestDupSubstring(self, S): nums, N = [ord(c) - ord('a') for c in S], len(S) BASE, MOD = 26, 2**32 def check(L): cur_hash, seen = 0, set() for val in nums[:L]: cur_hash = (cur_hash * BASE + val) % MOD seen.add(cur_hash) X = pow(BASE, L-1, MOD) for idx, val in enumerate(nums[L:]): cur_hash -= nums[idx] * X cur_hash = (cur_hash * BASE + val) % MOD if cur_hash in seen: return idx + 1 seen.add(cur_hash) return -1 low, high = 1, N + 1 start = 0 while low < high: mid = (low + high)//2 idx = check(mid) if idx != -1: low = mid + 1 start = idx else: high = mid return S[start: start + low - 1]
PYTHON
{ "starter_code": "\nclass Solution:\n def longestDupSubstring(self, S: str) -> str:\n ", "url": "https://leetcode.com/problems/longest-duplicate-substring/" }
d223
train
class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int: def getFS(x1, x2): F = [x1, x2] while F[-1] <= 1000000000: F.append(F[-2] + F[-1]) return F C1 = getFS(1, 0) C2 = C1[1:] def getLLFS(x1, x2): max_len = 2 F = [x1, x2] xi = x1 + x2 while xi in setA: max_len += 1 F.append(xi) xi = F[-2] + F[-1] if max_len == 6: print(F) return max_len max_len = 2 setA = set(A) for i in range(len(A)): for j in range(i+1, len(A)): x1, x2 = A[i], A[j] # calculate X_{max_len+1} if x1 * C1[max_len] + x2 * C2[max_len] > A[-1]: break max_len = max(max_len, getLLFS(x1, x2)) if max_len < 3: return 0 return max_len
PYTHON
{ "starter_code": "\nclass Solution:\n def lenLongestFibSubseq(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/" }
d224
train
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) l = 0 r = n-1 while l <= r: m = (l + r) // 2 if m == 0 and citations[m] >= n - m or citations[m-1] < n - (m-1) and citations[m] >= n-m: return n-m if citations[m] < n - m: l = m+1 else: r = m return 0
PYTHON
{ "starter_code": "\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/h-index-ii/" }
d225
train
class Solution: def numDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ setOft=set(t) news="" for ch in s: if ch in setOft: news+=ch dp=[[1 for i in range(len(news)+1)] for j in range(len(t)+1)] for j in range(1,len(t)+1): dp[j][0]=0 for i in range(len(t)): for j in range(len(news)): if t[i]==news[j]: dp[i+1][j+1]=dp[i][j]+dp[i+1][j] else: dp[i+1][j+1]=dp[i+1][j] return dp[len(t)][len(news)]
PYTHON
{ "starter_code": "\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n ", "url": "https://leetcode.com/problems/distinct-subsequences/" }
d226
train
INF = float('inf') class Solution: def pushDominoes(self, dominoes: str) -> str: n = len(dominoes) d1 = [-1] * n d2 = [-1] * n cnt = INF for i in range(n - 1, -1, -1): if dominoes[i] == 'L': cnt = 0 elif dominoes[i] == '.': cnt += 1 elif dominoes[i] == 'R': cnt = INF d1[i] = cnt cnt = INF for i in range(n): if dominoes[i] == 'R': cnt = 0 elif dominoes[i] == '.': cnt += 1 elif dominoes[i] == 'L': cnt = INF d2[i] = cnt ret = [] for i in range(n): if d1[i] == d2[i]: ret.append('.') elif d1[i] < d2[i]: ret.append('L') else: ret.append('R') return ''.join(ret)
PYTHON
{ "starter_code": "\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n ", "url": "https://leetcode.com/problems/push-dominoes/" }
d227
train
class Solution: def numSquarefulPerms(self, A: List[int]) -> int: A.sort() self.ans = 0 def check(A, i, path): return int((A[i] + path[-1])**0.5 + 0.0)**2 == A[i] + path[-1] def dfs(A, path): if not A: self.ans += 1 return for i in range(len(A)): if i > 0 and A[i] == A[i - 1]: continue if not path or (path and check(A, i, path)): dfs(A[:i] + A[i + 1:], path + [A[i]]) dfs(A, []) return self.ans
PYTHON
{ "starter_code": "\nclass Solution:\n def numSquarefulPerms(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/number-of-squareful-arrays/" }
d228
train
class Solution: def longestOnes(self, A: List[int], K: int) -> int: hulu = [] cnt = 0 num = A[0] for x in A: if x == num: cnt += 1 else: hulu.append([num,cnt]) cnt = 1 num = x if cnt>0: hulu.append([num,cnt]) # print(hulu) output = 0 if A[0] == 1: start = 0 else: start = 1 if len(hulu)<2: return min(K,len(A)) end = start usage = 0 ones = hulu[start][1] while end+2<len(hulu) and usage+hulu[end+1][1]<=K: usage += hulu[end+1][1] ones += hulu[end+2][1] end += 2 output = ones+K # print([start,end,usage,ones]) start += 2 while start<len(hulu): ones -= hulu[start-2][1] usage -= hulu[start-1][1] if start>end: end = start ones = hulu[start][1] usage = 0 while end+2<len(hulu) and usage+hulu[end+1][1]<=K: usage += hulu[end+1][1] ones += hulu[end+2][1] end += 2 # print([start,end,usage,ones]) output = max(output,ones+K) start += 2 return min(output,len(A))
PYTHON
{ "starter_code": "\nclass Solution:\n def longestOnes(self, A: List[int], K: int) -> int:\n ", "url": "https://leetcode.com/problems/max-consecutive-ones-iii/" }
d229
train
class Solution: def maxVowels(self, s: str, k: int) -> int: n = len(s) vowel = set(['a','e','i','o','u']) i=0 res = 0 while i<k: if s[i] in vowel: res+=1 i+=1 j=k i=0 maxV = res while j<n: if s[i] in vowel: res-=1 if s[j] in vowel: res+=1 i+=1 j+=1 if maxV<res: maxV = res return maxV
PYTHON
{ "starter_code": "\nclass Solution:\n def maxVowels(self, s: str, k: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/" }
d230
train
class Solution: def canReorderDoubled(self, A: List[int]) -> bool: cache=Counter(A) c_list=sorted(list(cache),key=abs) for x in c_list: if cache[x]>cache[2*x]: return False cache[2*x]-=cache[x] return True
PYTHON
{ "starter_code": "\nclass Solution:\n def canReorderDoubled(self, A: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/array-of-doubled-pairs/" }
d231
train
class Solution: def removeKdigits(self, num, k): """ :type num: str :type k: int :rtype: str """ out=[] for digit in num: while k and out and out[-1] > digit: out.pop() k-=1 out.append(digit) return ''.join(out[:-k or None]).lstrip('0') or "0"
PYTHON
{ "starter_code": "\nclass Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n ", "url": "https://leetcode.com/problems/remove-k-digits/" }
d232
train
class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ nums = sorted(set(nums), key=lambda x: x) result = 0 for i in range(len(nums)): if nums[i] <= 0: continue elif nums[i] == result + 1: result += 1 else: break return result + 1
PYTHON
{ "starter_code": "\nclass Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/first-missing-positive/" }
d233
train
class Solution: def findPoisonedDuration(self, timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ if not timeSeries: return 0 prev = timeSeries[0] ret = 0 count = 0 for t in timeSeries[1:]: diff = t - prev if diff > duration: count += 1 else: ret += diff prev = t; ret += (count+1)*duration return ret
PYTHON
{ "starter_code": "\nclass Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n ", "url": "https://leetcode.com/problems/teemo-attacking/" }
d234
train
from itertools import chain class Solution: def regionsBySlashes(self, grid): grid = self.convert_grid(grid) print(*(list(map(str, x)) for x in grid), sep='\ ') return len([self.destroy_island(x, y, grid) for y in range(len(grid)) for x,v in enumerate(grid[y]) if v == 0]) @staticmethod def convert_grid(grid): new_grid = [[0] * len(grid[0]) * 2 for _ in range(len(grid) * 2)] for (x, y, v) in ((x, y, v) for y in range(len(grid)) for x,v in enumerate(grid[y]) if v in '\\\\/'): new_grid[y * 2 + 0][x * 2 + (1 if v == '/' else 0)] = v new_grid[y * 2 + 1][x * 2 + (0 if v == '/' else 1)] = v return new_grid def destroy_island(self, x, y, grid): grid[y][x] = 1 for c in Solution.search(x, y, grid): self.destroy_island(c[0], c[1], grid) @staticmethod def search(x, y, grid): in_bounds = lambda c:0 <= c[1] < len(grid) and 0 <= c[0] < len(grid[c[1]]) check_orthog = lambda c:in_bounds(c) and grid[c[1]][c[0]] == 0 def check_diag(c): if not in_bounds(c) or grid[c[1]][c[0]] != 0: return False d_x, d_y = c[0] - x, c[1] - y sep = '\\\\' if ((d_x > 0 > d_y) or (d_x < 0 < d_y)) else '/' return not (grid[y + d_y][x] == sep and grid[y][x + d_x] == sep) yield from chain(filter(check_orthog, ((x-1, y), (x+1, y), (x, y-1), (x, y+1))), filter(check_diag, ((x + 1, y + 1), (x + 1, y - 1), (x - 1, y + 1), (x - 1, y - 1))))
PYTHON
{ "starter_code": "\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n ", "url": "https://leetcode.com/problems/regions-cut-by-slashes/" }
d235
train
class Solution: def minAddToMakeValid(self, S: str) -> int: if not S: return 0 stack = [] add = 0 for c in S: if c == '(': stack.append(c) elif c == ')': if stack: stack.pop() else: add += 1 add += len(stack) return add
PYTHON
{ "starter_code": "\nclass Solution:\n def minAddToMakeValid(self, S: str) -> int:\n ", "url": "https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/" }
d236
train
class Solution: def numberOfArithmeticSlices(self, A): curr, sum = 0, 0 for i in range(2,len(A)): if A[i]-A[i-1] == A[i-1]-A[i-2]: curr += 1 sum += curr else: curr = 0 return sum # solution = 0 # connected = 1 # old_diff = None # sequences = [] # if len(A) < 3: # return 0 # for index,num in enumerate(A): # if index < len(A) - 1: # new_diff = num - A[index + 1] # else: # new_diff = A[index - 1] - num # if old_diff == new_diff: # if index == len(A) - 1 and connected >= 3: # connected += 1 # sequences.append(connected) # connected += 1 # else: # old_diff = new_diff # if connected > 2: # sequences.append(connected) # connected = 1 # for sequence in sequences: # prev = 0 # while sequence >= 2: # prev += 1 # solution += prev # sequence -= 1 # return solution
PYTHON
{ "starter_code": "\nclass Solution:\n def numberOfArithmeticSlices(self, A: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/arithmetic-slices/" }
d237
train
class Solution: def minFlipsMonoIncr(self, S: str) -> int: onesSoFar = 0 partial = 0 for n in S: if n == '0': partial = min(onesSoFar, partial+1) else: onesSoFar += 1 return partial
PYTHON
{ "starter_code": "\nclass Solution:\n def minFlipsMonoIncr(self, S: str) -> int:\n ", "url": "https://leetcode.com/problems/flip-string-to-monotone-increasing/" }
d238
train
class Solution: def numSubarraysWithSum(self, pl, S): ans = 0 if(S == 0): c = 0 for i in range(len(pl)): if(pl[i] == 0): c+=1 else: c = 0 ans +=c return ans; l = [-1] for i in range(len(pl)): if(pl[i] == 1 ): l.append(i) l.append(len(pl)) ans = 0 for i in range(1,len(l)-S): ans += (l[i]-l[i-1])*(l[i+S] - l[i+S-1]) return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def numSubarraysWithSum(self, A: List[int], S: int) -> int:\n ", "url": "https://leetcode.com/problems/binary-subarrays-with-sum/" }
d239
train
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ tmax_profit = 0 rmax_profits = [0] * len(prices) rmax = -1 for ii in range(len(prices)-2, -1, -1): if (prices[rmax] - prices[ii] > rmax_profits[ii+1]): rmax_profits[ii] = prices[rmax] - prices[ii] else: rmax_profits[ii] = rmax_profits[ii+1] if prices[ii] > prices[rmax]: rmax = ii #print("rmax profit = {}".format(rmax_profits)) lmin = 0 lmax_profit = 0 for ii in range(1, len(prices)): profit = prices[ii]-prices[lmin] if profit > lmax_profit: lmax_profit = profit if prices[ii] < prices[lmin]: lmin = ii tprofit = lmax_profit if ii < len(prices)-1: tprofit += rmax_profits[ii+1] #print("ii = {}, rmax_profit = {}, lmax_profit = {}, tprofit = {}".format(ii, rmax_profits[ii], lmax_profit, tprofit)) if tprofit > tmax_profit: tmax_profit = tprofit return tmax_profit if tmax_profit>0 else 0
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-iii/" }
d240
train
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: # my solution ... 128 ms ... 99 % ... 17.9 MB ... 85 % # time: O(nlogn) # space: O(n) l2v = collections.defaultdict(list) for v,l in zip(values, labels): l2v[l].append(v) pool = [] for l in l2v: pool += sorted(l2v[l])[-use_limit:] return sum(sorted(pool)[-num_wanted:])
PYTHON
{ "starter_code": "\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n ", "url": "https://leetcode.com/problems/largest-values-from-labels/" }
d241
train
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ counter = collections.Counter(s) colls = sorted(counter.items(), key=lambda k: k[1], reverse=True) res = '' for k, v in colls: res += k * v return res
PYTHON
{ "starter_code": "\nclass Solution:\n def frequencySort(self, s: str) -> str:\n ", "url": "https://leetcode.com/problems/sort-characters-by-frequency/" }
d242
train
class Solution: def move(self, pos, direction): x, y = pos if direction == 0: y += 1 elif direction == 1: x += 1 elif direction == 2: y -= 1 elif direction == 3: x -= 1 return (x, y) def isRobotBounded(self, instructions: str) -> bool: direction = 0 # 0 for north, 1 for east, 2 for south, 3 for west pos = (0, 0) for i in instructions: if i == 'G': pos = self.move(pos, direction) elif i == 'L': direction = (direction - 1) % 4 elif i == 'R': direction = (direction + 1) % 4 if pos == (0, 0) or direction != 0: return True else: return False
PYTHON
{ "starter_code": "\nclass Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n ", "url": "https://leetcode.com/problems/robot-bounded-in-circle/" }
d243
train
class Solution: def isvalid(self,C): if len(C)>2: return False if len(C)==1: a = min(C) if a==1 or C[a]==1: # EXPLANATION: # a==1 : All lengths are unitary like A=[1,2,3,4,...], so poping anything is fine # C[a]==1: We have a unique length occurence like A=[4,4,4,4,...], so poping anything is fine too return True # EXPLANATION: # For all other cases of len(C)==1, we'd end with a mistmatch like [1,1,2,2,2], or [1,1,1], so we need to \"return False\" right away return False # # --------- len(D)==2 -------------- # a,b = sorted(C) # -> Attempt removing from \"a\" if a==C[a]==1: # EXPLANATION: # If we remove from a chain of length \"a\", we will create something smaller than \"b\", so... # The only way to be fine is to have a single element, like [1,2,2,2,3,3,3,...] # -> If we had anything else, we would be stuck with a contradiction (so we move forward to removing \"b\") return True # -> Attempt removing from \"b\" # EXPLANATION: # This only works if there is a single chain of length \"b\", and poping one element makes a chain of length \"a\". # In other words, if works when \"C[b]==1 and (b-1)==a\" return True if ( C[b]==1 and (b-1)==a ) else False def remove(self,B,x): if B[x]==1: B.pop(x) else: B[x] -= 1 def maxEqualFreq(self, A): remove = self.remove B = Counter(A) # Count number of repetitions/length (per value) [1,1,2,2,3,3,4] = {1:2, 2:2, 3:2, 4:1} C = Counter(B.values()) # Count number of times a length has been seen [1,1,2,2,3,3,4] = { 1:1, 2:3 } # # -> Iterate Reversed, to get best answer at the first match for i in reversed(range(len(A))): # -> Check if C_dictionary is a valid answer if self.isvalid(C): return i+1 # # -> Remove current element \"x\" from our System x = A[i] # B[x] = N_repetitions for \"x\" # remove(C,B[x]) # Deregister old N_repetitions remove(B, x ) # Deregister one instance of \"x\" (from N_repetitions) if B[x]: # -> If N_repetitions>0 exists, register shortened length C[B[x]] += 1 return 0
PYTHON
{ "starter_code": "\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-equal-frequency/" }
d244
train
class Solution: def flipgame(self, fronts: List[int], backs: List[int]) -> int: w = set(fronts[i] for i in range(len(fronts)) if fronts[i] == backs[i]) x = set() for a in fronts: if a not in w: x.add(a) for a in backs: if a not in w: x.add(a) if not x: return 0 return min(x)
PYTHON
{ "starter_code": "\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/card-flipping-game/" }
d245
train
class Solution: def numSteps(self, s: str) -> int: i, mid_zero = 0 , 0 for j in range(1, len(s)): if s[j] == '1': mid_zero += j -i - 1 i = j if i == 0: return len(s)-1 return mid_zero + 1 + len(s)
PYTHON
{ "starter_code": "\nclass Solution:\n def numSteps(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/" }
d246
train
class Solution: def optimalDivision(self, nums): """ :type nums: List[int] :rtype: str """ if(len(nums) == 0): return '' if(len(nums) == 1): return str(nums[0]) if(len(nums) == 2): return str(nums[0]) + '/' + str(nums[1]) res = str(nums[0]) + '/' + '(' for i in range(1,len(nums)-1): res += str(nums[i]) res += '/' res += str(nums[-1]) res += ')' return res
PYTHON
{ "starter_code": "\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n ", "url": "https://leetcode.com/problems/optimal-division/" }
d247
train
class Solution: def replaceWords(self, dt, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ trie = {} for w in dt: t = trie for c in w: if c not in t: t[c] = {} t = t[c] t['#'] = w # result = [] # for word in sentence.split(): # result.append(self.replace(word, trie)) # return " ".joinresult # OR return " ".join([ self.replace(i, trie) for i in sentence.split() ]) def replace( self, word, trie ): cur = trie for letter in word: if letter not in cur: break cur = cur[letter] if "#" in cur: return cur['#'] return word setenceAsList = sentence.split(" ") for i in range(len(setenceAsList)): for j in dt: if setenceAsList[i].startswith(j): setenceAsList[i] = j return " ".join(setenceAsList) arrs = sentence.split() for i in range(len(arrs)): w = arrs[i] for j in range(len(arrs[i])): cur = w[:j] if cur in dt: arrs[i] = cur break return ' '.join(arrs)
PYTHON
{ "starter_code": "\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n ", "url": "https://leetcode.com/problems/replace-words/" }
d248
train
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: i, window, result = 0, 0, float('inf') premin = [float('inf')]*len(arr) for j, num in enumerate(arr): window += num while window > target: window -= arr[i] i+=1 if window == target: curr = j - i + 1 result = min(result, curr + premin[i-1]) premin[j] = min(curr, premin[j-1]) else: premin[j] = premin[j-1] return result if result < float('inf') else -1 # class Solution: # def minSumOfLengths(self, arr: List[int], target: int) -> int: # i, window, result = 0, 0, float('inf') # premin = [float('inf')] * len(arr) # for j, num in enumerate(arr): # window += num # while window > target: # window -= arr[i] # i += 1 # if window == target: # curr = j - i + 1 # result = min(result, curr + premin[i - 1]) # premin[j] = min(curr, premin[j - 1]) # else: # premin[j] = premin[j - 1] # return result if result < float('inf') else -1
PYTHON
{ "starter_code": "\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n ", "url": "https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/" }
d249
train
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n = len(grid) m = len(grid[0]) F = [i for i in range(m * n)] def find(x): if x == F[x]: return x else: F[x] = find(F[x]) return F[x] for i in range(n): for j in range(m): if i > 0 and grid[i-1][j] == grid[i][j]: f1 = find((i-1)*m+j) f2 = find((i)*m+j) if f1 == f2: return True F[f1] = f2 if j > 0 and grid[i][j-1] == grid[i][j]: f1 = find((i)*m+j-1) f2 = find((i)*m+j) if f1 == f2: return True F[f1] = f2 return False
PYTHON
{ "starter_code": "\nclass Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n ", "url": "https://leetcode.com/problems/detect-cycles-in-2d-grid/" }
d250
train
class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: # slide window and call isMagicSquare if len(grid) < 3 or len(grid[0]) < 3: return 0 rows = len(grid) cols = len(grid[0]) magic_squares = 0 for i in range(rows - 2): for j in range(cols - 2): window = [tmp[j:j + 3] for tmp in grid[i: i + 3]] if self.isMagicSquare(window): magic_squares += 1 return magic_squares def isMagicSquare(self, square: List[List[int]]) -> bool: target = square[0][0] + square[0][1] + square[0][2] seen = {} print(square) # check rows for row in square: tmp = 0 for i in row: tmp += i if i in seen or i > 9 or i < 1: return False else: seen[i] = 1 if tmp != target: return False # check cols for i in range(3): tmp = 0 for row in square: tmp += row[i] if tmp != target: return False # check left to right diag tmp = 0 for i in range(3): tmp += square[i][i] if tmp != target: return False # check right to left diag tmp = 0 for i in range(3): tmp += square[i][2 - i] if tmp != target: return False return True
PYTHON
{ "starter_code": "\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n ", "url": "https://leetcode.com/problems/magic-squares-in-grid/" }
d251
train
from typing import * from heapq import heappop, heappush class Solution: def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float: N = len(quality) heap_quality = [] workers = [i for i in range(N)] workers = sorted(workers, key=lambda x: wage[x] / quality[x]) sum_quality = 0 for i in range(K): heappush(heap_quality, -quality[workers[i]]) sum_quality += quality[workers[i]] ans = sum_quality * (wage[workers[K - 1]] / quality[workers[K - 1]]) for i in range(K, N): heappush(heap_quality, -quality[workers[i]]) sum_quality += quality[workers[i]] sum_quality += heappop(heap_quality) # negative quality value ans = min(ans, sum_quality * (wage[workers[i]] / quality[workers[i]])) return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:\n ", "url": "https://leetcode.com/problems/minimum-cost-to-hire-k-workers/" }
d252
train
class Solution: def clumsy(self, N: int) -> int: if N <= 2: return N if N <= 4: return N + 3 if (N - 4) % 4 == 0: return N + 1 elif (N - 4) % 4 <= 2: return N + 2 else: return N - 1
PYTHON
{ "starter_code": "\nclass Solution:\n def clumsy(self, N: int) -> int:\n ", "url": "https://leetcode.com/problems/clumsy-factorial/" }
d253
train
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: for i,r in enumerate(ranges): l = max(0,i-r) ranges[l] = max(i+r, ranges[l]) res = lo = hi = 0 while hi < n: lo, hi = hi, max(ranges[lo:hi+1]) if hi == lo: return -1 res += 1 return res
PYTHON
{ "starter_code": "\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/" }
d254
train
class Solution: def findMinMoves(self, machines): """ :type machines: List[int] :rtype: int """ if sum(machines) % len(machines) != 0: return -1 mean = sum(machines) // len(machines) cum, step = 0, 0 for x in machines: cum += x - mean step = max(step, abs(cum), x-mean) return step
PYTHON
{ "starter_code": "\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/super-washing-machines/" }
d255
train
class Solution: def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ ls = [1,10,91] mul = 9 res = 0 for i in range(8): mul = 9 m = 9 for j in range(i+2): mul *= m m -= 1 #print(mul) ls.append(mul +ls[-1]) if n >=9: return ls[9] else: return ls[n]
PYTHON
{ "starter_code": "\nclass Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/count-numbers-with-unique-digits/" }
d256
train
class Solution: def jump(self,nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return 0 else: step = 0 pos = 0 while pos != len(nums) - 1: bestStep = -1 bestValue = -1 for i in range(nums[pos], 0, -1): if len(nums) - 1 == pos + i: bestStep = i break if (pos + i < len(nums) and nums[pos + i] != 0 and nums[pos + i] + i > bestValue): bestStep = i bestValue = nums[pos + i] + i print(bestStep) pos += bestStep step += 1 return step
PYTHON
{ "starter_code": "\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/jump-game-ii/" }
d257
train
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: bananas = sum(piles) K = bananas // H + (bananas % H != 0) while True: hours_needed = 0 for pile in piles: hours_needed += pile // K if pile % K != 0: hours_needed += 1 if hours_needed <= H: return K K += 1
PYTHON
{ "starter_code": "\nclass Solution:\n def minEatingSpeed(self, piles: List[int], H: int) -> int:\n ", "url": "https://leetcode.com/problems/koko-eating-bananas/" }
d258
train
class Solution: def maxProbability(self, n: int, edges: List[List[int]], probs: List[float], s: int, t: int) -> float: # first build the graph graph = {u: {} for u in range(n)} for (u, v), prob in zip(edges, probs): graph[u][v] = prob graph[v][u] = prob # run A* search frontier = [(-1, s)] seen = set() while len(frontier) != 0: neg_path_prob, u = heapq.heappop(frontier) if u == t: return -neg_path_prob seen.add(u) for v, edge_prob in graph[u].items(): if v not in seen: heapq.heappush(frontier, (neg_path_prob * edge_prob, v)) return 0
PYTHON
{ "starter_code": "\nclass Solution:\n def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:\n ", "url": "https://leetcode.com/problems/path-with-maximum-probability/" }
d259
train
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ dmap={} dmap[0]=s.count('z') dmap[2]=s.count('w') dmap[4]=s.count('u') dmap[6]=s.count('x') dmap[8]=s.count('g') dmap[1]=s.count('o')-dmap[0]-dmap[2]-dmap[4] dmap[3]=s.count('h')-dmap[8] dmap[5]=s.count('f')-dmap[4] dmap[7]=s.count('s')-dmap[6] dmap[9]=s.count('i')-dmap[6]-dmap[8]-dmap[5] res='' #现在的问题就是如何在这里输入 dmap=sorted(list(dmap.items()),key=lambda x:x[0]) lst=['0','1','2','3','4','5','6','7','8','9'] #就是按照第一个来进行排序 ''' lst=['zero','one','two','three','four','five', 'six','seven','eight','nine'] 这个是错误示范 我们需要输出的是数字 字符串 而不是字母 ''' for i in range(len(lst)): res+=lst[i]*dmap[i][1] return res #注意 这道题比较关键的就是需要找到规律才行
PYTHON
{ "starter_code": "\nclass Solution:\n def originalDigits(self, s: str) -> str:\n ", "url": "https://leetcode.com/problems/reconstruct-original-digits-from-english/" }
d260
train
import numpy as np import math class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: if len(nums) == 1: return int(math.ceil(nums[0]/threshold)) np_nums = np.array(nums) low, high = 1, np.max(np_nums) divisors = [] while low + 1 < high: mid = (low + high) // 2 if np.sum(np.ceil(np_nums/mid)) > threshold: low = mid else: high = mid if np.sum(np.ceil(np_nums/low)) <= threshold: return low return high
PYTHON
{ "starter_code": "\nclass Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n ", "url": "https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/" }
d261
train
class Solution: def wiggleMaxLength(self, arr): """ :type nums: List[int] :rtype: int """ n = len(arr) if n < 2: return n wsl = [0]*n wsl[0] = 1 for cur in range(1, n): prev = cur - 1 if arr[cur] > arr[prev] and wsl[prev] <= 1: wsl[cur] = abs(wsl[prev]) + 1 elif arr[cur] < arr[prev] and wsl[prev] > 0: wsl[cur] = (abs(wsl[prev]) + 1)*(-1) else: wsl[cur] = wsl[prev] return abs(wsl[n-1])
PYTHON
{ "starter_code": "\nclass Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/wiggle-subsequence/" }
d262
train
class Solution: def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums = sorted(nums, reverse=True) return nums[k - 1]
PYTHON
{ "starter_code": "\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n ", "url": "https://leetcode.com/problems/kth-largest-element-in-an-array/" }
d263
train
class Solution: def isSolvable(self, words: List[str], result: str) -> bool: longest_word = max([len(word) for word in words]) if len(result) != longest_word and len(result) != longest_word + 1: return False result_indices = [] acc = 0 all_chars = [] front_indices = [] for i in range(1, longest_word + 1): for word in words: if i == len(word): front_indices.append(acc) if i <= len(word): all_chars.append(word[i * -1]) acc += 1 if i == len(result): front_indices.append(acc) result_indices.append(acc) acc += 1 all_chars.append(result[i * -1]) if len(result) > longest_word: result_indices.append(acc) front_indices.append(acc) all_chars.append(result[0]) self.words = words self.result = result self.result_indices = result_indices self.all_chars = all_chars self.mappings = {} self.used_chars = set() self.front_indices = front_indices return self.backtrack(0, 0) def backtrack(self, current_i: int, carry: int) -> bool: if current_i == len(self.all_chars): if self.mappings[self.result[0]] == 0: return False return True cur_char = self.all_chars[current_i] if current_i in self.result_indices: code, new_carry = self.verify(self.result_indices.index(current_i), carry) if code == 0: return False else: if self.backtrack(current_i + 1, new_carry): return True if code == 2: self.used_chars.remove(self.mappings[cur_char]) del self.mappings[cur_char] return False if cur_char in self.mappings: if current_i in self.front_indices and self.mappings[cur_char] == 0: return False return self.backtrack(current_i + 1, carry) for i in range(10): if current_i in self.front_indices and i == 0: continue if i not in self.used_chars: self.mappings[cur_char] = i self.used_chars.add(i) if self.backtrack(current_i + 1, carry): return True del self.mappings[cur_char] self.used_chars.remove(i) return False def verify(self, index: int, carry: int) -> (int, int): cur_sum = carry for word in self.words: if index < len(word): cur_sum += self.mappings[word[index * -1 -1]] carry = int(cur_sum / 10) cur_sum = cur_sum % 10 result_char = self.result[index * -1 - 1] if result_char in self.mappings: if self.mappings[result_char] != cur_sum: return 0, 0 else: return 1, carry else: if cur_sum in self.used_chars: return 0, 0 self.mappings[result_char] = cur_sum self.used_chars.add(cur_sum) return 2, carry
PYTHON
{ "starter_code": "\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n ", "url": "https://leetcode.com/problems/verbal-arithmetic-puzzle/" }
d264
train
class Solution: dp = [[1] * 10] def knightDialer(self, n: int) -> int: MOD = 10 ** 9 + 7 jump = [[4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [], [0, 1, 7], [2, 6], [1, 3], [2, 4]] for i in range(len(self.dp), n): new = [0] * 10 for j in range(10): new[j] = sum(self.dp[-1][k] for k in jump[j]) % MOD self.dp.append(new) return sum(self.dp[n - 1]) % MOD
PYTHON
{ "starter_code": "\nclass Solution:\n def knightDialer(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/knight-dialer/" }
d265
train
class Solution: def maxLength(self, arr: List[str]) -> int: def digit_representation(s): ans = 0 for c in s: ans |= 1<<(ord(c)-ord('a')) return ans A = sorted([(len(s), digit_representation(s)) for s in set(arr) if len(set(s))==len(s)], reverse=True) if not A: return 0 R = [sum(t[0] for t in A)] for i in range(1, len(A)): R.append(R[-1] - A[i][0]) self.ans = A[0][0] def helper(i, b, k): if i == len(A): self.ans = max(self.ans, k) elif k + R[i] > self.ans: if not (b & A[i][1]): helper(i+1, b | A[i][1], k+A[i][0]) helper(i+1, b, k) helper(0, 0, 0); return self.ans
PYTHON
{ "starter_code": "\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/" }
d266
train
class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: sum_set = set() sum_set.add(0) temp = 0 count = 0 for num in nums: temp += num if temp - target in sum_set: count += 1 sum_set.clear() sum_set.add(0) temp = 0 continue sum_set.add(temp) return count
PYTHON
{ "starter_code": "\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/" }
d267
train
class Solution: def numSplits(self, s: str) -> int: left = [0]*len(s) unique = set() n_distinct = 0 for i, l in enumerate(s): if l not in unique: unique.add(l) n_distinct += 1 left[i] = n_distinct count = 0 unique = set() n_distinct = 0 for i in range(len(s)-1, 0,-1): if s[i] not in unique: unique.add(s[i]) n_distinct += 1 if n_distinct == left[i-1]: count += 1 return count
PYTHON
{ "starter_code": "\nclass Solution:\n def numSplits(self, s: str) -> int:\n ", "url": "https://leetcode.com/problems/number-of-good-ways-to-split-a-string/" }
d268
train
class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ s = [] for token in tokens: if token == "+": a = int(s.pop()) b = int(s.pop()) s.append(a+b) elif token == "/": a = int(s.pop()) b = int(s.pop()) s.append(b/a) elif token == "*": a = int(s.pop()) b = int(s.pop()) s.append(a*b) elif token == "-": a = int(s.pop()) b = int(s.pop()) s.append(b-a) else: s.append(token) if len(s) is not 1: return False else: return int(s.pop())
PYTHON
{ "starter_code": "\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n ", "url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/" }
d269
train
class Solution: def baseNeg2(self, N: int) -> str: # res = [] # x = N # while x: # res.append(x & 1) # x = -(x >> 1) # return \"\".join(map(str, res[::-1] or [0])) neg = [1 << i for i in range(1, 33, 2)] for mask in neg: if N & mask: N += mask*2 return bin(N)[2:]
PYTHON
{ "starter_code": "\nclass Solution:\n def baseNeg2(self, N: int) -> str:\n ", "url": "https://leetcode.com/problems/convert-to-base-2/" }
d270
train
class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: if nums.count(0) == len(nums): return True idx = nums.index(1) ctr = 0 for num in nums[idx+1:]: if num == 1: if ctr < k: return False ctr = 0 else: ctr+=1 return True
PYTHON
{ "starter_code": "\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n", "url": "https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/" }
d271
train
import math class Solution: def __init__(self): self.happy_string = '' def getHappyString(self, n: int, k: int) -> str: # determine starting character poss_per_group = 2 ** (n - 1) group_num = math.ceil(k / poss_per_group) - 1 starting_char = '' # check to make sure there are at least k happy strings if k > poss_per_group * 3: return '' if group_num == 0: self.happy_string += 'a' elif group_num == 1: self.happy_string += 'b' else: self.happy_string += 'c' self.findNextChar(group_num, n - 1, group_num * poss_per_group, (group_num + 1) * poss_per_group, k) return self.happy_string def findNextChar(self, char_index: int, n: int, start: int, end: int, k: int) -> None: if n != 0: lower_index = -1 upper_index = -1 # 0 = 'a', 1 = 'b', 2 = 'c' if char_index == 0: lower_index = 1 upper_index = 2 elif char_index == 1: lower_index = 0 upper_index = 2 else: lower_index = 0 upper_index = 1 midpoint = int((start + end ) / 2) if (k <= midpoint): self.happy_string += self.indexToStr(lower_index) self.findNextChar(lower_index, n - 1, start, midpoint, k) else: self.happy_string += self.indexToStr(upper_index) self.findNextChar(upper_index, n - 1, midpoint, end, k) def indexToStr(self, index: int) -> str: if index == 0: return 'a' elif index == 1: return 'b' else: return 'c'
PYTHON
{ "starter_code": "\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n ", "url": "https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/" }
d272
train
class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) can = True smallest_idx = n - 1 for i in range(n - 2, -1, -1): can = i + nums[i] >= smallest_idx if can: smallest_idx = i return can
PYTHON
{ "starter_code": "\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/jump-game/" }
d273
train
class Solution: def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int: # nested boxes reachable=[False]*len(status) visited=[False]*len(status) for box in initialBoxes: reachable[box]=True for i in range(len(containedBoxes)): for inside in containedBoxes[i]: reachable[inside]=False # we only start with initial boxes queue=initialBoxes target=[] ret=0 while queue: for box in queue: if status[box]==1 and reachable[box] and not visited[box]: ret+=candies[box] visited[box]=True for key in keys[box]: if status[key]==0: status[key]=1 if reachable[key]: target.append(key) for inside in containedBoxes[box]: reachable[inside]=True if status[inside]==1: target.append(inside) else: target.append(box) if target==queue: break queue=target target=[] return ret
PYTHON
{ "starter_code": "\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/" }
d274
train
class Solution: dp = {0: 0} def racecar(self, target: int) -> int: if target in self.dp: return self.dp[target] n = target.bit_length() if 2**n - 1 == target: self.dp[target] = n else: self.dp[target] = self.racecar(2**n - 1 - target) + n + 1 for m in range(n - 1): self.dp[target] = min(self.dp[target], self.racecar(target - 2**(n - 1) + 2**m) + n + m + 1) return self.dp[target]
PYTHON
{ "starter_code": "\nclass Solution:\n def racecar(self, target: int) -> int:\n ", "url": "https://leetcode.com/problems/race-car/" }
d275
train
from collections import deque class Solution: def longestSubarray(self, nums, limit): maxQ, minQ = deque(), deque() i = 0 res = 0 for j, val in enumerate(nums): while maxQ and val > maxQ[-1]: maxQ.pop() while minQ and val < minQ[-1]: minQ.pop() maxQ.append(val) minQ.append(val) if maxQ[0] - minQ[0] > limit: if maxQ[0] == nums[i]: maxQ.popleft() if minQ[0] == nums[i]: minQ.popleft() i += 1 res = max(res, j-i+1) return res from collections import deque class Solution: def longestSubarray(self, nums, limit): maxQ, minQ = deque(), deque() i = 0 for val in nums: while maxQ and val > maxQ[-1]: maxQ.pop() while minQ and val < minQ[-1]: minQ.pop() maxQ.append(val) minQ.append(val) if maxQ[0] - minQ[0] > limit: if maxQ[0] == nums[i]: maxQ.popleft() if minQ[0] == nums[i]: minQ.popleft() i += 1 return len(nums) - i
PYTHON
{ "starter_code": "\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n ", "url": "https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/" }
d276
train
class Solution: def checkValidString(self, s): """ :type s: str :rtype: bool """ low, high = 0, 0 for c in s: if c == "(": low += 1 high += 1 elif c == ")": if low > 0: low -= 1 high -= 1 else: if low > 0: low -= 1 high += 1 if high < 0: return False return low == 0
PYTHON
{ "starter_code": "\nclass Solution:\n def checkValidString(self, s: str) -> bool:\n ", "url": "https://leetcode.com/problems/valid-parenthesis-string/" }
d277
train
class Solution: def findMinStep(self, board, hand): """ :type board: str :type hand: str :rtype: int """ res=float("inf") hmap=collections.defaultdict(int) for c in hand: hmap[c]+=1 res=self.helper(board,hmap) if res == float("inf"): return -1 return res def helper(self,board,hmap): board=self.removeConsecutive(board) if len(board) ==0: return 0 cnt=float("inf") j=0 for i in range(len(board)+1): if i<len(board) and board[i] ==board[j]: continue need=3-(i-j) if hmap[board[j]]>=need: hmap[board[j]]-=need res=self.helper(board[0:j]+board[i:],hmap) if res!=float("inf"): cnt=min(cnt,res+need) hmap[board[j]]+=need j=i return cnt def removeConsecutive(self,board): j=0 for i in range(len(board)+1): if i<len(board) and board[i] ==board[j]: continue if i-j>=3: return self.removeConsecutive(board[0:j]+board[i:]) else: j=i return board
PYTHON
{ "starter_code": "\nclass Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n ", "url": "https://leetcode.com/problems/zuma-game/" }
d278
train
class Solution: def numTimesAllBlue(self, light: List[int]) -> int: right = 0 ans = 0 for i in range(len(light)): if (light[i] > right): right = light[i] if (i + 1 == right): ans += 1 return ans
PYTHON
{ "starter_code": "\nclass Solution:\n def numTimesAllBlue(self, light: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/bulb-switcher-iii/" }
d279
train
class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: counts = Counter(digits) m = sum(digits) % 3 if m: if counts[m] + counts[m+3] + counts[m+6]: counts[min([m+i for i in [0,3,6] if counts[m+i]])] -= 1 else: counts[min([i-m for i in [3,6,9] if counts[i-m]])] -= 1 counts[min([i-m for i in [3,6,9] if counts[i-m]])] -= 1 ans = '' for i in range(9, -1, -1): if not ans and not counts[i]: continue ans += str(i) * counts[i] if ans: return ans.lstrip('0') or '0' return ''
PYTHON
{ "starter_code": "\nclass Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n ", "url": "https://leetcode.com/problems/largest-multiple-of-three/" }
d280
train
class Solution: def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ nums = list("123456789") k -= 1 factor = 1 for i in range(1, n): factor *= i res = [] for i in reversed(list(range(n))): res.append(nums[k//factor]) nums.remove(nums[k//factor]) if i: k %= factor factor //= i return "".join(res)
PYTHON
{ "starter_code": "\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n ", "url": "https://leetcode.com/problems/permutation-sequence/" }
d281
train
from functools import lru_cache class Solution: def palindromePartition(self, s: str, k: int) -> int: n = len(s) if n == k: return 0 @lru_cache(None) def cnt(left,right): # cost to make palindrome if left >= right: return 0 return cnt(left+1,right-1) + (s[left] != s[right]) @lru_cache(None) def dp(length,partition): if partition == length: return 0 if partition == 1: return cnt(0,length-1) return min(dp(prelength,partition-1) + cnt(prelength,length-1) for prelength in range(partition -1, length)) return dp(n,k)
PYTHON
{ "starter_code": "\nclass Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n ", "url": "https://leetcode.com/problems/palindrome-partitioning-iii/" }
d282
train
class Solution: def canConvertString(self, s: str, t: str, k: int) -> bool: if len(s) != len(t): return False c = Counter((ord(c2) - ord(c1)) % 26 for c1, c2 in zip(s, t)) return k >= max( (m + 26 * (count - 1) for m, count in list(c.items()) if m), default = 0)
PYTHON
{ "starter_code": "\nclass Solution:\n def canConvertString(self, s: str, t: str, k: int) -> bool:\n ", "url": "https://leetcode.com/problems/can-convert-string-in-k-moves/" }
d283
train
class Solution: def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: dp = [[0 for _ in range(len(mat[0]) + 1)]for r in range(len(mat) + 1)] for r in range(1, len(mat) + 1): for c in range(1, len(mat[r-1]) + 1): dp[r][c] += mat[r-1][c-1] if not r and not c: continue elif not r: dp[r][c] += dp[r][c-1] continue elif not c: dp[r][c] += dp[r-1][c] continue dp[r][c] += dp[r][c-1] + dp[r-1][c] - dp[r-1][c-1] # print(dp) highest = -1 for r in range(1, len(dp)): r0= r1 = r c0= c1 = 1 while r1 < len(dp) and c1 < len(dp[0]): result = dp[r1][c1] + dp[r0-1][c0-1] - dp[r1][c0-1] - dp[r0-1][c1] # print(f'r0:{r0} r1:{r1} c0:{c0} c1:{c1} result:{result}') if result <= threshold: highest = max(r1-r0, highest) r1 += 1 c1 +=1 else: r1 -=1 c0 +=1 r1 = max(r0+1,r1) c1 = max(c0+1,c1) return highest + 1
PYTHON
{ "starter_code": "\nclass Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/" }
d284
train
class Solution: def smallestDistancePair(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() l, r = 0, nums[-1] - nums[0] while l < r: m = l + (r - l) // 2 count = 0 left = 0 for right in range(len(nums)): while nums[right] - nums[left] > m: left += 1 count += (right - left) if count < k : l = m+1 else: r = m return l
PYTHON
{ "starter_code": "\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n ", "url": "https://leetcode.com/problems/find-k-th-smallest-pair-distance/" }
d285
train
class Solution: def bagOfTokensScore(self, tokens: List[int], P: int) -> int: tokens = sorted(tokens) left = 0 right = len(tokens) - 1 points = 0 if len(tokens) == 1: if tokens[0] <= P: return 1 if len(tokens) == 0: return 0 while left < right: if tokens[left] <= P: P -= tokens[left] left += 1 points += 1 elif tokens[left] > P and points > 0: P += tokens[right] points -= 1 right -= 1 elif points == 0 and tokens[left] > P: break if P >= tokens[left]: points += 1 return points
PYTHON
{ "starter_code": "\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], P: int) -> int:\n ", "url": "https://leetcode.com/problems/bag-of-tokens/" }
d286
train
class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: if not A: return 0 nums = sorted([num + K for num in set(A)], reverse=True) max_num = nums[0] min_num = nums[-1] changed_max = max_num - 2 * K res = max_num - min_num for i in range(len(nums) - 1): changed = nums[i] - 2 * K max_num = max(nums[i + 1], changed, changed_max) min_num = min(min_num, changed) res = min(res, max_num - min_num) return res
PYTHON
{ "starter_code": "\nclass Solution:\n def smallestRangeII(self, A: List[int], K: int) -> int:\n ", "url": "https://leetcode.com/problems/smallest-range-ii/" }
d287
train
from math import comb class Solution: def getProbability(self, balls: List[int]) -> float: n = len(balls) s = sum(balls) s2 = s // 2 @lru_cache(None) def count(index, delta, ca): if index == n: return 1 if delta == 0 and ca == s2 else 0 total = sum([count(index + 1, delta, ca + x) * comb(balls[index], x) for x in range(1, balls[index])]) total += count(index + 1, delta + 1, ca) total += count(index + 1, delta - 1, ca + balls[index]) return total return count(0, 0, 0) / comb(s, s // 2)
PYTHON
{ "starter_code": "\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n ", "url": "https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/" }
d288
train
class Solution: def countArrangement(self, N): """ :type N: int :rtype: int """ d = { 1:1, 2:2, 3:3, 4:8, 5:10, 6:36, 7:41, 8:132, 9:250, 10:700, 11:750, 12:4010, 13:4237, 14:10680, 15:24679 } return d.get(N, N)
PYTHON
{ "starter_code": "\nclass Solution:\n def countArrangement(self, N: int) -> int:\n ", "url": "https://leetcode.com/problems/beautiful-arrangement/" }
d289
train
class Solution: def flipLights(self, n, m): """ :type n: int :type m: int :rtype: int """ states = set() for op_odd in [0, 1]: for op_even in [0, 1]: for op_third in [0, 1]: op_all = m - op_odd - op_even - op_third if op_all >= 0: one = (op_odd + op_all + op_third) % 2 two = (op_even + op_all) % 2 three = op_odd % 2 four = (op_even + op_all + op_third) % 2 states.add((one, two, three, four)[:n]) return len(states)
PYTHON
{ "starter_code": "\nclass Solution:\n def flipLights(self, n: int, m: int) -> int:\n ", "url": "https://leetcode.com/problems/bulb-switcher-ii/" }
d290
train
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: N = len(A) if L+M>N: return -1 def findmax(L,M): sL = [sum(A[:L])] for i in range(L,N-M): tmp = sL[-1]+A[i]-A[i-L] sL.append(tmp) sLmax = [sL[0]] for i in range(1,len(sL)): if sL[i]>sLmax[-1]: sLmax.append(sL[i]) else: sLmax.append(sLmax[-1]) sM = [sum(A[-M:])] for i in range(N-M-1,L-1,-1): tmp = sM[-1]+A[i]-A[i+M] sM.append(tmp) sMmax = [sM[0]] for i in range(1,len(sM)): if sM[i]>sMmax[-1]: sMmax.append(sM[i]) else: sMmax.append(sMmax[-1]) sMax = [sum(x) for x in zip(sLmax, sMmax[::-1])] m = max(sMax) return m if L == M: return findmax(L,M) else: return max(findmax(L,M), findmax(M,L))
PYTHON
{ "starter_code": "\nclass Solution:\n def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:\n ", "url": "https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/" }
d291
train
class Solution: def minCost(self, n: int, cuts: List[int]) -> int: cuts.sort() from functools import lru_cache @lru_cache(None) def helper(i = 0, j = n): ans = math.inf for c in cuts: if c <= i: continue if c >= j: break ans = min(ans, j - i + helper(i, c) + helper(c, j)) if ans == math.inf: return 0 return ans return helper()
PYTHON
{ "starter_code": "\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/minimum-cost-to-cut-a-stick/" }
d292
train
class Solution: def numOfSubarrays(self, arr: List[int]) -> int: mod = 10**9+7 odd_presum_cnt = 0 par = 0 for a in arr: par ^= a & 1 if par: odd_presum_cnt += 1 return odd_presum_cnt * (len(arr)+1 - odd_presum_cnt)%mod
PYTHON
{ "starter_code": "\nclass Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/" }
d293
train
# https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/340075/c%2B%2B-beats-100-(both-time-and-memory)-with-algorithm-and-image class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: N = len(arr1) a = [arr1[i] + arr2[i] + i for i in range(N)] b = [arr1[i] + arr2[i] - i for i in range(N)] c = [arr1[i] - arr2[i] + i for i in range(N)] d = [arr1[i] - arr2[i] - i for i in range(N)] return max( max(x) - min(x) for x in (a, b, c, d) )
PYTHON
{ "starter_code": "\nclass Solution:\n def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/maximum-of-absolute-value-expression/" }
d294
train
class Solution: def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ if n == 0: return len(tasks) from collections import Counter counter = Counter(tasks) window = n + 1 biggest_freq = max(list(counter.values())) num_of_max_freq = list(counter.values()).count(biggest_freq) return max(window * (biggest_freq - 1) + num_of_max_freq, len(tasks))
PYTHON
{ "starter_code": "\nclass Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n ", "url": "https://leetcode.com/problems/task-scheduler/" }
d295
train
class Solution: def totalNQueens(self, n): def dfs(lst, xy_dif, xy_sum): p=len(lst) if p==n: res.append(lst) for q in range(n): if (q not in lst) and (p-q not in xy_dif) and (p+q not in xy_sum): dfs(lst+[q], xy_dif+[p-q], xy_sum +[p+q]) res=[] dfs([],[],[]) return len(res)
PYTHON
{ "starter_code": "\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n ", "url": "https://leetcode.com/problems/n-queens-ii/" }
d296
train
class Solution: def isSelfCrossing(self, x): """ :type x: List[int] :rtype: bool """ if not x or len(x) < 4: return False i = 3 while i < len(x): #print(i) if x[i] >= x[i-2] and x[i-1] <= x[i-3]: print('case 1') return True elif i >= 4 and x[i-1] == x[i-3] and x[i] + x[i-4] >= x[i-2]: print('case 2') return True elif i >= 5 and x[i-4] < x[i-2] <= x[i] + x[i-4] and x[i-1] <= x[i-3] <= x[i] + x[i-5]: print('case 3') return True i += 1 return False
PYTHON
{ "starter_code": "\nclass Solution:\n def isSelfCrossing(self, x: List[int]) -> bool:\n ", "url": "https://leetcode.com/problems/self-crossing/" }
d297
train
class Solution: def findMin(self, nums): """ :type nums: List[int] :rtype: int """ min = nums[0] start, end = 0, len(nums) - 1 while start<end: mid = (start+end)//2 if nums[mid]>nums[end]: start = mid+1 elif nums[mid]<nums[end]: end = mid else: end = end - 1 return nums[start]
PYTHON
{ "starter_code": "\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n ", "url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/" }
d298
train
class Solution: def numTilePossibilities(self, tiles: str) -> int: res = 0 freqs = [f + 1 for f in Counter(tiles).values()] for t in itertools.product(*map(range, freqs)): n = sum(t) subtotal = math.factorial(n) for freq in t: subtotal //= math.factorial(freq) res += subtotal return res - 1
PYTHON
{ "starter_code": "\nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n ", "url": "https://leetcode.com/problems/letter-tile-possibilities/" }
d299
train
class Solution: def multiply(self,num1, num2): """ :type num1: str :type num2: str :rtype: str """ a=['0','1','2','3','4','5','6','7','8','9'] z=0 x=0 for i,element in enumerate(num1): for j in range(10): if element==a[j]: z+=j*(10**(len(num1)-i-1)) for c,b in enumerate(num2): for k in range(10): if b==a[k]: x+=k*(10**(len(num2)-c-1)) mul=z*x return(''.join('%d'%mul))
PYTHON
{ "starter_code": "\nclass Solution:\n def multiply(self, num1: str, num2: str) -> str:\n ", "url": "https://leetcode.com/problems/multiply-strings/" }
d300
train
from collections import deque class Solution: def minCost(self, grid: List[List[int]]) -> int: right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0) direction_map = { 1: right, 2: left, 3: down, 4: up } directions = [right, left, down, up] visited = set() def in_bounds(i, j): return 0 <= i < len(grid) and 0 <= j < len(grid[i]) def dfs(i, j): # not in bounds if not in_bounds(i, j) or (i, j) in visited: return [] visited.add((i, j)) sign = grid[i][j] direction = direction_map[sign] next_i, next_j = i + direction[0], j + direction[1] return [(i, j)] + dfs(next_i, next_j) reachable = dfs(0, 0) curr_cost = 0 while reachable: next_reachable = [] for (i, j) in reachable: if i == len(grid) - 1 and j == len(grid[i]) - 1: return curr_cost for d in directions: next_reachable += dfs(i + d[0], j + d[1]) reachable = next_reachable curr_cost += 1 return -1
PYTHON
{ "starter_code": "\nclass Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n ", "url": "https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/" }