problem_id
stringlengths
32
32
name
stringclasses
1 value
problem
stringlengths
200
14k
solutions
stringlengths
12
1.12M
test_cases
stringlengths
37
74M
difficulty
stringclasses
3 values
language
stringclasses
1 value
source
stringclasses
7 values
num_solutions
int64
12
1.12M
starter_code
stringlengths
0
956
98bb0f3812b1b0afd48397419871f1e5
UNKNOWN
Given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed. Return the minimum number of different frogs to finish all the croak in the given string. A valid "croak" means a frog is printing ...
["class Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n # valid string? can be seperated into full croaks:\n ### dict of letters. c, r, o, a, k should all be equal, nothing else in\n if len(croakOfFrogs)%5!=0 or croakOfFrogs[0]!='c' or croakOfFrogs[-1]!='k':\n retu...
{"fn_name": "minNumberOfFrogs", "inputs": [["\"croakcroak\""]], "outputs": [-1]}
INTERVIEW
PYTHON3
LEETCODE
29,588
class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
3da7f6497557fc97c2073a9d02f14337
UNKNOWN
We have an array A of non-negative integers. For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. Return the number of possible results.  (Results that occur more than once are only counted once in th...
["class Solution:\n def subarrayBitwiseORs(self, A: List[int]) -> int:\n res = set()\n cur = set()\n for a in A:\n cur = {a | i for i in cur}\n cur |= {a}\n res |= cur\n return len(res)", "class Solution:\n def subarrayBitwiseORs(self, A: List[int]) -> ...
{"fn_name": "subarrayBitwiseORs", "inputs": [[[0]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
44,167
class Solution: def subarrayBitwiseORs(self, A: List[int]) -> int:
9c1f54070fc92e56cb2216a7891a6e75
UNKNOWN
A string S of lowercase letters is given.  Then, we may make any number of moves. In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string. Return the lexicographically smallest string we could have after any number of moves.   Example 1: Input: S = ...
["class Solution:\n def orderlyQueue(self, S: str, K: int) -> str:\n if K >= 2:\n return ''.join(sorted(S))\n \n length = len(S)\n S = S + S\n i, j, k = 0, 1, 0\n while j + k < len(S) and k < length:\n if S[i + k] == S[j + k]:\n k += 1\n ...
{"fn_name": "orderlyQueue", "inputs": [["\"cba\"", 1]], "outputs": ["\"\"cba"]}
INTERVIEW
PYTHON3
LEETCODE
1,424
class Solution: def orderlyQueue(self, S: str, K: int) -> str:
18ebf812bbb9bfc8d8f0e709388f7d3f
UNKNOWN
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number o...
["class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n ans, count, seen = 0, 0, {}\n for i, hour in enumerate(hours):\n count = count + 1 if hour > 8 else count - 1\n if count > 0:\n ans = i + 1\n else:\n if count not in seen:...
{"fn_name": "longestWPI", "inputs": [[[9, 9, 6, 0, 6, 6, 9]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
32,740
class Solution: def longestWPI(self, hours: List[int]) -> int:
ab3a9a05ab52ce7c7c6dffad8ba02aa2
UNKNOWN
Today, the bookstore owner has a store open for customers.length minutes.  Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy.  If the bookstore owner is grumpy on the i-th minute, grumpy[i] = ...
["class Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:\n # feel like its sliding window max\n \n window, max_window = 0, 0\n \n # init first window\n for i in range(X):\n if grumpy[i]: window += customers[i]\n ma...
{"fn_name": "maxSatisfied", "inputs": [[[1, 0, 1, 2, 1, 1, 7, 5], [0, 1, 0, 1, 0, 1, 0, 1], 3]], "outputs": [16]}
INTERVIEW
PYTHON3
LEETCODE
68,622
class Solution: def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
796e0eb9da716fbec65dce0a407ff4c5
UNKNOWN
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times.  (The occurrences may overlap.) Return any duplicated substring that has the longest possible length.  (If S does not have a duplicated substring, the answer is "".)   Example 1: Input: "banana" Output: "ana" ...
["class Solution:\n def longestDupSubstring(self, S):\n nums, N = [ord(c) - ord('a') for c in S], len(S)\n BASE, MOD = 26, 2**32\n def check(L):\n cur_hash, seen = 0, set()\n for val in nums[:L]:\n cur_hash = (cur_hash * BASE + val) % MOD\n seen.ad...
{"fn_name": "longestDupSubstring", "inputs": [["\"banana\""]], "outputs": ["ana"]}
INTERVIEW
PYTHON3
LEETCODE
85,820
class Solution: def longestDupSubstring(self, S: str) -> str:
9b49eb057fc13cda0a5ac0c273fac95d
UNKNOWN
A sequence X_1, X_2, ..., X_n is fibonacci-like if: n >= 3 X_i + X_{i+1} = X_{i+2} for all i + 2 <= n Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A.  If one does not exist, return 0. (Recall that a subsequence is derived fro...
["class Solution:\n def lenLongestFibSubseq(self, A: List[int]) -> int:\n \n def getFS(x1, x2):\n F = [x1, x2]\n while F[-1] <= 1000000000:\n F.append(F[-2] + F[-1])\n return F\n\n C1 = getFS(1, 0)\n C2 = C1[1:]\n \n def getLLF...
{"fn_name": "lenLongestFibSubseq", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
170,983
class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int:
a6ac4565183f2b77135f9cbe43491239
UNKNOWN
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N −...
["class Solution(object):\n def hIndex(self, citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n n = len(citations)\n l = 0\n r = n-1\n while l <= r:\n m = (l + r) // 2\n if m == 0 and citations[m] >= n - ...
{"fn_name": "hIndex", "inputs": [[[0, 1, 3, 5, 6]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
5,609
class Solution: def hIndex(self, citations: List[int]) -> int:
0312ea0163b60448dfbd427d7efc639c
UNKNOWN
Given a string S and a string T, count the number of distinct subsequences of S which equals T. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subs...
["class Solution:\n def numDistinct(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: int\n \"\"\"\n setOft=set(t)\n news=\"\"\n for ch in s:\n if ch in setOft:\n news+=ch\n dp=[[1 for i in range(len(news...
{"fn_name": "numDistinct", "inputs": [["\"rabbbit\"", "\"rabbit\""]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
4,176
class Solution: def numDistinct(self, s: str, t: str) -> int:
fcf2e363dc13f5a0960e8cb4cf15a022
UNKNOWN
There are N dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right ...
["INF = float('inf')\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n n = len(dominoes)\n d1 = [-1] * n\n d2 = [-1] * n\n \n cnt = INF\n for i in range(n - 1, -1, -1):\n if dominoes[i] == 'L':\n cnt = 0\n elif dominoes[i...
{"fn_name": "pushDominoes", "inputs": [["\".L.R...LR..L..\""]], "outputs": ["LLL.RR.LLRRLL..."]}
INTERVIEW
PYTHON3
LEETCODE
5,838
class Solution: def pushDominoes(self, dominoes: str) -> str:
dc1b98dad73de3980014b5dbde717405
UNKNOWN
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square. Return the number of permutations of A that are squareful.  Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].   Example 1: Input: [1,17,...
["\nclass Solution:\n def numSquarefulPerms(self, A: List[int]) -> int:\n\n A.sort()\n self.ans = 0\n\n def check(A, i, path):\n return int((A[i] + path[-1])**0.5 + 0.0)**2 == A[i] + path[-1]\n\n def dfs(A, path):\n if not A:\n self.ans += 1\n ...
{"fn_name": "numSquarefulPerms", "inputs": [[[1, 17, 8]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
35,094
class Solution: def numSquarefulPerms(self, A: List[int]) -> int:
8cfc58134298f72f38a2e0cf991181c0
UNKNOWN
Given an array A of 0s and 1s, we may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1s.    Example 1: Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray i...
["class Solution:\n def longestOnes(self, A: List[int], K: int) -> int:\n hulu = []\n cnt = 0\n num = A[0]\n for x in A:\n if x == num:\n cnt += 1\n else:\n hulu.append([num,cnt])\n cnt = 1\n num = x\n ...
{"fn_name": "longestOnes", "inputs": [[[1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
85,897
class Solution: def longestOnes(self, A: List[int], K: int) -> int:
9b0b4a03eb7ace0383cddf06d0737e5c
UNKNOWN
Given a string s and an integer k. Return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are (a, e, i, o, u).   Example 1: Input: s = "abciiidef", k = 3 Output: 3 Explanation: The substring "iii" contains 3 vowel letters. Example 2: Input: s = "aeiou", k = 2 Output: 2...
["class Solution:\n def maxVowels(self, s: str, k: int) -> int:\n n = len(s)\n vowel = set(['a','e','i','o','u'])\n i=0\n res = 0\n while i<k:\n if s[i] in vowel:\n res+=1\n i+=1\n j=k\n i=0\n maxV = res\n while j<n:\...
{"fn_name": "maxVowels", "inputs": [["\"abciiidef\"", 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
33,909
class Solution: def maxVowels(self, s: str, k: int) -> int:
f3fa96086dab824f81751fd73b77dfca
UNKNOWN
Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.   Example 1: Input: A = [3,1,3,6] Output: false Example 2: Input: A = [2,1,2,6] Output: false Example 3: Input: A = [4,-2,2,-4] Output: tr...
["class Solution:\n def canReorderDoubled(self, A: List[int]) -> bool:\n cache=Counter(A)\n c_list=sorted(list(cache),key=abs)\n for x in c_list:\n if cache[x]>cache[2*x]:\n return False\n cache[2*x]-=cache[x]\n return True", "class Solution:\n def ...
{"fn_name": "canReorderDoubled", "inputs": [[[3, 1, 3, 6]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
74,189
class Solution: def canReorderDoubled(self, A: List[int]) -> bool:
96069301ca05c3204f9d564095960a5b
UNKNOWN
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanat...
["class Solution:\n def removeKdigits(self, num, k):\n \"\"\"\n :type num: str\n :type k: int\n :rtype: str\n \"\"\"\n out=[]\n for digit in num:\n while k and out and out[-1] > digit:\n out.pop()\n k-=1\n ...
{"fn_name": "removeKdigits", "inputs": [["\"1432219\"", 3]], "outputs": ["\"1219\""]}
INTERVIEW
PYTHON3
LEETCODE
3,391
class Solution: def removeKdigits(self, num: str, k: int) -> str:
481a0a87b6b810689620db7341ad7054
UNKNOWN
Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space.
["class Solution:\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = sorted(set(nums), key=lambda x: x)\n result = 0\n for i in range(len(nums)):\n if nums[i] <= 0:\n continue\n ...
{"fn_name": "firstMissingPositive", "inputs": [[[0, 1, 2, 0]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
11,655
class Solution: def firstMissingPositive(self, nums: List[int]) -> int:
b6d663a906f88e988e92d7206fa129d2
UNKNOWN
In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition. You may assume...
["class Solution:\n def findPoisonedDuration(self, timeSeries, duration):\n \"\"\"\n :type timeSeries: List[int]\n :type duration: int\n :rtype: int\n \"\"\"\n if not timeSeries:\n return 0\n prev = timeSeries[0]\n ret = 0\n count =...
{"fn_name": "findPoisonedDuration", "inputs": [[[1, 4], 2]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
6,053
class Solution: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
9a84850bd58137024105a2c92c1c6cdc
UNKNOWN
In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space.  These characters divide the square into contiguous regions. (Note that backslash characters are escaped, so a \ is represented as "\\".) Return the number of regions.   Example 1: Input: [   " /",   "/ " ] Out...
["from itertools import chain\nclass Solution:\n def regionsBySlashes(self, grid):\n grid = self.convert_grid(grid)\n print(*(list(map(str, x)) for x in grid), sep='\\\n')\n return len([self.destroy_island(x, y, grid) for y in range(len(grid)) for x,v in enumerate(grid[y]) if v == 0])\n\n @st...
{"fn_name": "regionsBySlashes", "inputs": [[["\" /\"", "\"/ \""]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
46,360
class Solution: def regionsBySlashes(self, grid: List[str]) -> int:
db00d0a2ab207f107da2679c56fe5e1c
UNKNOWN
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A and B...
["class Solution:\n def minAddToMakeValid(self, S: str) -> int:\n if not S:\n return 0\n \n stack = []\n \n add = 0\n for c in S:\n if c == '(':\n stack.append(c)\n elif c == ')':\n if stack:\n ...
{"fn_name": "minAddToMakeValid", "inputs": [["\"())\""]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
1,589
class Solution: def minAddToMakeValid(self, S: str) -> int:
37497e88e0bccd8177c5e98bff493932
UNKNOWN
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, these are arithmetic sequence: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic. 1, 1, 2, 5, 7 A zero-indexed array...
["class Solution:\n def numberOfArithmeticSlices(self, A):\n curr, sum = 0, 0\n for i in range(2,len(A)):\n if A[i]-A[i-1] == A[i-1]-A[i-2]:\n curr += 1\n sum += curr\n else:\n curr = 0\n return sum\n # solution ...
{"fn_name": "numberOfArithmeticSlices", "inputs": [[[1, 2, 3, 4]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
6,521
class Solution: def numberOfArithmeticSlices(self, A: List[int]) -> int:
c58809b097f2cb9e41fe93dc440e8d35
UNKNOWN
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.) We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'. Return the minimum number of flips to make S monotone increasing.   Examp...
["class Solution:\n def minFlipsMonoIncr(self, S: str) -> int:\n onesSoFar = 0\n partial = 0\n \n for n in S:\n if n == '0':\n partial = min(onesSoFar, partial+1) \n else:\n onesSoFar += 1\n \n return partial\n", "clas...
{"fn_name": "minFlipsMonoIncr", "inputs": [["\"00110\""]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
4,989
class Solution: def minFlipsMonoIncr(self, S: str) -> int:
de8debdc0516579b499f8d441d731ead
UNKNOWN
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
["class Solution:\n def numSubarraysWithSum(self, pl, S):\n ans = 0\n \n if(S == 0):\n c = 0\n for i in range(len(pl)):\n if(pl[i] == 0):\n c+=1\n else:\n c = 0\n ans +=c\n return ...
{"fn_name": "numSubarraysWithSum", "inputs": [[[1, 0, 1, 0, 1], 2]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
32,933
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int:
22c822bd9b2a49d378359bdd83732cc8
UNKNOWN
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Inpu...
["class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n tmax_profit = 0\n rmax_profits = [0] * len(prices)\n rmax = -1\n for ii in range(len(prices)-2, -1, -1):\n if (prices[rmax] - price...
{"fn_name": "maxProfit", "inputs": [[[3, 3, 5, 0, 0, 3, 1, 4]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
9,103
class Solution: def maxProfit(self, prices: List[int]) -> int:
439e92a20f24ae5ea5d27adb404a6ec4
UNKNOWN
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], l...
["class Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n \n \n \n # my solution ... 128 ms ... 99 % ... 17.9 MB ... 85 %\n # time: O(nlogn)\n # space: O(n)\n \n l2v = collections.defau...
{"fn_name": "largestValsFromLabels", "inputs": [[[5, 4, 3, 2, 1], [1, 1, 2, 2, 3], 3, 1]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
26,782
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
87d3ce1f367dc8d5c9d0b1d9dd6ec26c
UNKNOWN
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "c...
["class Solution:\n def frequencySort(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n counter = collections.Counter(s)\n colls = sorted(counter.items(), key=lambda k: k[1], reverse=True)\n res = ''\n for k, v in colls:\n res += k...
{"fn_name": "frequencySort", "inputs": [["\"tree\""]], "outputs": ["\"\"eetr"]}
INTERVIEW
PYTHON3
LEETCODE
5,425
class Solution: def frequencySort(self, s: str) -> str:
ee5567f71e262f8118c18f481af0b1ee
UNKNOWN
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and onl...
["class Solution:\n def move(self, pos, direction):\n x, y = pos\n if direction == 0:\n y += 1\n elif direction == 1:\n x += 1\n elif direction == 2:\n y -= 1\n elif direction == 3:\n x -= 1\n return (x, y)\n \n def isRobotBo...
{"fn_name": "isRobotBounded", "inputs": [["\"GGLLGG\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
5,491
class Solution: def isRobotBounded(self, instructions: str) -> bool:
3895450827f6f8fad8bac2799d7d931c
UNKNOWN
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining ele...
["class Solution:\n def isvalid(self,C):\n if len(C)>2:\n return False\n if len(C)==1:\n a = min(C)\n if a==1 or C[a]==1:\n # EXPLANATION:\n # a==1 : All lengths are unitary like A=[1,2,3,4,...], so poping anything is fine\n ...
{"fn_name": "maxEqualFreq", "inputs": [[[2, 2, 1, 1, 5, 3, 3, 5]]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
66,918
class Solution: def maxEqualFreq(self, nums: List[int]) -> int:
f8a300ae6f214e5600cd5c4f77c42439
UNKNOWN
On a table are N cards, with a positive integer printed on the front and back of each card (possibly different). We flip any number of cards, and after we choose one card.  If the number X on the back of the chosen card is not on the front of any card, then this number X is good. What is the smallest number that is goo...
["class Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n w = set(fronts[i] for i in range(len(fronts)) if fronts[i] == backs[i])\n \n x = set()\n for a in fronts:\n if a not in w:\n x.add(a)\n for a in backs:\n if a ...
{"fn_name": "flipgame", "inputs": [[[1, 2, 4, 4, 7], [1, 3, 4, 1, 3]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
11,208
class Solution: def flipgame(self, fronts: List[int], backs: List[int]) -> int:
4b4e3bc86da79cff1441fdd1cb289be9
UNKNOWN
Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It's guaranteed that you can always reach to one for all testcases.   Example 1...
["class Solution:\n def numSteps(self, s: str) -> int:\n i, mid_zero = 0 , 0 \n for j in range(1, len(s)):\n if s[j] == '1':\n mid_zero += j -i - 1\n i = j\n if i == 0:\n return len(s)-1\n return mid_zero + 1 + len(s)\n"]
{"fn_name": "numSteps", "inputs": [["\"1101\""]], "outputs": [8]}
INTERVIEW
PYTHON3
LEETCODE
304
class Solution: def numSteps(self, s: str) -> int:
1745b88e4d86d5910f221e09ebc1cc92
UNKNOWN
Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4. However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the correspo...
["class Solution:\n def optimalDivision(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: str\n \"\"\"\n if(len(nums) == 0):\n return ''\n if(len(nums) == 1):\n return str(nums[0])\n if(len(nums) == 2):\n return str(nu...
{"fn_name": "optimalDivision", "inputs": [[[1000, 100, 10, 2]]], "outputs": ["1000/(100/10/2)"]}
INTERVIEW
PYTHON3
LEETCODE
6,848
class Solution: def optimalDivision(self, nums: List[int]) -> str:
2de459674c1ae0efce9b0dbd90260376
UNKNOWN
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another. Now, given a dictionary consisting of many roots and a sentence. You need to replace al...
["class Solution:\n def replaceWords(self, dt, sentence):\n \"\"\"\n :type dict: List[str]\n :type sentence: str\n :rtype: str\n \"\"\"\n trie = {}\n for w in dt:\n t = trie\n for c in w:\n if c not in t: t[c] = {}\n ...
{"fn_name": "replaceWords", "inputs": [[["\"cat\"", "\"bat\"", "\"rat\""], "\"the cattle was rattled by the battery\""]], "outputs": ["\"the cattle was rattled by the battery\""]}
INTERVIEW
PYTHON3
LEETCODE
5,386
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str:
1b3291ff72af45552424b6aaa7be6f6c
UNKNOWN
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required su...
["class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n i, window, result = 0, 0, float('inf')\n premin = [float('inf')]*len(arr)\n for j, num in enumerate(arr):\n window += num\n while window > target:\n window -= arr[i]\n ...
{"fn_name": "minSumOfLengths", "inputs": [[[3, 2, 2, 4, 3], 3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
173,469
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int:
b9b8dfd7fd6268cb8e32294fd05434c2
UNKNOWN
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions ...
["class Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n n = len(grid)\n m = len(grid[0])\n \n F = [i for i in range(m * n)]\n def find(x):\n if x == F[x]:\n return x\n else:\n F[x] = find(F[x])\n ...
{"fn_name": "containsCycle", "inputs": [[[["\"a\"", "\"a\"", "\"a\"", "\"a\""], ["\"a\"", "\"b\"", "\"b\"", "\"a\""], ["\"a\"", "\"b\"", "\"b\"", "\"a\""], ["\"a\"", "\"a\"", "\"a\"", "\"a\""], [], []]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
119,393
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool:
d34d475d2acdfb1b875ae64c6f675373
UNKNOWN
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).   Example 1: Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6...
["class Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n # slide window and call isMagicSquare\n if len(grid) < 3 or len(grid[0]) < 3:\n return 0\n rows = len(grid)\n cols = len(grid[0])\n magic_squares = 0\n for i in range(rows - 2):\n...
{"fn_name": "numMagicSquaresInside", "inputs": [[[[4, 3, 8, 4], [9, 5, 1, 9], [2, 7, 6, 2], [], []]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
2,811
class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
2462bf6dfb9ca05467748a20a85f5ce0
UNKNOWN
There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Now we want to hire exactly K workers to form a paid group.  When hiring a group of K workers, we must pay them according to the following rules: Every worker in the paid group should be paid in the ratio of their quality co...
["from typing import *\nfrom heapq import heappop, heappush\n\n\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:\n N = len(quality)\n heap_quality = []\n workers = [i for i in range(N)]\n workers = sorted(workers, key=lambda x: wage[...
{"fn_name": "mincostToHireWorkers", "inputs": [[[10, 20, 5], [70, 50, 30], 2]], "outputs": [105.0]}
INTERVIEW
PYTHON3
LEETCODE
61,778
class Solution: def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
b9747b308c1974a87e1e850dee12f0e8
UNKNOWN
Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n.  For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of o...
["class Solution:\n def clumsy(self, N: int) -> int:\n if N <= 2:\n return N\n if N <= 4:\n return N + 3\n \n if (N - 4) % 4 == 0:\n return N + 1\n elif (N - 4) % 4 <= 2:\n return N + 2\n else:\n return N - 1", "class So...
{"fn_name": "clumsy", "inputs": [[4]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
21,290
class Solution: def clumsy(self, N: int) -> int:
110296a4a12106b7c2b181722ff3e399
UNKNOWN
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th t...
["class Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n for i,r in enumerate(ranges):\n l = max(0,i-r)\n ranges[l] = max(i+r, ranges[l])\n \n res = lo = hi = 0 \n while hi < n:\n lo, hi = hi, max(ranges[lo:hi+1])\n ...
{"fn_name": "minTaps", "inputs": [[5, [3, 4, 1, 1, 0, 0]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
81,910
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int:
73b4a40a3a166cbe366a4d2269d64388
UNKNOWN
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time . Given an integer array representing ...
["class Solution:\n def findMinMoves(self, machines):\n \"\"\"\n :type machines: List[int]\n :rtype: int\n \"\"\"\n if sum(machines) % len(machines) != 0:\n return -1\n mean = sum(machines) // len(machines)\n cum, step = 0, 0\n for x in mac...
{"fn_name": "findMinMoves", "inputs": [[[1, 0, 5]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
5,894
class Solution: def findMinMoves(self, machines: List[int]) -> int:
67f12ebbfab21793cb44cc8c8ed3d1b5
UNKNOWN
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. Example: Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99]) Credits:Special thanks to @memoryless for adding this problem and creating all...
["class Solution:\n def countNumbersWithUniqueDigits(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n ls = [1,10,91]\n mul = 9\n \n res = 0\n for i in range(8):\n mul = 9\n m = 9\n for j in range(i+...
{"fn_name": "countNumbersWithUniqueDigits", "inputs": [[2]], "outputs": [91]}
INTERVIEW
PYTHON3
LEETCODE
3,444
class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int:
a137b6834fc685e97cd20b8efc9c914f
UNKNOWN
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minimum ...
["class Solution:\n def jump(self,nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return 0\n else:\n step = 0\n pos = 0\n while pos != len(nums) - 1:\n bestStep = -1\...
{"fn_name": "jump", "inputs": [[[2, 3, 1, 1, 4]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
7,788
class Solution: def jump(self, nums: List[int]) -> int:
0a94519d9ce58fb36f862b0868ff7a9d
UNKNOWN
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas...
["class Solution:\n def minEatingSpeed(self, piles: List[int], H: int) -> int:\n bananas = sum(piles)\n K = bananas // H + (bananas % H != 0)\n while True:\n hours_needed = 0\n for pile in piles:\n hours_needed += pile // K\n if pile % K != 0:\...
{"fn_name": "minEatingSpeed", "inputs": [[[3, 6, 7, 11], 8]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
125,493
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int:
9636d9f190eb1f8bca671637d48e5086
UNKNOWN
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of succes...
["class Solution:\n def maxProbability(self, n: int, edges: List[List[int]], probs: List[float], s: int, t: int) -> float:\n # first build the graph\n graph = {u: {} for u in range(n)}\n for (u, v), prob in zip(edges, probs):\n graph[u][v] = prob\n graph[v][u] = prob\n\n ...
{"fn_name": "maxProbability", "inputs": [[3, [[0, 1], [1, 2], [0, 2], [], []], [0.5, 0.5, 0.2], 0, 2]], "outputs": [0.25]}
INTERVIEW
PYTHON3
LEETCODE
39,517
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
d90422a1c0712fd7020f1a9d67205dc2
UNKNOWN
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are no...
["class Solution:\n def originalDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n dmap={}\n dmap[0]=s.count('z')\n dmap[2]=s.count('w')\n dmap[4]=s.count('u')\n dmap[6]=s.count('x')\n dmap[8]=s.count('g')\n dmap[...
{"fn_name": "originalDigits", "inputs": [["\"owoztneoer\""]], "outputs": ["012"]}
INTERVIEW
PYTHON3
LEETCODE
27,915
class Solution: def originalDigits(self, s: str) -> str:
ee64b81da173198c7b103f2fc239b302
UNKNOWN
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest inte...
["import numpy as np\nimport math\n\nclass Solution:\n \n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n if len(nums) == 1:\n return int(math.ceil(nums[0]/threshold))\n \n np_nums = np.array(nums) \n low, high = 1, np.max(np_nums)\n \n div...
{"fn_name": "smallestDivisor", "inputs": [[[1, 2, 5, 9], 6]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
86,551
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int:
c6b726602c77a65179187c472a62fc8a
UNKNOWN
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1,7,4,9,2,5] ...
["class Solution:\n def wiggleMaxLength(self, arr):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(arr)\n if n < 2:\n return n\n wsl = [0]*n\n wsl[0] = 1\n for cur in range(1, n):\n prev = cur - 1 ...
{"fn_name": "wiggleMaxLength", "inputs": [[[1, 7, 4, 9, 2, 5]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
8,519
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int:
19b5f5fa6894984f12daa11dcdaba326
UNKNOWN
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's len...
["class Solution:\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n nums = sorted(nums, reverse=True)\n return nums[k - 1]", "class Solution:\n def findKthLargest(self, nums, k):\n \"\"\"\...
{"fn_name": "findKthLargest", "inputs": [[[2, 1, 3, 4, 5, 6], 2]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
4,116
class Solution: def findKthLargest(self, nums: List[int], k: int) -> int:
372827b5bf9eae8bd7e03641a77c3374
UNKNOWN
Given an equation, represented by words on left side and the result on right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). Every pair of different characters they must map to different digits. Each words[i] and result are decoded as one n...
["class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n longest_word = max([len(word) for word in words])\n if len(result) != longest_word and len(result) != longest_word + 1:\n return False\n \n result_indices = []\n acc = 0\n all_chars...
{"fn_name": "isSolvable", "inputs": [[["\"SEND\"", "\"MORE\""], "\"MONEY\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
83,954
class Solution: def isSolvable(self, words: List[str], result: str) -> bool:
a1d264eeef0901daea59b5ef989aa19d
UNKNOWN
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagra...
["class Solution:\n dp = [[1] * 10]\n def knightDialer(self, n: int) -> int:\n MOD = 10 ** 9 + 7\n jump = [[4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [], [0, 1, 7], [2, 6], [1, 3], [2, 4]]\n for i in range(len(self.dp), n):\n new = [0] * 10\n for j in range(10):\n ...
{"fn_name": "knightDialer", "inputs": [[1]], "outputs": [10]}
INTERVIEW
PYTHON3
LEETCODE
482,271
class Solution: def knightDialer(self, n: int) -> int:
6136437b8e749b5a14231683760c9bf5
UNKNOWN
Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters. Return the maximum possible length of s.   Example 1: Input: arr = ["un","iq","ue"] Output: 4 Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique". Maximum length is 4. Example ...
["class Solution:\n def maxLength(self, arr: List[str]) -> int:\n def digit_representation(s):\n ans = 0\n for c in s:\n ans |= 1<<(ord(c)-ord('a'))\n return ans\n \n A = sorted([(len(s), digit_representation(s)) for s in set(arr) if len(set(s))==l...
{"fn_name": "maxLength", "inputs": [[["\"un\"", "\"iq\"", "\"ue\""]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
84,019
class Solution: def maxLength(self, arr: List[str]) -> int:
727d4056e01ef75e23fa92df3f5d0755
UNKNOWN
Given an array nums and an integer target. Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.   Example 1: Input: nums = [1,1,1,1,1], target = 2 Output: 2 Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to targ...
["class Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n sum_set = set()\n sum_set.add(0)\n temp = 0\n count = 0\n for num in nums:\n temp += num\n if temp - target in sum_set:\n count += 1\n sum_set...
{"fn_name": "maxNonOverlapping", "inputs": [[[1, 1, 1, 1, 1], 2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
74,955
class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int:
6521cb609b43eee0ea9fa45167de8181
UNKNOWN
You are given a string s, a split is called good if you can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are the same. Return the number of good splits you can make in s.   Example 1: Input: s = "aacaba" Output: 2 Explanation: There are 5 w...
["class Solution:\n def numSplits(self, s: str) -> int:\n left = [0]*len(s)\n \n unique = set()\n n_distinct = 0\n for i, l in enumerate(s):\n if l not in unique:\n unique.add(l)\n n_distinct += 1\n left[i] = n_distinct\n \...
{"fn_name": "numSplits", "inputs": [["\"aacaba\""]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
60,813
class Solution: def numSplits(self, s: str) -> int:
41c033e1758595a82b8dc339062c7f79
UNKNOWN
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would al...
["class Solution:\n def evalRPN(self, tokens):\n \"\"\"\n :type tokens: List[str]\n :rtype: int\n \"\"\"\n s = []\n for token in tokens:\n if token == \"+\":\n a = int(s.pop())\n b = int(s.pop())\n s.append(a+b)\n elif token == \"/\":\n a = int(s.pop...
{"fn_name": "evalRPN", "inputs": [[["\"2\"", "\"1\""]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
717
class Solution: def evalRPN(self, tokens: List[str]) -> int:
00de5a9dcd0824c9ef7b175d604661e4
UNKNOWN
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). The returned string must have no leading zeroes, unless the string is "0".   Example 1: Input: 2 Output: "110" Explantion: (-2) ^ 2 + (-2) ^ 1 = 2 Example 2: Input: 3 Output: "111" Explantion: (-2) ^ 2 ...
["class Solution:\n def baseNeg2(self, N: int) -> str:\n # res = []\n # x = N\n # while x:\n # res.append(x & 1)\n # x = -(x >> 1)\n # return \\\"\\\".join(map(str, res[::-1] or [0]))\n \n neg = [1 << i for i in range(1, 33, 2)]\n for mask in neg...
{"fn_name": "baseNeg2", "inputs": [[2]], "outputs": ["110"]}
INTERVIEW
PYTHON3
LEETCODE
799
class Solution: def baseNeg2(self, N: int) -> str:
ce0c8d708c81f6abab5653b00215363a
UNKNOWN
Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.   Example 1: Input: nums = [1,0,0,0,1,0,0,1], k = 2 Output: true Explanation: Each of the 1s are at least 2 places away from each other. Example 2: Input: nums = [1,0,0,1,0,1]...
["class Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n \n if nums.count(0) == len(nums):\n return True\n \n idx = nums.index(1)\n ctr = 0\n for num in nums[idx+1:]:\n if num == 1:\n if ctr < k:\n ...
{"fn_name": "kLengthApart", "inputs": [[[1, 0, 0, 0, 1, 0, 0, 1], 2]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
35,318
class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool:
56629c1956a8013da866f588b1b1462b
UNKNOWN
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two in...
["import math\n\nclass Solution:\n def __init__(self):\n self.happy_string = ''\n \n def getHappyString(self, n: int, k: int) -> str:\n # determine starting character\n poss_per_group = 2 ** (n - 1)\n group_num = math.ceil(k / poss_per_group) - 1\n starting_char = ''\n ...
{"fn_name": "getHappyString", "inputs": [[1, 3]], "outputs": ["c"]}
INTERVIEW
PYTHON3
LEETCODE
16,974
class Solution: def getHappyString(self, n: int, k: int) -> str:
0e52b74f228a894351d28e0baef0f8fd
UNKNOWN
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 ...
["class Solution:\n def canJump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n \n can = True\n smallest_idx = n - 1\n \n for i in range(n - 2, -1, -1):\n can = i + nums[i] >= smallest...
{"fn_name": "canJump", "inputs": [[[2, 3, 1, 1, 4]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
7,734
class Solution: def canJump(self, nums: List[int]) -> bool:
4c4c47dd1bf27faa5a79fec75ca74790
UNKNOWN
Given n boxes, each box is given in the format [status, candies, keys, containedBoxes] where: status[i]: an integer which is 1 if box[i] is open and 0 if box[i] is closed. candies[i]: an integer representing the number of candies in box[i]. keys[i]: an array contains the indices of the boxes you can open with the key ...
["class Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n # nested boxes\n reachable=[False]*len(status)\n visited=[False]*len(status)\n for box in initialBoxes:\n r...
{"fn_name": "maxCandies", "inputs": [[[1, 1, 1, 0], [7, 5, 4, 100], [[], [], [1], [], [], []], [[1, 2], [3], [], [], [], []], [0]]], "outputs": [16]}
INTERVIEW
PYTHON3
LEETCODE
100,946
class Solution: def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
0230e0ba6cfd0707fb74d6d98818d3e5
UNKNOWN
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you g...
["class Solution:\n dp = {0: 0}\n def racecar(self, target: int) -> int:\n if target in self.dp:\n return self.dp[target]\n n = target.bit_length()\n if 2**n - 1 == target:\n self.dp[target] = n\n else:\n self.dp[target] = self.racecar(2**n - 1 - target...
{"fn_name": "racecar", "inputs": [[3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
137,700
class Solution: def racecar(self, target: int) -> int:
48036f0bc36280f356e849563b7b1481
UNKNOWN
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum...
["from collections import deque\nclass Solution:\n def longestSubarray(self, nums, limit):\n maxQ, minQ = deque(), deque()\n i = 0\n res = 0\n for j, val in enumerate(nums):\n while maxQ and val > maxQ[-1]: maxQ.pop()\n while minQ and val < minQ[-1]: minQ.pop()\n ...
{"fn_name": "longestSubarray", "inputs": [[[8, 2, 4, 7], 4]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
312,534
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int:
6480c79e033a6d3ebcb4ab2e4bfa381d
UNKNOWN
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left paren...
["class Solution:\n def checkValidString(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n low, high = 0, 0\n for c in s:\n if c == \"(\":\n low += 1\n high += 1\n elif c == \")\":\n if ...
{"fn_name": "checkValidString", "inputs": [["\"()\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
5,434
class Solution: def checkValidString(self, s: str) -> bool:
9f6de61da3eee4ebe820a7d74866feef
UNKNOWN
Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand. Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3...
["class Solution:\n def findMinStep(self, board, hand):\n \"\"\"\n :type board: str\n :type hand: str\n :rtype: int\n \"\"\"\n res=float(\"inf\")\n hmap=collections.defaultdict(int)\n for c in hand:\n hmap[c]+=1\n res=self.helper(bo...
{"fn_name": "findMinStep", "inputs": [["\"WRRBBW\"", "\"RB\""]], "outputs": [-1]}
INTERVIEW
PYTHON3
LEETCODE
5,776
class Solution: def findMinStep(self, board: str, hand: str) -> int:
952015f4af19871578a875fa8e56827d
UNKNOWN
There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. Initially, all the bulbs are turned off. At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too. Return the number...
["class Solution:\n def numTimesAllBlue(self, light: List[int]) -> int:\n right = 0\n ans = 0\n for i in range(len(light)):\n if (light[i] > right):\n right = light[i]\n \n if (i + 1 == right):\n ans += 1\n \n r...
{"fn_name": "numTimesAllBlue", "inputs": [[[2, 1, 3, 5, 4]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
55,739
class Solution: def numTimesAllBlue(self, light: List[int]) -> int:
a15d8babed8edc853f4e656f32dcaa8f
UNKNOWN
Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. Since the answer may not fit in an integer data type, return the answer as a string. If there is no answer return an empty string.   Example 1: Input: digits = [8,1,9] Output...
["class Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n counts = Counter(digits)\n m = sum(digits) % 3\n if m:\n if counts[m] + counts[m+3] + counts[m+6]:\n counts[min([m+i for i in [0,3,6] if counts[m+i]])] -= 1\n else:\n ...
{"fn_name": "largestMultipleOfThree", "inputs": [[[9, 8, 1]]], "outputs": ["981"]}
INTERVIEW
PYTHON3
LEETCODE
18,500
class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str:
15ca8ca4ad75bac6827e1f95d606c2ae
UNKNOWN
The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Give...
["class Solution:\n def getPermutation(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n nums = list(\"123456789\")\n k -= 1\n factor = 1\n for i in range(1, n):\n factor *= i\n res = []\n ...
{"fn_name": "getPermutation", "inputs": [[3, 3]], "outputs": ["213"]}
INTERVIEW
PYTHON3
LEETCODE
9,552
class Solution: def getPermutation(self, n: int, k: int) -> str:
674311d23f02fa6a387dfe00c8638644
UNKNOWN
You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is palindrome. Return the minimal number of characters that you need to change to div...
["from functools import lru_cache\nclass Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n n = len(s)\n if n == k:\n return 0\n @lru_cache(None)\n def cnt(left,right): # cost to make palindrome\n if left >= right:\n return 0\n ...
{"fn_name": "palindromePartition", "inputs": [["\"abc\"", 2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
62,268
class Solution: def palindromePartition(self, s: str, k: int) -> int:
56e340dc8d4dd084e15b56a8ce2d2547
UNKNOWN
Given two strings s and t, your goal is to convert s into t in k moves or less. During the ith (1 <= i <= k) move you can: Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times. Do nothing. Shifting a character...
["class Solution:\n def canConvertString(self, s: str, t: str, k: int) -> bool:\n if len(s) != len(t):\n return False\n \n c = Counter((ord(c2) - ord(c1)) % 26 for c1, c2 in zip(s, t))\n return k >= max(\n (m + 26 * (count - 1) for m, count in list(c.items()) if m),\...
{"fn_name": "canConvertString", "inputs": [["\"input\"", "\"ouput\"", 9]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
62,583
class Solution: def canConvertString(self, s: str, t: str, k: int) -> bool:
db049917eab9f340b1c09834f4778672
UNKNOWN
Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.   Example 1: Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 Output: 2 Explanation: The maximum side length of s...
["class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n dp = [[0 for _ in range(len(mat[0]) + 1)]for r in range(len(mat) + 1)]\n \n for r in range(1, len(mat) + 1):\n for c in range(1, len(mat[r-1]) + 1):\n dp[r][c] += mat[r-1][c-1]\n...
{"fn_name": "maxSideLength", "inputs": [[[[1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2], [], []], 4]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
1,362
class Solution: def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
a496d079a0506a47798e00ebd962d341
UNKNOWN
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. Example 1: Input: nums = [1,3,1] k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pa...
["class Solution:\n def smallestDistancePair(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n nums.sort()\n l, r = 0, nums[-1] - nums[0]\n \n while l < r:\n m = l + (r - l) // 2\n ...
{"fn_name": "smallestDistancePair", "inputs": [[[1, 1, 3], 1]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
1,312
class Solution: def smallestDistancePair(self, nums: List[int], k: int) -> int:
222c6d115df465bade5652f009aa2d8f
UNKNOWN
You have an initial power P, an initial score of 0 points, and a bag of tokens. Each token can be used at most once, has a value token[i], and has potentially two ways to use it. If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point. If we have at least 1 point, ...
["class Solution:\n def bagOfTokensScore(self, tokens: List[int], P: int) -> int:\n tokens = sorted(tokens)\n left = 0\n right = len(tokens) - 1\n points = 0\n\n if len(tokens) == 1:\n if tokens[0] <= P:\n return 1\n if len(tokens) == 0:\n ...
{"fn_name": "bagOfTokensScore", "inputs": [[[100], 50]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
9,877
class Solution: def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
e56962ec9c27f9f69d45747ae3552494
UNKNOWN
Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once). After this process, we have some array B. Return the smallest possible difference between the maximum value of B and the minimum value of B.   Example 1: Input: A = [1], K = 0 Output: 0 Explan...
["class Solution:\n def smallestRangeII(self, A: List[int], K: int) -> int:\n if not A:\n return 0\n nums = sorted([num + K for num in set(A)], reverse=True)\n max_num = nums[0]\n min_num = nums[-1]\n changed_max = max_num - 2 * K\n res = max_num - min_num\n ...
{"fn_name": "smallestRangeII", "inputs": [[[1], 0]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
11,118
class Solution: def smallestRangeII(self, A: List[int], K: int) -> int:
857204471655dde5b5265e9ed64cf281
UNKNOWN
Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.  All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanatio...
["from math import comb\n\n\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = len(balls)\n s = sum(balls)\n s2 = s // 2\n\n @lru_cache(None)\n def count(index, delta, ca):\n if index == n: return 1 if delta == 0 and ca == s2 else 0\n ...
{"fn_name": "getProbability", "inputs": [[[1, 1]]], "outputs": [1.0]}
INTERVIEW
PYTHON3
LEETCODE
81,077
class Solution: def getProbability(self, balls: List[int]) -> float:
4a9c8861be4fd2e5b4aa175452d5e1b3
UNKNOWN
Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 The number at the ith position is divisible by i. i is divisible by the number at the ith position. Now given N, how man...
["class Solution:\n def countArrangement(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n d = {\n 1:1, 2:2, 3:3, 4:8, 5:10, 6:36,\n 7:41, 8:132, 9:250, 10:700,\n 11:750, 12:4010, 13:4237, 14:10680, 15:24679\n }\n ...
{"fn_name": "countArrangement", "inputs": [[2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
2,375
class Solution: def countArrangement(self, N: int) -> int:
eaee462da265a874003a31afc1c4fa5c
UNKNOWN
There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be. Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons ar...
["class Solution:\n def flipLights(self, n, m):\n \"\"\"\n :type n: int\n :type m: int\n :rtype: int\n \"\"\"\n states = set()\n for op_odd in [0, 1]:\n for op_even in [0, 1]:\n for op_third in [0, 1]:\n op_all =...
{"fn_name": "flipLights", "inputs": [[1, 1]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
9,130
class Solution: def flipLights(self, n: int, m: int) -> int:
8562a76b3a7191e26cd289b5f3a426b8
UNKNOWN
Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M.  (For clarification, the L-length subarray could occur before or after the M-length subarray.) Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+...
["class Solution:\n def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:\n N = len(A)\n if L+M>N:\n return -1\n\n\n def findmax(L,M): \n sL = [sum(A[:L])]\n for i in range(L,N-M):\n tmp = sL[-1]+A[i]-A[i-L]\n sL.appe...
{"fn_name": "maxSumTwoNoOverlap", "inputs": [[[0, 6, 5, 2, 2, 5, 1, 9, 4], 1, 2]], "outputs": [20]}
INTERVIEW
PYTHON3
LEETCODE
108,693
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
36410ed8fd08ef14b9fa4fc1991cd3bc
UNKNOWN
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost ...
["class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts.sort()\n from functools import lru_cache\n @lru_cache(None)\n def helper(i = 0, j = n):\n ans = math.inf\n for c in cuts:\n if c <= i: continue\n if c >= j: br...
{"fn_name": "minCost", "inputs": [[7, [1, 3, 4, 5, 0, 7]]], "outputs": [16]}
INTERVIEW
PYTHON3
LEETCODE
48,153
class Solution: def minCost(self, n: int, cuts: List[int]) -> int:
da864a5aee7de0fc741ea2df6f43be65
UNKNOWN
Given an array of integers arr. Return the number of sub-arrays with odd sum. As the answer may grow large, the answer must be computed modulo 10^9 + 7.   Example 1: Input: arr = [1,3,5] Output: 4 Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,8,5]. Odd sums are [1,9,3...
["class Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n mod = 10**9+7\n odd_presum_cnt = 0\n par = 0\n for a in arr:\n par ^= a & 1\n if par:\n odd_presum_cnt += 1\n return odd_presum_cnt * (len(arr)+1 - odd_presum_cnt)%mod", "cla...
{"fn_name": "numOfSubarrays", "inputs": [[[1, 3, 5]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
80,497
class Solution: def numOfSubarrays(self, arr: List[int]) -> int:
af3af4be19bfa29f525b7d03372cf31a
UNKNOWN
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,-...
["# https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/340075/c%2B%2B-beats-100-(both-time-and-memory)-with-algorithm-and-image\nclass Solution:\n def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:\n N = len(arr1)\n a = [arr1[i] + arr2[i] + i for i in range(N)]\n ...
{"fn_name": "maxAbsValExpr", "inputs": [[[1, 2, 3, 4], [-1, 4, 5, 6]]], "outputs": [13]}
INTERVIEW
PYTHON3
LEETCODE
41,878
class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
73d1edc2e639684dcced004600fbc478
UNKNOWN
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. However, there is a non-negative ...
["class Solution:\n def leastInterval(self, tasks, n):\n \"\"\"\n :type tasks: List[str]\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0: return len(tasks)\n from collections import Counter\n counter = Counter(tasks)\n window = n + 1\n ...
{"fn_name": "leastInterval", "inputs": [[["\"A\"", "\"A\"", "\"A\"", "\"B\"", "\"B\"", "\"B\""], 2]], "outputs": [8]}
INTERVIEW
PYTHON3
LEETCODE
1,576
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int:
ba13ca7e2fb22444236904158892fe9e
UNKNOWN
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example: Input: 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown below...
["class Solution:\n def totalNQueens(self, n):\n def dfs(lst, xy_dif, xy_sum):\n p=len(lst)\n if p==n: res.append(lst)\n for q in range(n):\n if (q not in lst) and (p-q not in xy_dif) and (p+q not in xy_sum):\n dfs(lst+[q], xy_dif+[p-q]...
{"fn_name": "totalNQueens", "inputs": [[4]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
10,069
class Solution: def totalNQueens(self, n: int) -> int:
60be4176d03387cccdf84b5af479b866
UNKNOWN
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on. In other words, after each move your direction changes counter-clockwise. Write a one-pass algorithm w...
["class Solution:\n def isSelfCrossing(self, x):\n \"\"\"\n :type x: List[int]\n :rtype: bool\n \"\"\"\n if not x or len(x) < 4:\n return False\n i = 3\n while i < len(x):\n #print(i)\n if x[i] >= x[i-2] and x[i-1] <= x[i-3]...
{"fn_name": "isSelfCrossing", "inputs": [[[2, 1, 1, 2]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
2,523
class Solution: def isSelfCrossing(self, x: List[int]) -> bool:
4ecb7c0683f6814ac7075ee056add57c
UNKNOWN
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 Example 2: Input: [2,2,2,0,1] Output: 0 Note: This is ...
["class Solution:\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n min = nums[0]\n start, end = 0, len(nums) - 1\n while start<end:\n mid = (start+end)//2\n if nums[mid]>nums[end]:\n s...
{"fn_name": "findMin", "inputs": [[[1, 3, 5]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
7,205
class Solution: def findMin(self, nums: List[int]) -> int:
f1c61ae229d120223580551232abe20f
UNKNOWN
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA...
["class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n res = 0\n freqs = [f + 1 for f in Counter(tiles).values()]\n for t in itertools.product(*map(range, freqs)):\n n = sum(t)\n subtotal = math.factorial(n)\n for freq in t:\n sub...
{"fn_name": "numTilePossibilities", "inputs": [["\"AAB\""]], "outputs": [89]}
INTERVIEW
PYTHON3
LEETCODE
38,631
class Solution: def numTilePossibilities(self, tiles: str) -> int:
6c6d67ae84e4af44ee8a736501019ca7
UNKNOWN
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. ...
["class Solution:\n def multiply(self,num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n a=['0','1','2','3','4','5','6','7','8','9']\n z=0\n x=0\n for i,element in enumerate(num1):\n for j in range(10...
{"fn_name": "multiply", "inputs": [["\"2\"", "\"3\""]], "outputs": ["600"]}
INTERVIEW
PYTHON3
LEETCODE
2,112
class Solution: def multiply(self, num1: str, num2: str) -> str:
f55a5844bcc4b879ab5d93031cdc7015
UNKNOWN
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to gr...
["from collections import deque\n\nclass Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0)\n \n direction_map = {\n 1: right,\n 2: left,\n 3: down,\n 4: up\n }\n \n ...
{"fn_name": "minCost", "inputs": [[[[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2], [], []]]], "outputs": [-1]}
INTERVIEW
PYTHON3
LEETCODE
1,489
class Solution: def minCost(self, grid: List[List[int]]) -> int:
332e036a5acd30a53b391c2dac02f51d
UNKNOWN
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:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n def dp(i, j):\n if i==0: return 2*j\n # if j==0: return 0\n if j==1: return 2\n if (i, j) in memo: return memo[(i, j)]\n base = x**i\n q, r = divmod(j, base)\n ...
{"fn_name": "leastOpsExpressTarget", "inputs": [[3, 19]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
7,260
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int:
50024000b4a7d644bb92da39ad55a180
UNKNOWN
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines...
["class Solution:\n def maxUncrossedLines(self, A, B):\n # Optimization\n #commons = set(A).intersection(set(B)) # or commons = set(A) & set(B)\n #A = [x for x in A if x in commons]\n #B = [x for x in B if x in commons]\n\n N1, N2 = len(A), len(B)\n dp = [[0 for _ in range(N...
{"fn_name": "maxUncrossedLines", "inputs": [[[1, 4, 2], [1, 2, 4]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
78,604
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
7b121b1f512c1c6bedd0471d07b50c8e
UNKNOWN
Given the coordinates of four points in 2D space, return whether the four points could construct a square. The coordinate (x,y) of a point is represented by an integer array with two integers. Example: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True Note: All the input integers are in the ra...
["class Solution:\n def validSquare(self, p1, p2, p3, p4):\n \"\"\"\n :type p1: List[int]\n :type p2: List[int]\n :type p3: List[int]\n :type p4: List[int]\n :rtype: bool\n \"\"\"\n \n def length(x,y):\n return (x[0]-y[0])*(x[0]-y[0...
{"fn_name": "validSquare", "inputs": [[[0, 0], [1, 1], [1, 0], [0, 1]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
10,977
class Solution: def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
2932fa2ea11b3355dcf1ea29666f581e
UNKNOWN
Given an integer array arr, you should partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning.   Example 1: Input: arr = [1,15,7,9,2,5,10], ...
["class Solution:\n def maxSumAfterPartitioning(self, arr, k):\n res = [0]\n \n for idx, val in enumerate(arr):\n max_val, cur_val = 0, 0\n \n for i in range(max(0, idx-k+1), idx+1)[::-1]:\n \n if arr[i] > max_val:\n ...
{"fn_name": "maxSumAfterPartitioning", "inputs": [[[1, 15, 7, 9, 2, 5, 10], 3]], "outputs": [84]}
INTERVIEW
PYTHON3
LEETCODE
139,182
class Solution: def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
68dc209d358cebaf5cf550ff59be5687
UNKNOWN
Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.  Person A will NOT friend request person B (B != A) if any of the following conditions are true: age[B] <= 0.5 * age[A] + 7 age[B] > age[A] age[B] > 100 && age[A] < 100 Otherwise, A will friend request B. ...
["class Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n count = [0]*121\n s = [0]*121\n for a in ages:\n count[a]+=1\n for i in range(1,121):\n s[i] = s[i-1]+count[i]\n res = 0\n for i in range(15,121):\n edge = i//2+7\n ...
{"fn_name": "numFriendRequests", "inputs": [[[16, 16]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
72,321
class Solution: def numFriendRequests(self, ages: List[int]) -> int:
67863c10995e451a0bd935b22cf621cc
UNKNOWN
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).   Example 1: Input: text = "abcabcabc" Output: 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". Example 2: Input: ...
["# class Solution:\n# def distinctEchoSubstrings(self, text: str) -> int:\n# ans = set()\n \n# for i in range(len(text)-1): \n# for j in range(i+1, (i+len(text))//2+1): \n# if text[i:j] == text[j:2*j-i]: ans.add(text[i:j])\n \n# return len(ans)\nfro...
{"fn_name": "distinctEchoSubstrings", "inputs": [["\"abcabcabc\""]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
66,644
class Solution: def distinctEchoSubstrings(self, text: str) -> int:
0aa1b141cef1f3945738e8efde1a22e3
UNKNOWN
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences...
["class Solution:\n def combinationSum4(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n cache = {}\n def f(val):\n if val == target:\n return 1\n \n total = 0\n remain...
{"fn_name": "combinationSum4", "inputs": [[[1, 2, 3], 4]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
12,065
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int:
08c06cb6e8ab53155e474c0d887fcc80
UNKNOWN
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations: Serve 100 ml of soup A and 0 ml of soup B Serve 75 ml of soup A and 25 ml of soup B Serve 50 ml of soup A and 50 ml of soup B Serve 25 ml of soup A and 75 ml of soup B When we serve some so...
["class Solution:\n \n def soupServings(self, N: int) -> float:\n if N > 5000: return 1 # shortcut for large N (accurate to 1e-6)\n\n @lru_cache(None)\n def dp(a, b):\n if a <= 0 and b <= 0: return 0.5\n if a <= 0: return 1\n if b <= 0: return 0\n ...
{"fn_name": "soupServings", "inputs": [[50]], "outputs": [0.625]}
INTERVIEW
PYTHON3
LEETCODE
23,219
class Solution: def soupServings(self, N: int) -> float:
f946a806fda639e54db1adcc2f9e34b6
UNKNOWN
Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. A closed tag (not necessarily valid) has exactly t...
["class Solution:\n def isValid(self, code):\n \"\"\"\n :type code: str\n :rtype: bool\n \"\"\"\n def parseTag(src, i):\n j = i\n tag, i = findtag(src, i)\n if not tag:\n return False, j\n \n res, i = parseConten...
{"fn_name": "isValid", "inputs": [["\"<DIV>This is the first line <![CDATA[<div>]]></DIV>\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
3,851
class Solution: def isValid(self, code: str) -> bool:
2fe1a37872b001f264da55a299330260
UNKNOWN
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Exa...
["from collections import Counter\nclass Solution:\n def longestArithSeqLength(self, A: List[int]) -> int:\n c = dict(Counter(A).most_common())\n # print(c)\n m1 = max(c.values())\n # A = list(set(A))\n # A.sort()\n index = {}\n # for i in range(len(A)):\n ...
{"fn_name": "longestArithSeqLength", "inputs": [[[3, 6, 9, 12]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
345,168
class Solution: def longestArithSeqLength(self, A: List[int]) -> int:
bf0d91fa1f3714ecf419f2613966f002
UNKNOWN
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1...
["class Solution:\n def monotoneIncreasingDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n \n arr = [int(ch) for ch in str(N)] # create array from number 1234 => [1,2,3,4]\n marker = len(arr)\n \n i = len(arr)-2\n while...
{"fn_name": "monotoneIncreasingDigits", "inputs": [[10]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
6,093
class Solution: def monotoneIncreasingDigits(self, N: int) -> int:
43c3933275135c3763dd723bfeecea1e
UNKNOWN
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies y...
["class Solution:\n def candy(self, ratings):\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n \n if not ratings:\n return 0\n \n total, pre, decrease = 1, 1, 0\n for i in range(1, len(ratings)):\n if ratings[i] >= ratings[i...
{"fn_name": "candy", "inputs": [[[1, 0, 2]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
7,976
class Solution: def candy(self, ratings: List[int]) -> int:
6735b05704b799fe5d24473014f2d173
UNKNOWN
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A...
["import collections\n\nclass Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n cum_sum = 0\n queue = collections.deque([(-1, 0)])\n result = len(A) + 1\n for i, v in enumerate(A):\n cum_sum += v \n if v > 0:\n # find any matche...
{"fn_name": "shortestSubarray", "inputs": [[[1], 1]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
91,811
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int:
a60593f50d08634dda4708dfcd781172
UNKNOWN
Given an integer array bloomDay, an integer m and an integer k. We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days...
["class Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n \n flowersN = len(bloomDay)\n if flowersN < m*k:\n return -1\n \n def checkFlowers(x):\n count = 0\n gotFlowers = 0\n for num in bloomDay:\n ...
{"fn_name": "minDays", "inputs": [[[1, 10, 3, 10, 2], 3, 1]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
245,798
class Solution: def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
9a066aa688945684697f05c58267631f
UNKNOWN
Given a binary string s (a string consisting only of '0' and '1's). Return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: s = "0110111" Output: 9 Explanation: There are 9 substring in total with only 1's characters. "1" -> 5 times. "11...
["class Solution:\n def numSub(self, s: str) -> int:\n # 10/6/20\n dic = collections.defaultdict(int)\n \n n = len(s)\n left, right = 0, 0\n while left < n:\n if s[left] == '1':\n right = left\n while right < n and s[right] == '1':\n ...
{"fn_name": "numSub", "inputs": [["\"0110111\""]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
6,813
class Solution: def numSub(self, s: str) -> int:
e6a646cdb1a0a6472290df52f7e1a83e
UNKNOWN
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equal...
["class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n xy_pair = 0\n yx_pair = 0\n \n for c1, c2 in zip(s1, s2):\n if c1 == 'x' and c2 == 'y':\n xy_pair += 1\n elif c1 == 'y' and c2 == 'x':\n yx_pair += 1\n \n ...
{"fn_name": "minimumSwap", "inputs": [["\"xx\"", "\"yy\""]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
4,479
class Solution: def minimumSwap(self, s1: str, s2: str) -> int: