sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
ae1c2c
4a480f
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.   Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-...
class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: n = len(arr1) rtn = 0 for sign1 in [-1, 1]: for sign2 in [-1, 1]: b = [] for i in range(n): b.append(arr1[i] * sign1 + arr2[i] * sign2 + i) ...
63bce4
4a480f
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.   Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-...
class Solution(object): def maxAbsValExpr(self, A, B): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ # max Ai - Aj + Bi - Bj, Aj - Ai + Bi - Bj, Ai - Aj + Bj - Bi, Aj - Ai + Bj - Bi T = [A[0] + B[0], A[0] - B[0], -A[0] + B[0], -A[0] - B[0]] ...
3d79cf
88be47
There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments w...
class Solution: def maximizeWin(self, prizePositions: List[int], k: int) -> int: n = len(prizePositions) pre = [0]*(n+1) for i in range(n): cur = i + 1 - bisect.bisect_left(prizePositions, prizePositions[i]-k) pre[i+1] = pre[i] if pre[i] > cur else cur post...
c34354
88be47
There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments w...
from collections import Counter class Solution(object): def maximizeWin(self, prizePositions, k): """ :type prizePositions: List[int] :type k: int :rtype: int """ cnt = Counter(prizePositions) pos = list(sorted(cnt.keys())) n = len(pos) max_pri...
64c83d
9e74d0
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination r...
class Solution(object): def numOfMinutes(self, n, headID, parent, informTime): children = collections.defaultdict(list) for i, x in enumerate(parent): if x >= 0: children[x].append(i) self.ans = 0 def dfs(node, w): if w > self.ans:...
4a4f63
9e74d0
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination r...
from functools import lru_cache class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: @lru_cache(maxsize=None) def dfs(x): fa=manager[x] if fa==-1: return 0 return dfs(fa)+informTime[fa] ...
dd376d
36c675
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s a...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def getDirections(self, root, startValue, destValue): """ :type root: Option...
676775
36c675
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s a...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: d = defau...
28044a
f99e7a
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following w...
class Solution: def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int: n = len(plants) half = n // 2 refill = 0 balance = capacityA for i in range(half): if balance < plants[i]: balance = capacityA refill...
2dfe73
f99e7a
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following w...
class Solution(object): def minimumRefill(self, plants, capacityA, capacityB): """ :type plants: List[int] :type capacityA: int :type capacityB: int :rtype: int """ a = plants i = 0 j = len(a)-1 r = 0 ci = capacityA cj =...
28540b
e66801
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct ...
import itertools import sys sys.setrecursionlimit(20000) class Solution: def dfs(self, grams, prefix, n, k): if not grams: return prefix suffix = prefix[1 - n:] for c in range(k): candidate = suffix + str(c) if candidate in grams: # Try it...
37b1fa
e66801
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct ...
class Solution(object): def crackSafe(self, n, k): """ :type n: int :type k: int :rtype: str """ alph = list(map(str, range(k))) if n == 1: return "".join(i for i in alph) if k == 1: return "0" * n a = [0] * k *...
e465e5
35c9d2
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x t...
from typing import * from functools import lru_cache import bisect from queue import Queue import math class Solution: def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: n, m = len(nums), len(multipliers) @lru_cache(None) def helper(i, j, idx): ...
63e038
35c9d2
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x t...
class Solution(object): def maximumScore(self, nums, multipliers): """ :type nums: List[int] :type multipliers: List[int] :rtype: int """ n = len(nums) r = [0] for k, mult in enumerate(multipliers, 1): rr = [-float('inf')] * (k+1) ...
523571
071557
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/three". Two folders (not necessarily on the same level) are...
from collections import Counter class Trie: def __init__(self): self.ch = {} self.is_dir = False class Solution(object): def deleteDuplicateFolder(self, paths): """ :type paths: List[List[str]] :rtype: List[List[str]] """ r = Trie() for path in p...
cfa919
071557
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/three". Two folders (not necessarily on the same level) are...
import collections class Solution: def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]: paths.sort() path_tree = {} # list of subfolders. For each subfolder, key is name, value is list of sub-folders for i in paths: cur = path_tree for j in i...
8317a3
d1c842
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be ...
class Solution(object): def fractionAddition(self, expression): from itertools import groupby from fractions import Fraction sign = 1 fra = [0, 0] part = 0 ans = Fraction(0, 1) for k, v in groupby(expression, lambda x: x.isdigit()): w = "".join(v) ...
d036ed
d1c842
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be ...
class Solution: def fractionAddition(self, expression): """ :type expression: str :rtype: str """ def gcd(a, b): if a < 0: return gcd(-a, b) if b < 0: return gcd(a, -b) if a < b: retu...
f6d2bb
950a39
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2.   Example 1: Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11...
class Solution: def advantageCount(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ n = len(A) A = list(sorted(A)) b = [(v, i) for i, v in enumerate(B)] b.sort() r = [-1] * n used = [False] * n ...
b3dd0b
950a39
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2.   Example 1: Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11...
class Solution(object): def advantageCount(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ N = len(B) Bs = sorted([(B[i], i) for i in xrange(N)]) As = sorted([(A[i], i) for i in xrange(N)]) per = [None for i in xran...
e0380d
4a4186
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= nums1 < nums2 <= right . nums1 and nums2 are both prime numbers. nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array ans = [nums1, nums2]. If there are...
def euler_flag_prime(n): # 欧拉线性筛素数 # 说明:返回小于等于 n 的所有素数 flag = [False for _ in range(n + 1)] prime_numbers = [] for num in range(2, n + 1): if not flag[num]: prime_numbers.append(num) for prime in prime_numbers: if num * prime > n: break ...
ce6336
4a4186
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= nums1 < nums2 <= right . nums1 and nums2 are both prime numbers. nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array ans = [nums1, nums2]. If there are...
class Solution(object): def closestPrimes(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ p, i, a, b, d = [False, True] + [False] * (right - 1), 2, [], [-1, -1], float('inf') while i * i <= right: if not p[i]: ...
63e8fa
e277bf
You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to: Trim each number in nums to its rightmost trimi digits. Determine the index of the...
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: ans=[] for k,trim in queries: arr=[] for i,v in enumerate(nums): arr.append((v[-trim:],i)) arr.sort() ans.append(arr[k-1][1]) ...
b78601
e277bf
You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to: Trim each number in nums to its rightmost trimi digits. Determine the index of the...
class Solution(object): def smallestTrimmedNumbers(self, nums, queries): """ :type nums: List[str] :type queries: List[List[int]] :rtype: List[int] """ r, i, n = [0] * len(queries), 0, [None] * len(nums) for q in queries: for j in range(0, len(nums...
7261f2
45b588
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[...
class Solution(object): def diagonalSort(self, A): R, C = len(A), len(A[0]) vals = collections.defaultdict(list) for r, row in enumerate(A): for c,v in enumerate(row): vals[r-c].append(v) for row in vals.values(): row.sort(reverse=True) ...
db2dcc
45b588
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[...
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: m=len(mat) n=len(mat[0]) for i in range(n): ind=[(k,i+k) for k in range(100) if k in range(m) and i+k in range(n)] L=[mat[x[0]][x[1]] for x in ind] L.sort() for k ...
c8994b
623c36
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and ...
from functools import lru_cache from itertools import groupby class Solution: def getLengthOfOptimalCompression(self, S, K): def rle(x): if x <= 1: return x return len(str(x)) + 1 N = len(S) if N == K: return 0 """ left = [1] * N f...
26f915
623c36
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and ...
class Solution(object): def getLengthOfOptimalCompression(self, s, k): """ :type s: str :type k: int :rtype: int """ n = len(s) cost = [0] * max(n+1, 5) cost[1] = 1 cost[2] = 2 t = 10 for i in xrange(3, n+1): cost[i]...
90b9eb
2e4b72
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2...
class Solution: def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) self.n = n pos1 = [0 for i in range(n)] pos2 = [0 for i in range(n)] for i in range(n): x = nums1[i] pos1[x] = i x = nums2[i] pos...
de019d
2e4b72
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2...
class Solution(object): def goodTriplets(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ d = {} for i, n in enumerate(nums1): d[n] = i nums = [] for n in nums2: nums.append(d[n]) ...
ec8939
dfc0a7
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[...
class Solution(object): def numPermsDISequence(self, S): """ :type S: str :rtype: int """ # dp[number of elements in the permutation][ranking of last element in the permutation] li1=[1] # previous list for i in range(len(S)): li2=[0]*(i...
b3734f
dfc0a7
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[...
class Solution: def numPermsDISequence(self, S): """ :type S: str :rtype: int """ x = [1] mod = 10**9 + 7 for c in S: new_x = [0] if c == "I": for i in x: new_x.append((new_x[-1] + i)%mod) ...
99b427
7cd4d0
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions: arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1. arr2 contains uniqueCnt2 distinct positive integers, each of which ...
class Solution: def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int: low, high = 1, 10**20 while low != high: mid = (low+high) >> 1 x = mid - mid // divisor1 y = mid - mid // divisor2 both = mid - mid // lcm(div...
2d38c0
7cd4d0
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions: arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1. arr2 contains uniqueCnt2 distinct positive integers, each of which ...
class Solution(object): def minimizeSet(self, divisor1, divisor2, uniqueCnt1, uniqueCnt2): """ :type divisor1: int :type divisor2: int :type uniqueCnt1: int :type uniqueCnt2: int :rtype: int """ def gcd(a, b): while a: a, b ...
869604
026443
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000',...
class Solution: def openLock(self, deadends, target): # BFS for the target deadends = set(deadends) level = ['0000'] visited = set('0000') nLevel = 0 if '0000' in deadends or target in deadends: return -1 while level: nLevel += 1 newLev...
806f4d
026443
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000',...
class Solution(object): def openLock(self, deadends, target): """ :type deadends: List[str] :type target: str :rtype: int """ dic = {} dic['0000'] = True blocked = {} for de in deadends: blocked[de] = True if "0000" in bl...
fc1d61
a8cc6e
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges ...
class Solution: def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: deg = [0] * n for x, y in edges: deg[x - 1] += 1 deg[y - 1] += 1 wtf = Counter() for x, y in edges: wtf[(min(x, y), max(x, y))] += 1 ...
a6b4d6
a8cc6e
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges ...
from sortedcontainers import SortedList class Solution(object): def countPairs(self, n, edges, queries): """ :type n: int :type edges: List[List[int]] :type queries: List[int] :rtype: List[int] """ g=[[] for i in range(n)] cnt=[0 for i in range(n)] ...
95a0b7
c738eb
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.   Example 1: Input: matrix = [   [0,1,1,1],   [1,1,1,1],   [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15...
class Solution(object): def countSquares(self, A): R, C = len(A), len(A[0]) dp = [[0] * (C+1) for _ in xrange(R+1)] ans = 0 # largest square ending here for r, row in enumerate(A): for c, val in enumerate(row): if val: ...
3dca89
c738eb
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.   Example 1: Input: matrix = [   [0,1,1,1],   [1,1,1,1],   [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15...
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m, n = len(matrix), len(matrix[0]) f = [[0] * n for _ in range(m)] ans = 0 for i in range(m): for j in range(n): if i == 0 or j == 0: f[i][j] = matrix[i][j] ...
e014e1
760e3d
Given the root of a binary tree, return the sum of values of its deepest leaves.   Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19   Constraints: The number of nodes in the tree is in the range [1, 10000]....
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def deepestLeavesSum(self, root): stack = [(root, 0)] if root else [] ans = 0 ansd = 0 wh...
0cb62c
760e3d
Given the root of a binary tree, return the sum of values of its deepest leaves.   Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19   Constraints: The number of nodes in the tree is in the range [1, 10000]....
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: ret = 0 b = collections.deque([(0, root)]) deep = -1 w...
ae5ce4
87412d
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1. A chessboard board is a board where no 0's and no 1's are 4-dire...
class Solution(object): def movesToChessboard(self, board): def dist(set1, set2): x = [item for item in set1 if item in set2] return len(set1)-len(x) N = len(board) if N<=1: return 0 sm = sum(sum(row) for row in board) ...
3314da
9473c1
Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: MajorityChecker(int[] arr) Initializes the instance of the class with the given array ar...
class MajorityChecker: def __init__(self, arr: List[int]): self.loc_dict = collections.defaultdict(list) for i in range(len(arr)): self.loc_dict[arr[i]] += [i] self.cnt = [] for i in self.loc_dict: self.cnt += [[i,len(self.loc_dict[i])]] self.cnt = so...
0d0d55
9473c1
Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: MajorityChecker(int[] arr) Initializes the instance of the class with the given array ar...
class MajorityChecker(object): def __init__(self, arr): """ :type arr: List[int] """ self.D = collections.defaultdict(list) for i, x in enumerate(arr): self.D[x].append(i) #print sorted((len(self.D[x]), x) for x in self.D) self.vals, self.keys = z...
32b2f1
2681d4
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tre...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def bstFromPreorder(self, p): """ :type preorder: List[int] :rtype: TreeNode """ ...
d018a6
2681d4
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tre...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder) == 0: return None node ...
ccf0f1
c3fea8
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to ...
class Solution: def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: asteroids.sort() for asteroid in asteroids: if mass < asteroid: return False mass += asteroid return True
c6f62b
c3fea8
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to ...
class Solution(object): def asteroidsDestroyed(self, mass, asteroids): """ :type mass: int :type asteroids: List[int] :rtype: bool """ for v in sorted(asteroids): if v > mass: return False mass += v return True
65c8c4
072fc1
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has e...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ if N%2==0: return [] ...
f24e03
072fc1
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has e...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ def make...
717e2e
21a5ef
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the Tre...
class TreeAncestor(object): def __init__(self, n, parent): self.pars = [parent] self.n = n for k in xrange(17): row = [] for i in xrange(n): p = self.pars[-1][i] if p != -1: p = self.pars[-1][p] row....
ca0492
21a5ef
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the Tre...
class TreeAncestor: def __init__(self, n: int, par: List[int]): self.lca=[par] for _ in range(20): pvr=self.lca[-1] cur=[x for x in pvr] for i,x in enumerate(pvr): if x==-1: continue cur[i]=pvr[x] se...
e2ae76
942f9d
LeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, ...
class Solution(object): def maxVacationDays(self, flights, days): """ :type flights: List[List[int]] :type days: List[List[int]] :rtype: int """ n, t = len(flights), len(days[0]) prev = [-float('inf')] * n prev[0] = 0 for i in range(t)...
95dc69
ba71bd
You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note th...
class Solution: def xorBeauty(self, a: List[int]) -> int: ans = 0 for i in a: ans ^= i return ans
8d113f
ba71bd
You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. Note th...
class Solution(object): def xorBeauty(self, nums): """ :type nums: List[int] :rtype: int """ n=len(nums) dp=[0 for i in range(32)] for i in nums: for j in range(32): if i&(1<<j): dp[j]+=1 print dp ...
406ea2
961c7d
Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high]. Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13. Note that the digit d = 1 occ...
class Solution: def digitsCount(self, d: int, low: int, high: int) -> int: # Count from 1 to x def pre_count(x): if x == 0: return 0 str_x = str(x) N = len(str_x) ans = 0 # Numbers with less digits for i...
1ccd5a
961c7d
Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high]. Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13. Note that the digit d = 1 occ...
class Solution(object): def digitsCount(self, d, low, high): """ :type d: int :type low: int :type high: int :rtype: int """ def count(N): if N == 0: return 0 A = map(int, str(N)) res = 0 n = len(A) ...
01a12e
4a2766
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).   Example 1: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output...
class Solution(object): def reachingPoints(self, sx, sy, tx, ty): while tx!=ty and tx!=0 and ty!=0 and (tx>sx or ty>sy): if tx>ty: if ty!=sy: tx = tx%ty else: return (tx-sx)%ty == 0 else: if tx!=s...
effd1c
4a2766
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).   Example 1: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output...
class Solution(object): def reachingPoints(self, sx, sy, tx, ty): """ :type sx: int :type sy: int :type tx: int :type ty: int :rtype: bool """ while (tx == sx and ty == sy) is False and (tx != 0 and ty != 0): if tx > ty: if ...
584a33
c9d605
Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j]. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1,1,1], k ...
class Solution(object): def countGood(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ f, a, t, i = defaultdict(int), 0, 0, 0 for j in range(len(nums)): t, f[nums[j]] = t + f[nums[j]], f[nums[j]] + 1 while t >= k: ...
67503b
c9d605
Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j]. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums = [1,1,1,1,1], k ...
from typing import List, Tuple, Optional from collections import defaultdict, Counter from sortedcontainers import SortedList MOD = int(1e9 + 7) INF = int(1e20) # 给你一个整数数组 nums 和一个整数 k ,请你返回 nums 中 好 子数组的数目。 # 一个子数组 arr 如果有 至少 k 对下标 (i, j) 满足 i < j 且 arr[i] == arr[j] ,那么称它是一个 好 子数组。 # 子数组 是原数组中一段连续 非空 的元素序列。 class ...
5aec0c
3f8e8b
You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there...
class Solution: def canChange(self, s: str, t: str) -> bool: ls = [] rs = [] lt = [] rt = [] n = len(s) for i in range(n): if s[i] == 'L': ls.append(i) if s[i] == 'R': rs.append(i) if t[i] == 'L': ...
dbb171
3f8e8b
You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there...
class Solution(object): def canChange(self, start, target): a = [] n = len(start) for i in range(n): if(start[i] == "L"): a.append(["L", i]) elif (start[i] == "R"): a.append(["R", i]) b = [] for i in range(n): ...
bc65a3
df8d5e
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed stri...
class Encrypter: def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): self.d = defaultdict(int) self.m = {} for i, j in zip(keys, values): self.m[i] = j for i in dictionary: l = [] for x in i: l.append(sel...
cb9fd3
df8d5e
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed stri...
class Encrypter(object): def __init__(self, keys, values, dictionary): """ :type keys: List[str] :type values: List[str] :type dictionary: List[str] """ self.keys = keys self.values = values self.key_index = dict() for i, k in enumerate(keys):...
9c18cb
607c62
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.   Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) ...
class Solution(object): def numDupDigitsAtMostN(self, N): """ :type N: int :rtype: int """ def helper(n,used): if not used: if n == 0: return 0 if n == 1: return 9 res = 9 ...
595c71
607c62
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.   Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) ...
import functools class Solution: def numDupDigitsAtMostN(self, N: int) -> int: digits = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1] if N <= 10: return 0 str_N = list(map(int, str(N + 1))) n = len(str_N) ans = 0 # for i in range(1, n + 1): # ans += functools...
f8bc0f
fd6b38
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it...
from functools import lru_cache from sys import setrecursionlimit as srl; srl(10**5) from fractions import Fraction class Solution(object): def frogPosition(self, n, edges, T, target): graph = [[] for _ in range(n)] for u, v in edges: u-=1;v-=1 graph[u].append(v) ...
e66c33
fd6b38
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it...
class Solution(object): def frogPosition(self, n, edges, t, target): """ :type n: int :type edges: List[List[int]] :type t: int :type target: int :rtype: float """ graph=collections.defaultdict(set) for x,y in edges: graph[x].add(y)...
270d0a
d4b23e
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j -...
class Solution: def threeEqualParts(self, A): """ :type A: List[int] :rtype: List[int] """ a = A n = len(a) s = sum(a) if s % 3 != 0: return [-1, -1] if s == 0: return [0, 2] idx = [] for i in range(n): ...
1ccc69
d4b23e
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j -...
class Solution(object): def threeEqualParts(self, A): def strip_leading_zeroes(arr,start): for i in range(start,len(arr)): if arr[i]!=0: return i return len(arr) def compare_ind_eq(arr,start1,end1,start2,end2): if end1-start1!=end2-start2: return False for i,j...
347715
f83561
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as ...
class Solution(object): def maxIncreasingCells(self, mat): """ :type mat: List[List[int]] :rtype: int """ v, q, r, a = [None] * (len(mat) * len(mat[0])), [deque([]) for _ in mat], [deque([]) for _ in mat[0]], 0 for i in range(len(mat)): for j in range(len(...
1caa60
f83561
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as ...
class Solution: def maxIncreasingCells(self, mat: List[List[int]]) -> int: dic = defaultdict(list) m = len(mat) n = len(mat[0]) for row in range(m): for col in range(n): dic[mat[row][col]].append((row, col)) rows = [0] * m ...
c280f4
20f5ba
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth que...
class Solution(object): def calcEquation(self, equations, values, query): """ :type equations: List[List[str]] :type values: List[float] :type query: List[List[str]] :rtype: List[float] """ g = {} for i, equa in enumerate(equations): a, b ...
2e4965
18c82f
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted.   Exam...
from math import sqrt class Solution: def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ output = flag = float('inf') ps = set((x, y) for x, y in points) N = len(points) for i in range(N): x1, y1 = point...
f53833
18c82f
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted.   Exam...
from itertools import combinations class Solution(object): def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ d = {} r = float('inf') def d2(p1, p2): return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 def key(p1,...
927a52
b9fc01
You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the s...
class Solution(object): def minimumCost(self, start, target, specialRoads): """ :type start: List[int] :type target: List[int] :type specialRoads: List[List[int]] :rtype: int """ v, d, q = defaultdict(list), defaultdict(int), set() for x in specialRoad...
d425d2
b9fc01
You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the s...
class Solution: def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int: start = tuple(start) target = tuple(target) sx, sy = start tx, ty = target m = len(specialRoads) adj = defaultdict(list) for x1,...
c108f4
0f37a6
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor. Your task is to determine if for every pair of indices i and j in nums, where i < j...
class PrimeTable: def __init__(self, n:int) -> None: self.n = n self.primes = [] self.max_div = list(range(n+1)) self.max_div[1] = 1 self.phi = list(range(n+1)) for i in range(2, n + 1): if self.max_div[i] == i: self.primes.append(i) ...
af53c3
0f37a6
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor. Your task is to determine if for every pair of indices i and j in nums, where i < j...
pre=[i for i in range(10**5+1)] for i in range(2,10**5+1): if pre[i]!=i: continue for j in range(2*i,10**5+1,i): pre[j]=i class Solution(object): def canTraverseAllPairs(self, nums): """ :type nums: List[int] :rtype: bool """ n=len(nums) p=[i f...
58376b
19ce97
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos an...
class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: MAX = 2 * 100000 + 5 cumsum = [0] * (MAX) orig = [0] * (MAX) for pos, cnt in fruits: orig[pos] = cnt for i in range(MAX): if i == 0: cumsum...
f00c78
19ce97
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos an...
class Solution(object): def maxTotalFruits(self, fruits, startPos, k): """ :type fruits: List[List[int]] :type startPos: int :type k: int :rtype: int """ x = startPos d = {i:v for i,v in fruits} s = sum(v for i,v in fruits if x-k <= i <= x) ...
5e9ac5
7fc14b
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. (An ...
class Solution(object): def getNext(self, expression): levelCount = 0 for i in range(len(expression)): if expression[i] == " ": if levelCount == 0: newExp = expression[i+1:] this = expression[:i] return newExp....
d84717
7fc14b
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. (An ...
from collections import ChainMap def find(s, i): while s[i] == " ": i += 1 start = i if s[i]=="(": i += 1 left = 1 while i < len(s): if s[i] == "(": left += 1 elif s[i] == ")": left -= 1 if left == 0: ...
683df0
59d165
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, ...
class Solution: def concatenatedBinary(self, n: int) -> int: ans = 0 mod = 10**9 + 7 for i in range(1, n + 1): b = bin(i)[2:] digs = len(b) ans *= (2**digs) ans += i ans %= mod return ans
d46f92
59d165
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, ...
class Solution(object): def concatenatedBinary(self, n): res = 1 mod = 10**9+7 for t in xrange(2, n+1): res = (res*(1<<len(bin(t))-2)+t) % mod return res """ :type n: int :rtype: int """
391b9b
63b617
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an ...
from functools import lru_cache class Solution: def leastOpsExpressTarget(self, x, target): """ :type x: int :type target: int :rtype: int """ @lru_cache(None) def dfs(target, power): if power == 0: return 2 * abs(target) y = x ** powe...
9cddde
63b617
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an ...
class Solution(object): def leastOpsExpressTarget(self, x, target): """ :type x: int :type target: int :rtype: int """ c = [(2,1)] d, v = 1, x while v < target * x: c.append((d, v)) v *= x d += 1 cache = {} ...
a4a926
53c0ca
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith marble and jth marble are in a bag, then all marbles with an index betwee...
class Solution(object): def putMarbles(self, weights, k): """ :type weights: List[int] :type k: int :rtype: int """ v, d = [0] * (len(weights) - 1), 0 for i in range(len(weights) - 1): v[i] = weights[i] + weights[i + 1] v.sort() for...
cd7f01
53c0ca
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith marble and jth marble are in a bag, then all marbles with an index betwee...
class Solution: def putMarbles(self, weights: List[int], k: int) -> int: tmp = [] for i in range(len(weights)-1): tmp.append(weights[i] + weights[i+1]) return - sum(nsmallest(k-1, tmp)) + sum(nlargest(k-1, tmp))
0b2b01
e4baca
Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.   Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "ab...
class Solution(object): def numberOfSubstrings(self, s): """ :type s: str :rtype: int """ a, b, c = -1, -1, -1 ans = 0 for i, x in enumerate(s): if x == 'a': a = i elif x == 'b': b = i elif x ...
d1b1b3
e4baca
Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.   Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "ab...
class Solution: def numberOfSubstrings(self, s: str) -> int: prev = {'a': -1, 'b': -1, 'c': -1} res = 0 for pos, let in enumerate(s): prev[let] = pos start = min(prev.values()) if start >= 0: res += (start + 1) return res ...
e8caeb
4d931a
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, bo...
class Solution: def dfs(self, x): if self.mark[x] == True: return 0 ret = 1 self.mark[x] = True for neigh in self.edge[x]: ret += self.dfs(neigh) return ret def minMalwareSpread(self, graph, initial): """ :type graph: List[List[in...
ec0f74
4d931a
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, bo...
class Solution(object): def minMalwareSpread(self, graph, initial): def fill_with_removed_node(edges,removed,sources): filled = [False]*len(edges) q = sources new_q = [] for source in sources: if source!=removed: new_q.append(source) filled[source] = True ...
cfa4b6
a687d9
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, movie...
from sortedcontainers import SortedList class MovieRentingSystem: def __init__(self, n: int, entries: List[List[int]]): self.movies = collections.defaultdict(SortedList) self.rented = SortedList() self.map = {} for s, m, p in entries: self.movies[m].add((p, s))...
5e1c35
a687d9
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, movie...
from sortedcontainers import SortedDict class MovieRentingSystem(object): def __init__(self, n, entries): """ :type n: int :type entries: List[List[int]] """ self.Query = dict() self.Rent = SortedDict() self.Movie = dict() for shop,...
d15921
96db85
You are given an array nums consisting of positive integers. We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0. Return the length of the longest nice subarray. A subarray is a contiguous part of an array. Note that subarrays of len...
class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: n = len(nums) l, r = 0, 0 def check(l, r): for i in range(l, r): for j in range(i + 1, r + 1): if nums[i] & nums[j] != 0: return False re...
526ec3
96db85
You are given an array nums consisting of positive integers. We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0. Return the length of the longest nice subarray. A subarray is a contiguous part of an array. Note that subarrays of len...
class Solution(object): def longestNiceSubarray(self, nums): """ :type nums: List[int] :rtype: int """ cs = [0]*32 r = 1 n = len(nums) i, j = 0, 0 while i<n: v = nums[i] for k in range(31): if v&(1<<k): c...
488a91
d6bfbe
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its nex...
class Solution(object): def nextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ n2=len(nums) if n2==0: return [] n = [(nums[a] if a < n2 else nums[a-n2]) for a in range(n2*2)] g = [n[-1]] ans=[] for a in range(len(n)-2, -1, -1): while len(g) >0: if g[-1] > n[a...