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
0f3fa57cb80f26471b9efd33fc67a7c9
UNKNOWN
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell c...
["class BIT():\n def __init__(self,n):\n self.BIT=[0]*(n+1)\n self.num=n\n\n def query(self,idx):\n res_sum = 0\n while idx > 0:\n res_sum += self.BIT[idx]\n idx -= idx&(-idx)\n return res_sum\n\n #Ai += x O(logN)\n def update(self,idx,x):\n wh...
{ "inputs": [ "6\n1 5\n0 10\n1 -5\n0 5\n1 11\n0 -10\n" ], "outputs": [ "5\n25\n10\n15\n36\n21\n" ] }
INTERVIEW
PYTHON3
CODEFORCES
8,126
829ec07da40bc119237cf08f8252c5da
UNKNOWN
Let's call an array $a_1, a_2, \dots, a_m$ of nonnegative integer numbers good if $a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$, where $\oplus$ denotes the bitwise XOR operation. For example, array $[1, 2, 3, 6]$ is good, as $1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplu...
["for nt in range(int(input())):\n\tn=int(input())\n\tl=list(map(int,input().split()))\n\ts=sum(l)\n\te=l[0]\n\tfor i in range(1,n):\n\t\te=e^l[i]\n\tif s==2*e:\n\t\tprint(0)\n\t\tprint ()\n\telse:\n\t\tprint(2)\n\t\tprint(e,s+e)\n", "for _ in range(int(input())):\n\tn=int(input())\n\tl=list(map(int,input().split()))\n...
{ "inputs": [ "3\n4\n1 2 3 6\n1\n8\n2\n1 1\n" ], "outputs": [ "0\n\n2\n4 4\n3\n2 2 6\n" ] }
INTERVIEW
PYTHON3
CODEFORCES
513
f86e7c85b0ae0e05e04c0e3860e7444c
UNKNOWN
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $n\cdot m$ different seals, denoted by distinct numbers. All of them were written in an $n\times m$ table. The table is lost now. Naruto managed to remember elements of each row from left to rig...
["from sys import stdin\ninput = stdin.readline\n\ntests = int(input())\nfor test in range(tests):\n n, m = list(map(int, input().split()))\n a = [[0] * m for _ in range(n)]\n r = [[int(i) for i in input().split()] for _ in range(n)]\n c = [[int(i) for i in input().split()] for _ in range(m)]\n z = [[-1,...
{ "inputs": [ "2\n2 3\n6 5 4\n1 2 3\n1 6\n2 5\n3 4\n3 1\n2\n3\n1\n3 1 2\n" ], "outputs": [ "1 2 3 \n6 5 4 \n3 \n1 \n2 \n" ] }
INTERVIEW
PYTHON3
CODEFORCES
2,576
759c5486518ba1e0acaa1adcecee768c
UNKNOWN
There are $n$ programmers that you want to split into several non-empty teams. The skill of the $i$-th programmer is $a_i$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the...
["__MULTITEST = True\n\n## solve\ndef solve():\n n, x = map(int, input().split())\n a = list(map(int, input().split()))\n a.sort()\n\n group = 0\n ptr = n-1\n members = 0\n\n currentMin = int(1e10)\n while ptr > -1:\n currentMin = min(currentMin, a[ptr])\n members += 1\n\n i...
{ "inputs": [ "3\n5 10\n7 11 2 9 5\n4 8\n2 4 2 3\n4 11\n1 3 3 7\n" ], "outputs": [ "2\n1\n0\n" ] }
INTERVIEW
PYTHON3
CODEFORCES
12,136
d76e71192b91524a5f4d5bdaf5312d02
UNKNOWN
Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols "0" and "1"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to "1". More formally, $f(s)$ is equ...
["import sys\ninput = sys.stdin.readline\n\nt=int(input())\n\ndef calc(x):\n return x*(x+1)//2\n\nfor test in range(t):\n n,m=list(map(int,input().split()))\n\n ANS=calc(n)\n\n k=n-m\n q,mod=divmod(k,m+1)\n\n ANS-=calc(q+1)*mod+calc(q)*(m+1-mod)\n\n print(ANS)\n \n", "import sys\n\nfor _ in rang...
{ "inputs": [ "5\n3 1\n3 2\n3 3\n4 0\n5 2\n" ], "outputs": [ "4\n5\n6\n0\n12\n" ] }
INTERVIEW
PYTHON3
CODEFORCES
1,669
159afa3642f21981fb4fa4da2a09ab0b
UNKNOWN
Reminder: the median of the array $[a_1, a_2, \dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$. There are $2n$ students, the $i$-th student has skill level $a_i$. It's n...
["for _ in range(int(input())):\n n = int(input())\n ar = list(map(int, input().split()))\n ar.sort()\n print(abs(ar[n] - ar[n - 1]))", "t = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n a = sorted(a)\n print(a[n]- a[n - 1])", "def iinput():\n ret...
{ "inputs": [ "3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16\n" ], "outputs": [ "0\n1\n5\n" ] }
INTERVIEW
PYTHON3
CODEFORCES
5,217
b6c3b2fb5794990dff45e1b206fae998
UNKNOWN
There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have ...
["class Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n max_score = 0\n curr_score= 0\n init_hand = cardPoints[len(cardPoints)-k:]\n max_score = sum(init_hand)\n curr_score = max_score\n for i in range(k):\n curr_score -= init_hand[i]\n ...
{"fn_name": "maxScore", "inputs": [[[1, 2, 3, 4, 5, 6, 1], 3]], "outputs": [12]}
INTERVIEW
PYTHON3
LEETCODE
45,423
class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int:
3e3d5bf7cf5b992fd8e977b4d49ec4e1
UNKNOWN
Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that: Every song is played at least once A song can only be played again only if K other songs have been played Return the number of possible playlists.  As the answe...
["import math\nclass Solution:\n def numMusicPlaylists(self, N: int, L: int, K: int) -> int:\n s=0\n c=0\n r=0\n x=math.factorial(N)\n while(True):\n c=x*((N-r-K)**(L-K))*(-1)**(r)//(math.factorial(N-r-K)*math.factorial(r))\n if(c!=0):\n s=(s+c)...
{"fn_name": "numMusicPlaylists", "inputs": [[3, 3, 1]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
19,223
class Solution: def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
a7659551dbfd5cc1be2f75cd752918cf
UNKNOWN
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true ...
["class Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: bool\n \"\"\"\n return target in nums\n", "class Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n ...
{"fn_name": "search", "inputs": [[[2, 5, 6, 0, 0, 1, 2], 0]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
14,644
class Solution: def search(self, nums: List[int], target: int) -> bool:
90aa0fccfd50a272e8bdc7a685592090
UNKNOWN
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example1: a = 2 b = [3] Result: 8 Example2: a = 2 b = [1,0] Result: 1024 Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases...
["class Solution:\n def superPow(self, a, b):\n result = 1\n fermatb = (int(''.join(map(str, b)))) % 570\n while fermatb:\n if fermatb & 1:\n result = (result * a) % 1337\n a = (a * a) % 1337\n fermatb >>= 1\n return result", "class...
{"fn_name": "superPow", "inputs": [[2, [3]]], "outputs": [8]}
INTERVIEW
PYTHON3
LEETCODE
5,701
class Solution: def superPow(self, a: int, b: List[int]) -> int:
35bd1bb834ead4a2e36a6753f12dd386
UNKNOWN
Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive.   Example 1: Input: s = "aababcaab", maxLetters = 2, minSiz...
["class Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n n = len(s)\n count = collections.Counter(s[i : i + minSize] for i in range(0, n - minSize + 1))\n res = 0 \n for k, v in count.items():\n if len(set(k)) <= maxLetters:\n ...
{"fn_name": "maxFreq", "inputs": [["\"aababcaab\"", 2, 3, 4]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
162,004
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
139ce72250a9de8fae467060da06ca6f
UNKNOWN
There is a group of G members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that gen...
["class Solution:\n def profitableSchemes(self, G: int, P: int, group: List[int], profit: List[int]) -> int:\n MOD = 10**9 + 7\n group_len, profit_len = len(group),len(profit)\n dp = [[0]*(G+1) for _ in range(P+1)]\n dp[0][0] = 1\n for pro, gro in zip(profit,group):\n dp...
{"fn_name": "profitableSchemes", "inputs": [[5, 3, [2, 2], [2, 3]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
66,918
class Solution: def profitableSchemes(self, G: int, P: int, group: List[int], profit: List[int]) -> int:
46dae9ba0ab4403684f6f9508f346112
UNKNOWN
Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . Example 1: Input: "1 + 1" Output: 2 Example 2: Input: " 2-1 + 2 " Output: 3 Example 3: Input: "(1+(4+5...
["class Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n res = 0\n num = 0\n sign = 1\n stk = []\n \n for c in s:\n if c.isdigit():\n num = 10 * num + (ord(c) - ord('0'))\n ...
{"fn_name": "calculate", "inputs": [["\"1 + 1\""]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
6,773
class Solution: def calculate(self, s: str) -> int:
5c6ac02bd99712d8d1ee705f16e67da6
UNKNOWN
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them. The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them. ...
["class Solution:\n def maxScoreSightseeingPair(self, A: List[int]) -> int:\n curmaxsight = A[0] - 1\n curmaxpair = 0\n for sight in A[1:]:\n if sight + curmaxsight > curmaxpair:\n curmaxpair = sight + curmaxsight\n if sight > curmaxsight:\n cu...
{"fn_name": "maxScoreSightseeingPair", "inputs": [[[8, 1, 5, 2, 6]]], "outputs": [11]}
INTERVIEW
PYTHON3
LEETCODE
35,767
class Solution: def maxScoreSightseeingPair(self, A: List[int]) -> int:
142c7c79f4926fbe005bb1ccc1cf508f
UNKNOWN
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k. There can be multiple...
["class Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n dp = [-1] * len(s)\n return self.dfs(s, k, 0, dp)\n \n def dfs(self, s: str, k: int, start: int, dp: List[int]) -> int:\n if start == len(s):\n return 1\n if s[start] == '0':\n return 0\n ...
{"fn_name": "numberOfArrays", "inputs": [["\"1000\"", 10000]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
6,291
class Solution: def numberOfArrays(self, s: str, k: int) -> int:
c1cfa9f4af66ba5036d497a01665574c
UNKNOWN
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, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single inte...
["class Solution(object):\n \tdef parse(self,expression,d,i):\n \t\tcount = 0\n \t\tstart = i\n \t\tif expression[i] == \"(\":\n \t\t\tcount += 1\n \t\t\ti += 1\n \t\t\twhile count != 0:\n \t\t\t\tif expression[i] == \"(\":\n \t\t\t\t\tcount += 1\n \t\t\t\telif expression[i] == \")\":\n \t\t\t\t\tcount -= 1\n \t\t\t\ti...
{"fn_name": "evaluate", "inputs": [["\"(add 1 2)\""]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
2,385
class Solution: def evaluate(self, expression: str) -> int:
7f550c60a7576c9676543c8b5da695bd
UNKNOWN
In a country popular for train travel, you have planned some train travelling one year in advance.  The days of the year that you will travel is given as an array days.  Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways: a 1-day pass is sold for costs[0] dollars; a 7-day pass is sold for...
["class Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = [0] + [-1 for i in range(days[-1])]\n \n for day in days:\n dp[day] = 0\n \n for i in range(1, len(dp)):\n if dp[i] == -1:\n dp[i] = dp[i-1]\n ...
{"fn_name": "mincostTickets", "inputs": [[[1, 4, 6, 7, 8, 20], [2, 7, 15]]], "outputs": [11]}
INTERVIEW
PYTHON3
LEETCODE
16,582
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int:
44ebae504e00485d21ab04b147d2acc6
UNKNOWN
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'. A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make the origin...
["class Solution:\n def balancedString(self, s: str) -> int:\n # minimum window so that outside is possible\n if len(s) //4 != len(s) / 4: return -1 \n ans, lb, n_cnt = len(s), 0, collections.Counter(s)\n\n i = 0\n while i < len(s): \n n_cnt[s[i]] -= 1 \n ...
{"fn_name": "balancedString", "inputs": [["\"QWER\""]], "outputs": [-1]}
INTERVIEW
PYTHON3
LEETCODE
5,960
class Solution: def balancedString(self, s: str) -> int:
0fb7f13b2aaaa034f22f9840bc963397
UNKNOWN
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.   Example 1: Input: 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: 100 Output: 10 Explanation: The positive numbers (<= 1...
["class Solution:\n def numDupDigitsAtMostN(self, N: int) -> int:\n # N -> total numbers less than or equal to N\n # We will calculate the integers with all different digits (which are less than/equal to N)\n # Then the answer would be: N - nums_with_different_digits\n \n # Calcula...
{"fn_name": "numDupDigitsAtMostN", "inputs": [[20]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
19,594
class Solution: def numDupDigitsAtMostN(self, N: int) -> int:
8058a21bd267d9637db518cd627dddb6
UNKNOWN
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.   Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(...
["class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n j = 0\n l = []\n for i in pushed:\n l.append(i)\n while l and (l[-1] == popped[j]):\n l.pop()\n j += 1\n if l:\n return Fals...
{"fn_name": "validateStackSequences", "inputs": [[[1, 2, 3, 4, 5], [4, 5, 3, 2, 1]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
11,292
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
7dd39b3276a532f740d03d1164f0def2
UNKNOWN
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.  At the end, the "skyline" when...
["class Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n # Pad with inf to make implementation easier\n INF = -10_000\n n = len(grid)\n\n total = 0\n max_rows = [max(row, default=INF) for row in grid]\n # Transpose the grid to make max less cu...
{"fn_name": "maxIncreaseKeepingSkyline", "inputs": [[[[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
630
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
afaba84e4c72d454a8f8068f7708d2a6
UNKNOWN
Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum n...
["class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n s = 0\n m = n\n while m:\n s += m & 1\n m >>= 1\n\n k = 1\n while s:\n s -= bool(n & k)\n n ^= (s & 1) and k\n k <<= 1\n\n return n", "class Solutio...
{"fn_name": "minimumOneBitOperations", "inputs": [[0]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
3,938
class Solution: def minimumOneBitOperations(self, n: int) -> int:
dfa55499da693faf0f1f0489e208a8f0
UNKNOWN
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product.   Example 1: Input: nums = [1,-2,-3,4]...
["class Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n maxx = 0\n nums.append(0)\n \n # starting position\n # where we find a 0\n i = -1\n minusarr = []\n \n for j,n in enumerate(nums):\n if n == 0:\n # now figure ou...
{"fn_name": "getMaxLen", "inputs": [[[1, -2, -3, 4]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
242,684
class Solution: def getMaxLen(self, nums: List[int]) -> int:
0bc527eeaf787e8c210cd6b6828808aa
UNKNOWN
We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices. For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions...
["class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n def isSorted(arr, i, j):\n return all(arr[k] <= arr[k+1] for k in range(i, j))\n ans = 0\n ranges = [[0, len(A)-1]]\n for col in zip(*A):\n if not ranges:\n break\n if all...
{"fn_name": "minDeletionSize", "inputs": [[["\"ca\"", "\"bb\"", "\"ac\""]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
8,582
class Solution: def minDeletionSize(self, A: List[str]) -> int:
760a2a5d6c0aa2866c4bf84bdaf8783f
UNKNOWN
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. Could you do this in O(n) runtime? Example: Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.
["class Solution:\n def findMaximumXOR(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ans = 0\n for bit in range(31, -1, -1) :\n ans = (ans << 1) + 1\n pre = set()\n for n in nums :\n p = (n >...
{"fn_name": "findMaximumXOR", "inputs": [[[3, 10, 5, 25, 2, 8]]], "outputs": [28]}
INTERVIEW
PYTHON3
LEETCODE
996
class Solution: def findMaximumXOR(self, nums: List[int]) -> int:
76f081c847c6c00ef13a07b16a5cf968
UNKNOWN
The i-th person has weight people[i], and each boat can carry a maximum weight of limit. Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person.  (It is guaranteed each person can be carried by ...
["class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n \n people.sort()\n lo = 0 \n hi = len(people) - 1\n count = 0\n \n while lo <= hi:\n count += 1\n if people[lo] + people[hi] <= limit:\n lo += 1\...
{"fn_name": "numRescueBoats", "inputs": [[[1, 2], 3]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
55,731
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int:
10bb21c768957af3e041d2f6a863fcfc
UNKNOWN
Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings. A subsequence is a sequence that can be derived from one seque...
["class Solution:\n def findLUSlength(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: int\n \"\"\"\n def isSubseq(s1, s2):\n i, m=0, len(s1)\n for c in s2:\n if i==m: return True\n if s1[i]==c: i+=1\n ...
{"fn_name": "findLUSlength", "inputs": [[["\"aba\"", "\"cdc\"", "\"eae\""]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
11,056
class Solution: def findLUSlength(self, strs: List[str]) -> int:
513692b5ffd20537e2d00ff42bd48305
UNKNOWN
In a row of trees, the i-th tree produces fruit with type tree[i]. You start at any tree of your choice, then repeatedly perform the following steps: Add one piece of fruit from this tree to your baskets.  If you cannot, stop. Move to the next tree to the right of the current tree.  If there is no tree to the right, s...
["class Solution:\n def totalFruit(self, tree: List[int]) -> int:\n prior_fruit = tree[0]\n prior_fruit_counter = 0\n fruits_in_basket = [tree[0]]\n fruits_in_basket_counter = 0\n max_fib = -1\n for fruit in tree: \n if prior_fruit == fruit:\n prior...
{"fn_name": "totalFruit", "inputs": [[[1, 2, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
178,022
class Solution: def totalFruit(self, tree: List[int]) -> int:
f6e78a0c00a7faf231517029b017fcc0
UNKNOWN
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given a number n. You have to get ...
["class Solution:\n def minSteps(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n primeFactors=[]\n for i in range(2,int(n**.5)+1):\n while n%i==0:\n primeFactors.append(i)\n n=n//i\n if n>1:\n ...
{"fn_name": "minSteps", "inputs": [[3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
6,099
class Solution: def minSteps(self, n: int) -> int:
35defba7a2bf835624aedcaa0556004d
UNKNOWN
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24. Example 1: Input: [4, 1, 8, 7] Output: True Explanation: (8-4) * (7-1) = 24 Example 2: Input: [1, 2, 1, 2] Output: False Note: The division operator / represe...
["class Solution(object):\n def judgePoint24(self, nums):\n bad = '\ub5a2\ube3b\uac01\uac4e\ub0c7\uac05\uac38\uae9a\ubd5f\uc223\uc684\ubd74\ubd5e\ub93c\uac08\uac0c\ub914\ub58c\uc60a\uba54\ub284\uc22d\uceb8\uae36\uae9b\uc616\uac0d\ub1d0\uca62\uacf4\ub4c7\uac6f\uad84\uc615\uc679\ub21e\uc1b4\uac43\ub057\uae2c\...
{"fn_name": "judgePoint24", "inputs": [[[4, 1, 8, 7]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
6,349
class Solution: def judgePoint24(self, nums: List[int]) -> bool:
6ce2076c3956b557d9f4ca8664ef5c53
UNKNOWN
Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square...
["class Solution:\n def decodeString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stack = []\n stack.append([\"\", 1])\n num = \"\"\n for ch in s:\n if ch.isdigit():\n num += ch\n elif ch == '[':\n ...
{"fn_name": "decodeString", "inputs": [["\"3[a]2[bc]\""]], "outputs": ["\"aaabcbc\""]}
INTERVIEW
PYTHON3
LEETCODE
4,667
class Solution: def decodeString(self, s: str) -> str:
2a4d6d1dbe164a82ae627147778a041e
UNKNOWN
There are n engineers numbered from 1 to n and two arrays: speed and efficiency, where speed[i] and efficiency[i] represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most k engineers, since the answer can be a huge number, return this modulo 10^...
["class Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n mod = 10**9+7\n \n order = sorted(range(n), key=lambda i: efficiency[i], reverse=True)\n\n heap = []\n filled = 0\n rec = 0\n speed_sum = 0\n\n for i...
{"fn_name": "maxPerformance", "inputs": [[6, [2, 10, 3, 1, 5, 8], [5, 4, 3, 9, 7, 2], 2]], "outputs": [60]}
INTERVIEW
PYTHON3
LEETCODE
50,830
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
94ce375929740cf3aca60ab99561a75b
UNKNOWN
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.  Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].  Every worker can be assigned at most one job, but one ...
["class Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n ws = sorted(worker, reverse=True)\n dp = sorted(zip(difficulty, profit), key=lambda x: x[1], reverse=True)\n # print(list(dp))\n \n i = 0\n total = 0\n ...
{"fn_name": "maxProfitAssignment", "inputs": [[[2, 4, 6, 8, 10], [10, 20, 30, 40, 50], [4, 5, 6, 7]]], "outputs": [100]}
INTERVIEW
PYTHON3
LEETCODE
71,819
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
c71b5a81cf0ce34f6030e88136002aef
UNKNOWN
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate r...
["class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n st=[['*',0]]\n for c in s:\n if c!=st[-1][0]:\n st.append([c,1])\n else:\n st[-1][1]+=1\n if st[-1][1]==k:\n st.pop()\n res=''\n f...
{"fn_name": "removeDuplicates", "inputs": [["\"abcd\"", 2]], "outputs": ["\"abcd\""]}
INTERVIEW
PYTHON3
LEETCODE
12,101
class Solution: def removeDuplicates(self, s: str, k: int) -> str:
2700dd3857cc334101b34ff7949f5be3
UNKNOWN
Given an array A, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the smallest possible size. Return the length of left after such a partitioning.  It is guaranteed that such a partitioni...
["class Solution:\n def partitionDisjoint(self, A: List[int]) -> int:\n biggest = A[0]\n newbiggest = A[0]\n lenL = 1\n total = 1\n for itr in A[1:]:\n total += 1\n if itr < biggest:\n lenL = total\n biggest = newbiggest\n ...
{"fn_name": "partitionDisjoint", "inputs": [[[5, 0, 3, 8, 6]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
29,595
class Solution: def partitionDisjoint(self, A: List[int]) -> int:
e523a33b7fdb4be1eee40aa4b7ac77c7
UNKNOWN
A password is considered strong if below conditions are all met: It has at least 6 characters and at most 20 characters. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa.....
["class Solution:\n def strongPasswordChecker(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def length_requirement(password):\n length = len(password)\n # positive means addition, negative means deletion\n if length < 6:\n ...
{"fn_name": "strongPasswordChecker", "inputs": [["\"a\""]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
6,091
class Solution: def strongPasswordChecker(self, s: str) -> int:
ac6c12703104363c315625f20b7a80a2
UNKNOWN
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two ba...
["class Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n position.sort()\n \n max_distance_between = (position[-1] - 1) // (m - 1)\n min_distance_between = 1\n \n if self.isDistancePossible(max_distance_between, position, m): return max_distance_betwe...
{"fn_name": "maxDistance", "inputs": [[[1, 2, 3, 4, 7], 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
360,356
class Solution: def maxDistance(self, position: List[int], m: int) -> int:
f2d3bd0dfc7ee9fc175cb3184e11a9f4
UNKNOWN
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Your input will be...
["class Solution:\n def makesquare(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if len(nums) < 4:\n return False\n \n length = sum(nums)\n if length % 4:\n return False\n length = (int) (length...
{"fn_name": "makesquare", "inputs": [[[1, 1, 2, 2, 2]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
5,051
class Solution: def makesquare(self, nums: List[int]) -> bool:
ee02f0284536e543ea5145dd8ab1187a
UNKNOWN
Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical c...
["class Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n mod = int(1e9)+7\n return ( ( self.getMax(horizontalCuts, h) % mod ) * ( self.getMax(verticalCuts, w) % mod ) ) % mod\n \n def getMax(self, cuts, size):\n if len(cuts) ==...
{"fn_name": "maxArea", "inputs": [[5, 4, [1, 2, 4], [1, 3]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
36,512
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
6b94e3dd8e893007969648da5da69a8e
UNKNOWN
Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (Mo...
["class Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n dp = [1] * (len(arr) + 1)\n stack = []\n for i, n in enumerate(arr + [1000000]):\n while stack and arr[stack[-1]] < n:\n same_height_idx = [stack.pop()]\n while stack and arr[stack[-...
{"fn_name": "maxJumps", "inputs": [[[6, 4, 14, 6, 8, 13, 9, 7, 10, 6, 12], 2]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
124,982
class Solution: def maxJumps(self, arr: List[int], d: int) -> int:
a8619a3c7049c0f749b869ee462eee8f
UNKNOWN
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them. (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in th...
["import sys\n\ndef dp(s1, s2, i, j, mem):\n if (i, j) in mem:\n return mem[(i, j)]\n elif i >= len(s1) and j >= len(s2):\n res = ''\n elif i >= len(s1):\n res = s2[j:]\n elif j >= len(s2):\n res = s1[i:]\n else:\n if s1[i] == s2[j]:\n res = s1[i] + dp(s1, s2...
{"fn_name": "shortestCommonSupersequence", "inputs": [["\"abac\"", "\"cab\""]], "outputs": ["\"cabac\""]}
INTERVIEW
PYTHON3
LEETCODE
70,666
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
4378db9f9bf26a5c1d0d6c9eed26f8f7
UNKNOWN
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty an...
["class Solution:\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n '''\u7ef4\u62a4\u4e24\u4e2a\u4e0b\u6807\uff0c\u9010\u4e2a\u6bd4\u8f83\uff0c\u5982\u679cpj\u4e3a*\uff0c\u5219\u8bb0\u5f55*\u7684\u4f4d\u7f6e\uff0c\u5c06*\u540e...
{"fn_name": "isMatch", "inputs": [["\"aa\"", "\"a\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
3,956
class Solution: def isMatch(self, s: str, p: str) -> bool:
c3541bd3613193888f482ca022792bf3
UNKNOWN
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B. Given two anagrams A and B, return the smallest K for which A and B are K-similar. Example 1: Input: A = "ab", B = "ba" Output: 1 Example 2: Input: A ...
["class Solution:\n def kSimilarity(self, A: str, B: str) -> int:\n a = ''\n b = ''\n \n for i in range(len(A)):\n if A[i] != B[i]:\n a+=A[i]\n b+=B[i]\n \n return self.dfs(a,b)\n \n def dfs(self,a,b):\n if not...
{"fn_name": "kSimilarity", "inputs": [["\"ab\"", "\"ba\""]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
108,041
class Solution: def kSimilarity(self, A: str, B: str) -> int:
82849051cbeb04925634d4fedc348e5e
UNKNOWN
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of element...
["from collections import deque\nclass Solution:\n def constrainedSubsetSum(self, nums, k):\n N, queue = len(nums), deque()\n dp = [val for val in nums]\n for i, val in enumerate(nums):\n if queue and (i - queue[0] > k):\n queue.popleft()\n if queue and dp[qu...
{"fn_name": "constrainedSubsetSum", "inputs": [[[10, 2, -10, 5, 20], 2]], "outputs": [37]}
INTERVIEW
PYTHON3
LEETCODE
50,548
class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
2bccf13809e68bf524a22a89ebd90bec
UNKNOWN
Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties. Alex and Lee take turns, with Alex star...
["class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True", "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return 1;\n", "class Solution:\n def recur(self,i,j,piles,n,dp,s):\n if j==i+1:\n return max(piles[i],piles[j])\n if dp[i...
{"fn_name": "stoneGame", "inputs": [[[5, 3, 4, 5]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
123,448
class Solution: def stoneGame(self, piles: List[int]) -> bool:
de2d02c44809586051fa8b7199be1680
UNKNOWN
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # # For example, the above binary tree can...
["class Solution(object):\n def isValidSerialization(self, preorder):\n \"\"\"\n :type preorder: str\n :rtype: bool\n \"\"\"\n # remember how many empty slots we have\n # non-null nodes occupy one slot but create two new slots\n # null nodes occupy one slot\n ...
{"fn_name": "isValidSerialization", "inputs": [["\"9,3,4,#,#,1,#,#,2,#,6,#,#\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
8,206
class Solution: def isValidSerialization(self, preorder: str) -> bool:
f13e697cc7602a20445585d8158368ef
UNKNOWN
Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "...
["class Solution:\n def longestCommonSubsequence(self, a: str, b: str) -> int:\n last, current = [0] * (len(b) + 1), [0] * (len(b) + 1)\n \n for i in range(len(a) - 1, -1, -1):\n for j in range(len(b) - 1, -1, -1):\n if a[i] == b[j]:\n current[j] = 1 ...
{"fn_name": "longestCommonSubsequence", "inputs": [["\"abcde\"", "\"ace\""]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
214,632
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int:
609ca3fac8433eaf601c1fc86f2d0251
UNKNOWN
Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string ( A subsequence of a string is a new string which is formed from the original string by del...
["class Solution:\n def isSubsequence(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) > len(t):\n return False\n for i in s:\n if i in t:\n index = t.find(i)\n t = ...
{"fn_name": "isSubsequence", "inputs": [["\"abc\"", "\"ahbgdc\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
3,901
class Solution: def isSubsequence(self, s: str, t: str) -> bool:
2dc5b6d49f1faaeeee9edb8eaaed7769
UNKNOWN
Given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string.   Example 1: Input: num = "4321", k = 4 Output: "1342" Explanation: The steps to obtain the mi...
["class Solution:\n def minInteger(self, num: str, k: int) -> str:\n n=len(num)\n if k<=0:\n return num\n \n if k>n*(n-1)//2:\n return ''.join(sorted(list(num)))\n \n for i in range(10):\n idx = num.find(str(i))\n if idx>=0 and idx...
{"fn_name": "minInteger", "inputs": [["\"4321\"", 4]], "outputs": ["1\"432\""]}
INTERVIEW
PYTHON3
LEETCODE
6,774
class Solution: def minInteger(self, num: str, k: int) -> str:
68a385e5d93dbf3bf25940aeab500cfc
UNKNOWN
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Ex...
["class Solution:\n def findLongestWord(self, s, d):\n \"\"\"\n :type s: str\n :type d: List[str]\n :rtype: str\n \"\"\"\n result = ''\n for word in d:\n lo = 0\n for l in word:\n lo = s.find(l, lo)+1\n i...
{"fn_name": "findLongestWord", "inputs": [["\"abpcplea\"", ["\"ale\"", "\"apple\"", "\"monkey\"", "\"plea\""]]], "outputs": ["\"apple\""]}
INTERVIEW
PYTHON3
LEETCODE
2,950
class Solution: def findLongestWord(self, s: str, d: List[str]) -> str:
a5f0c18ed3e7f61082c7028ce34dd751
UNKNOWN
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.   Example 1: Input: a = 2, b = 6, c = 5 Output: 3 Explanation...
["class Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n flips = 0\n print(bin(a))\n print(bin(b))\n print(bin(c))\n while a or b or c:\n # print(a, b, c)\n if c % 2:\n if not (a % 2 or b % 2):\n flips += 1\n ...
{"fn_name": "minFlips", "inputs": [[2, 6, 5]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
4,161
class Solution: def minFlips(self, a: int, b: int, c: int) -> int:
6ca52bda05dcf9e3ca848fad3dc97001
UNKNOWN
You are given K eggs, and you have access to a building with N floors from 1 to N.  Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floo...
["class Solution:\n def superEggDrop(self, K: int, N: int) -> int:\n def f(t):\n a=0\n r=1\n for i in range(1, K+1):\n r *= (t-i+1)\n r//=i\n a+=r\n if a>=N: \n break\n return a\n ...
{"fn_name": "superEggDrop", "inputs": [[1, 2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
185,524
class Solution: def superEggDrop(self, K: int, N: int) -> int:
b6a9e13e7b99bfffc297616e6440bdf2
UNKNOWN
Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s. Return True if you can use all the characters in s to construct k palindrome strings or False otherwise.   Example 1: Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palind...
["from collections import Counter\nclass Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n if k > len(s): #return False\n return False\n counter = Counter(s)\n odd_counts = 0\n \n for char in counter:\n if counter[char] % 2 == 1:\n o...
{"fn_name": "canConstruct", "inputs": [["\"annabelle\"", 2]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
15,482
class Solution: def canConstruct(self, s: str, k: int) -> bool:
e9939424377eb50c3c73f7afdcbc38a4
UNKNOWN
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). Note: You may assume that n is not less than 2 and not l...
["class Solution:\n def integerBreak(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n==2:return 1\n if n==3:return 2\n res=1\n while n>4:\n n=n-3\n res*=3\n return res*n\n", "class Solution:\n def inte...
{"fn_name": "integerBreak", "inputs": [[2]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
7,711
class Solution: def integerBreak(self, n: int) -> int:
bbe5dfbde96548275e5415aff96ffad1
UNKNOWN
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. A subarray is a contiguous subsequence of the array. Return the length of the shortest subarray to remove.   Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest su...
["class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n n = len(arr)\n if n<=1: \n return 0\n l,r = n,-1\n \n for i in range(1,n):\n if arr[i]<arr[i-1]:\n l = i\n break\n # monotonicially increa...
{"fn_name": "findLengthOfShortestSubarray", "inputs": [[[1, 2, 3, 10, 4, 2, 3, 5]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
133,870
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
fe881933339428ddc36db50b1976430b
UNKNOWN
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1]...
["class Solution:\n def maxProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def prod(nums):\n #function to calculate product\n prod = 1\n for i in nums:\n prod*=i\n return prod\n ...
{"fn_name": "maxProduct", "inputs": [[[2, 3, -2, 4]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
12,623
class Solution: def maxProduct(self, nums: List[int]) -> int:
547e1b1efb372c9f144bcf8a59157f90
UNKNOWN
You are given an integer num. You will apply the following steps exactly two times: Pick a digit x (0 <= x <= 9). Pick another digit y (0 <= y <= 9). The digit y can be equal to x. Replace all the occurrences of x in the decimal representation of num by y. The new integer cannot have any leading zeros, also the new in...
["class Solution:\n def maxDiff(self, num: int) -> int:\n if num < 10: return 8\n a = b = str(num)\n i = 0\n while i < len(a):\n if a[i] == '9':\n i += 1\n else:\n a = a.replace(a[i], '9')\n break\n\n if b[0] != '1'...
{"fn_name": "maxDiff", "inputs": [[555]], "outputs": [888]}
INTERVIEW
PYTHON3
LEETCODE
7,132
class Solution: def maxDiff(self, num: int) -> int:
06ca28905de57d461e647a7ad6b63584
UNKNOWN
Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return True If you can find a way to do that or False otherwise.   Example 1: Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5 Output: true Explanation: Pair...
["class Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n freq = [0] * k\n \n for n in arr:\n freq[n%k] += 1\n \n if freq[0] % 2: return False\n \n for i in range(1, (k//2)+1):\n if freq[i] != freq[k-i]: return False\n \n ...
{"fn_name": "canArrange", "inputs": [[[1, 2, 3, 4, 5, 10, 6, 7, 8, 9], 5]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
56,632
class Solution: def canArrange(self, arr: List[int], k: int) -> bool:
2ded902adc3930486de5a6a53e346bf3
UNKNOWN
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\...
["class Solution:\n def lengthLongestPath(self, input):\n \"\"\"\n :type input: str\n :rtype: int\n \"\"\"\n dict={0:0}\n maxlen=0\n line=input.split(\"\\n\")\n for i in line:\n name=i.lstrip('\\t')\n print(name)\n p...
{"fn_name": "lengthLongestPath", "inputs": [["\"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\""]], "outputs": [41]}
INTERVIEW
PYTHON3
LEETCODE
6,985
class Solution: def lengthLongestPath(self, input: str) -> int:
cce9cbd0e1bdff6f73add377c7051aba
UNKNOWN
Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones. Example 1: Input: 5 Output: 5 Explanation: Here are the non-negative integers Note: 1 9
["class Solution:\n def findIntegers(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n dp=[1,2]\n for i in range(2,32):\n dp.append(dp[i-1]+dp[i-2])\n \n bnum=bin(num)[2:]\n size=len(bnum)\n ans=dp[size]\n ...
{"fn_name": "findIntegers", "inputs": [[1]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
7,548
class Solution: def findIntegers(self, num: int) -> int:
865a5b3a6820635795d88f54d0f83b92
UNKNOWN
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a t To scramble the string, we may choose any non-leaf node...
["class Solution:\n def isScramble(self, A, B):\n if len(A) != len(B) or sorted(A) != sorted(B):\n return False\n \n if len(A) == 1 or A == B:\n return True\n \n for i in range(1, len(A)):\n if self.isScramble(A[:i], B[:i]) and self.isScramble(A[i:], B[i:]...
{"fn_name": "isScramble", "inputs": [["\"great\"", "\"rgeat\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
7,660
class Solution: def isScramble(self, s1: str, s2: str) -> bool:
72d4b3e49d5dd8c33d042685e67f962f
UNKNOWN
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is s...
["class Solution:\n def minWindow(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n left=-1\n right = 0\n result = \"\"\n totalMatch = 0\n d = {}\n for c in t:\n d[c] = d.get(c, 0) + 1\n \n...
{"fn_name": "minWindow", "inputs": [["\"ADOBECODEBANC\"", "\"ABC\""]], "outputs": ["\"ADOBECODEBANC\""]}
INTERVIEW
PYTHON3
LEETCODE
6,341
class Solution: def minWindow(self, s: str, t: str) -> str:
c77f1b49d8ef3a26a5821ed1cb679b64
UNKNOWN
Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may be more than one LIS combination, it is only necessary for yo...
["class Solution:\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n res = [nums[0]]\n def binarySearch(l,target):\n left , right = 0 , len(l)-1\n while l...
{"fn_name": "lengthOfLIS", "inputs": [[[10, 9, 2, 5, 3, 7, 101, 18]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
9,919
class Solution: def lengthOfLIS(self, nums: List[int]) -> int:
45e0ab7a30b289d53626f5c91820fda9
UNKNOWN
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:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n n = len(s)\n\n def compLen(c):\n return 1 + len(str(c)) if c > 1 else 1\n\n @lru_cache(None)\n def dp(i, k): # return {head: (len, -head_count)}\n if (n - i) <= k:\n ...
{"fn_name": "getLengthOfOptimalCompression", "inputs": [["\"aaabcccd\"", 2]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
69,278
class Solution: def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
72f7c76b82eaf7e59f747f2cf672be4e
UNKNOWN
A car travels from a starting position to a destination which is target miles east of the starting position. Along the way, there are gas stations.  Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas. The car starts with an infinite ta...
["class Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n if startFuel >= target: return 0\n heap = [] #record the reachable gas for now\n stop = 0 #total stops\n dist = startFuel #reachable distance\n for d, g in stations:\n ...
{"fn_name": "minRefuelStops", "inputs": [[1, 1, [[], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
38,810
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
baa9e65a6e0da6f04dd136faf3d1ae2d
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions: You may not engage in multiple...
["class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n n = len(prices)\n \n if n < 2: return 0\n \n sells = [0] * n\n buys = [0] * n\n \n buys[0] = -prices[0]\n ...
{"fn_name": "maxProfit", "inputs": [[[1, 2, 3, 0, 2]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
8,327
class Solution: def maxProfit(self, prices: List[int]) -> int:
85e40cc62f9037fa86bf7c49c3cec497
UNKNOWN
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for cont...
["class Solution:\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n if not height:\n return 0\n result = 0\n left = 0\n right = len(height) - 1\n while left < right:\n if height[left] ...
{"fn_name": "trap", "inputs": [[[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
14,030
class Solution: def trap(self, height: List[int]) -> int:
de317db4e26e324ce57759bb04cf3312
UNKNOWN
Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remai...
["class Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n \n # DP(a=index of last, b=index of last) = max of:\n # DP(a-1, b)\n # DP(a-1, i) + nums1[a] * max_or_min(nums2[i+1:b+1])\n # same for b\n \n INF = int(1e9)\n n, m =...
{"fn_name": "maxDotProduct", "inputs": [[[2, 1, -2, 5], [3, 0, -6]]], "outputs": [18]}
INTERVIEW
PYTHON3
LEETCODE
61,899
class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
fdfbebb50714dab829183b0c7f191d89
UNKNOWN
Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.   Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated charac...
["class Solution:\n def maxRepOpt1(self, text: str) -> int:\n letters = {}\n for i, char in enumerate(text):\n if char in letters:\n letters[char].append(i)\n else:\n letters[char] = [i]\n \n if len(letters) == 1:\n return len...
{"fn_name": "maxRepOpt1", "inputs": [["\"ababa\""]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
32,835
class Solution: def maxRepOpt1(self, text: str) -> int:
6c265e09d08a0ce4bfa5c5ca0f44bf10
UNKNOWN
Given a binary string s and an integer k. Return True if every binary code of length k is a substring of s. Otherwise, return False.   Example 1: Input: s = "00110110", k = 2 Output: true Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and...
["class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n if len(s) < 2 ** k + k - 1:\n return False # Cannot be a string, as this is the de brujin length\n target = 2 ** k\n seen = set()\n cur_len = 0\n for end in range(k, len(s) + 1):\n chunk = s[...
{"fn_name": "hasAllCodes", "inputs": [["\"00110110\"", 2]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
15,901
class Solution: def hasAllCodes(self, s: str, k: int) -> bool:
82fd619f19ff1ed57873a06c9edbae76
UNKNOWN
Given an array of integers cost and an integer target. Return the maximum integer you can paint under the following rules: The cost of painting a digit (i+1) is given by cost[i] (0 indexed). The total cost used must be equal to target. Integer does not have digits 0. Since the answer may be too large, return it as st...
["class Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n dp = [0] + [-target]*target\n for t in range(1, target+1):\n dp[t] = max([dp[t-i] for i in cost if i<=t]+[dp[t]]) + 1\n if dp[-1]<=0: return '0'\n res = ''\n for i in range(8, -1, -1):\n ...
{"fn_name": "largestNumber", "inputs": [[[4, 3, 2, 5, 6, 7, 2, 5, 5], 9]], "outputs": ["7772"]}
INTERVIEW
PYTHON3
LEETCODE
40,452
class Solution: def largestNumber(self, cost: List[int], target: int) -> str:
6d2cf2e5f998284520683fef946b2d9c
UNKNOWN
You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving j...
["class Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n if runningCost >= 4 * boardingCost:\n return -1\n result = sum(customers) // 4\n if (sum(customers) % 4) * boardingCost > runningCost:\n result += 1\n ...
{"fn_name": "minOperationsMaxProfit", "inputs": [[[8, 3], 5, 6]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
578,715
class Solution: def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
38dc4668e3c4deb9910eae9ad5b3e9a2
UNKNOWN
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. Example 1: Input: 123 Output: "One Hundred Twenty Three" Example 2: Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: 1234567 Output: "One Million Two Hundred ...
["class Solution:\n V1 = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\",\n \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"]\n V2 = [\"\", \"\", \"Twenty\", \"Thirty\", \"Fo...
{"fn_name": "numberToWords", "inputs": [[123]], "outputs": ["One Hundred Twenty Three"]}
INTERVIEW
PYTHON3
LEETCODE
15,285
class Solution: def numberToWords(self, num: int) -> str:
a3595fbf8e9dc54d7d40b0d664b3055d
UNKNOWN
You are given a list of preferences for n friends, where n is always even. For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 t...
["class Solution:\n def preferences_to_scores(self, preferences):\n scores = {}\n for u, up in enumerate(preferences):\n for s, v in enumerate(up):\n scores[(u, v)] = s\n return scores\n \n def unhappy_friends(self, scores, a, b):\n ret = set()\n for...
{"fn_name": "unhappyFriends", "inputs": [[4, [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0], [], []], [[0, 1], [2, 3], [], []]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
13,602
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
cbd9e665c1130105bfac8aba790569b4
UNKNOWN
Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. Example 1: Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3, 2, 1]. Note: 1 0
["class Solution:\n def findLength(self, A, B):\n def check(length):\n seen = {A[i:i+length]\n for i in range(len(A) - length + 1)}\n return any(B[j:j+length] in seen\n for j in range(len(B) - length + 1))\n \n A = ''.join(map(chr, A...
{"fn_name": "findLength", "inputs": [[[1, 2, 3, 2, 1], [3, 2, 1, 4, 7]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
625
class Solution: def findLength(self, A: List[int], B: List[int]) -> int:
1eb369a9bef07aac2c473eb37625fda3
UNKNOWN
Given an array of digits, you can write numbers using each digits[i] as many times as we want.  For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n.   Example 1: Inp...
["class Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n \n count = 0\n length = 1\n n_str = str(n)\n while length < len(n_str):\n count+= len(digits)**length\n length+=1\n\n digits_sorted = sorted(digits)\n\n\n ## ...
{"fn_name": "atMostNGivenDigitSet", "inputs": [[["\"1\"", "\"3\"", "\"5\"", "\"7\""], 100]], "outputs": [84]}
INTERVIEW
PYTHON3
LEETCODE
2,172
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
4506cf5ca5796076cc843484db886076
UNKNOWN
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with maximum number of coins. Y...
["class Solution:\n def maxCoins(self, piles: List[int]) -> int:\n piles.sort()\n \n i = 0\n j = len(piles) - 1\n \n max_coins = 0\n for i in range(len(piles) // 3, len(piles), 2):\n max_coins += piles[i]\n \n return max_coins", "class Solutio...
{"fn_name": "maxCoins", "inputs": [[[1, 2, 2, 4, 7, 8]]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
75,701
class Solution: def maxCoins(self, piles: List[int]) -> int:
12e5b992ffc6f92517c78a83760fc129
UNKNOWN
Given an array arr.  You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed.   Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Explanation: Choosing {3,7} will make the new ...
["from heapq import *\nfrom collections import Counter\n\nclass Solution:\n def minSetSize(self, arr: List[int]) -> int:\n \n counter = Counter(arr)\n size = len(arr)\n \n # unique elements (remove half of them)\n if len(counter) == size:\n return (size - 1) // 2 ...
{"fn_name": "minSetSize", "inputs": [[[3, 3, 3, 3, 5, 5, 5, 2, 2, 7]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
63,661
class Solution: def minSetSize(self, arr: List[int]) -> int:
1eaca010cfb6a7569bd3705491f8670d
UNKNOWN
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 Output: True Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal su...
["class Solution:\n def canPartitionKSubsets(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n target,rem=divmod(sum(nums),k)\n if rem or max(nums)>target: return False\n n=len(nums)\n seen=[0]*n\n ...
{"fn_name": "canPartitionKSubsets", "inputs": [[[5, 4, 3, 3, 2, 2, 1], 4]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
13,577
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
b46b0261ddaa7e4bcbfa71afbb515fd7
UNKNOWN
Given an array of integers A, find the number of triples of indices (i, j, k) such that: 0 <= i < A.length 0 <= j < A.length 0 <= k < A.length A[i] & A[j] & A[k] == 0, where & represents the bitwise-AND operator.   Example 1: Input: [2,1,3] Output: 12 Explanation: We could choose the following i, j, k triples: (i=0, ...
["class Solution:\n def countTriplets(self, A: List[int]) -> int:\n counters = [0] * (1 << 16)\n counters[0] = len(A)\n for num in A:\n mask = (~num) & ((1 << 16) - 1)\n sm = mask\n while sm != 0:\n counters[sm] += 1\n sm = (sm - 1) ...
{"fn_name": "countTriplets", "inputs": [[[2, 1, 3]]], "outputs": [12]}
INTERVIEW
PYTHON3
LEETCODE
34,281
class Solution: def countTriplets(self, A: List[int]) -> int:
92290cf61858310e567dbb4c79151521
UNKNOWN
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C. Here, a circular array means the end of the array connects to the beginning of the array.  (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.) Also, a subarray may only in...
["class Solution:\n def maxSubarraySumCircular(self, A: List[int]) -> int:\n N = len(A)\n if(N==0):\n return 0\n curr_max = A[0]\n global_max = A[0]\n curr_min = A[0]\n global_min = A[0]\n flag = 0 \n if(A[0]>=0):\n flag=1\n \n f...
{"fn_name": "maxSubarraySumCircular", "inputs": [[[-2, 3, -2, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
102,690
class Solution: def maxSubarraySumCircular(self, A: List[int]) -> int:
a0cda6a98de13b43e67bbc29539dd955
UNKNOWN
Given a string s, determine if it is valid. A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times: Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note...
["class Solution:\n def isValid(self, s: str) -> bool:\n if not s:\n return True\n return self.isValid(s.replace('abc', '')) if s.replace('abc', '') != s else False\n", "class Solution:\n def isValid(self, S: str) -> bool:\n stack = []\n for i in S:\n if i == 'c':...
{"fn_name": "isValid", "inputs": [["\"aabcbc\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
15,648
class Solution: def isValid(self, s: str) -> bool:
6cd927dba0002ab2b546fe77b44fb08a
UNKNOWN
You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters. You are also given an integer maxCost. Return the maximum length of a substring of s t...
["class Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n dist = [ abs( ord(s[i]) - ord(t[i]) ) for i in range(len(s))]\n \n# i = 0\n# cur = 0\n# res = 0\n# for j in range(len(s)):\n# cur += dist[j]\n# while cur>maxCost...
{"fn_name": "equalSubstring", "inputs": [["\"abcd\"", "\"bcdf\"", 3]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
18,669
class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
e0842cfd6329253f870937cb9e5be510
UNKNOWN
Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
["class Solution:\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n longest_streak = 0\n num_set = set(nums)\n for num in num_set:\n if num - 1 not in num_set:\n current_num = num\n ...
{"fn_name": "longestConsecutive", "inputs": [[[100, 4, 200, 1, 3, 2]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
14,696
class Solution: def longestConsecutive(self, nums: List[int]) -> int:
59e930796ea1d1463aa33baa6dce7ed6
UNKNOWN
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is guaranteed that for the given constraints we can always find such Fibonacci numbers th...
["class Solution:\n def findMinFibonacciNumbers(self, k: int) -> int:\n fib = [1, 1] # initializing a Fibonacci table with F[0] and F[1]\n i = 1 # index that will represent the last filled index of table\n temp = fib[0] + fib[1] # initial value of values to be appended\n while temp < k: #...
{"fn_name": "findMinFibonacciNumbers", "inputs": [[7]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
7,483
class Solution: def findMinFibonacciNumbers(self, k: int) -> int:
bfa354fc92cd4a7612aa5b055e3e6382
UNKNOWN
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? Example: Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ ...
["class Solution:\n hash = {}\n def numTrees(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # return base case\n if n == 0:\n return 1\n if n == 1 or n == 2:\n return n\n \n # try fetching from hash\n ...
{"fn_name": "numTrees", "inputs": [[3]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
8,035
class Solution: def numTrees(self, n: int) -> int:
3d99f30299dbd0e1fed5fb975351f806
UNKNOWN
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array A of integer...
["class Solution:\n def longestMountain(self, A: List[int]) -> int:\n up=0\n down=0\n ans=0\n for i in range(0,len(A)-1):\n if A[i]<A[i+1]:\n if down==0:\n up+=1\n else:\n up=1\n down=0\n ...
{"fn_name": "longestMountain", "inputs": [[[2, 1, 4, 7, 3, 2, 5]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
30,200
class Solution: def longestMountain(self, A: List[int]) -> int:
0661bbe79e8a9264493ddf490304d5c4
UNKNOWN
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above...
["class Solution:\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n def f(n):\n ret = 1\n for i in range(1, n+1):\n ret *= i\n return ret\n return f(m+n-2)//(f(m-1...
{"fn_name": "uniquePaths", "inputs": [[3, 7]], "outputs": [28]}
INTERVIEW
PYTHON3
LEETCODE
7,151
class Solution: def uniquePaths(self, m: int, n: int) -> int:
4c98ed4a78bde60402241113e9ea345b
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]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's ...
["class Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n # left = 0\n # right = len(nums) - 1\n # while left <= right: \n # mid = int((left + right)/2)\n # ...
{"fn_name": "search", "inputs": [[[4, 5, 6, 7, 0, 1, 2], 0]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
13,322
class Solution: def search(self, nums: List[int], target: int) -> int:
017dde9c5c521759d9df555cfd5a45a4
UNKNOWN
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue. For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s. Now your task is to find the maximum number of strin...
["class Solution:\n def getMax(self, arr, m, n):\n res = 0\n \n for e in arr:\n if m >= e[0] and n >= e[1]:\n res += 1\n m -= e[0]\n n -= e[1]\n \n return res\n \n def findMaxForm(self, strs, m, n):\n \"\"\"\n :t...
{"fn_name": "findMaxForm", "inputs": [[["\"10\"", "\"0001\"", "\"111001\"", "\"1\"", "\"0\""], 5, 3]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
2,913
class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
071d7a6e55c5187993e59644c7d3d4db
UNKNOWN
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. Th...
["class Solution:\n def PredictTheWinner(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if not nums: return True\n n = len(nums)\n if n & 1 == 0: return True\n \n dp = [0] * n\n for i in range(n-1, -1, -1):\n ...
{"fn_name": "PredictTheWinner", "inputs": [[[1, 5, 2]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
10,778
class Solution: def PredictTheWinner(self, nums: List[int]) -> bool:
660a65ca7b00f6d8f2b3a8cdba86672a
UNKNOWN
Given a list of non negative integers, arrange them such that they form the largest number. Example 1: Input: [10,2] Output: "210" Example 2: Input: [3,30,34,5,9] Output: "9534330" Note: The result may be very large, so you need to return a string instead of an integer.
["class Solution:\n def largestNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: str\n \"\"\"\n nums = [str(n) for n in nums]\n \n nums.sort(reverse=True)\n \n for i in range(1, len(nums)):\n if len(nums[i-1]) > len(num...
{"fn_name": "largestNumber", "inputs": [[[10, 2]]], "outputs": ["210"]}
INTERVIEW
PYTHON3
LEETCODE
12,370
class Solution: def largestNumber(self, nums: List[int]) -> str:
7ab77f62dd6ea04e3489c79312d8b53c
UNKNOWN
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the t...
["class Solution:\n def predictPartyVictory(self, senate):\n \"\"\"\n :type senate: str\n :rtype: str\n \"\"\"\n num = 0 # num of Reeding R\n while ('R' in senate and 'D' in senate):\n res = []\n for i in senate:\n if i=='R':\n...
{"fn_name": "predictPartyVictory", "inputs": [["\"RD\""]], "outputs": ["Dire"]}
INTERVIEW
PYTHON3
LEETCODE
5,147
class Solution: def predictPartyVictory(self, senate: str) -> str:
d2dde31db62459a28c051da017d52359
UNKNOWN
There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones. A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles. Find the minimum cost to merge all piles of stones into one pile.  If it is impossi...
["class Solution:\n def mergeStones(self, stones: List[int], K: int) -> int:\n n = len(stones)\n if (n - 1) % (K - 1) != 0:\n return -1\n prefix = [0]\n for s in stones:\n prefix.append(prefix[-1] + s)\n @lru_cache(None)\n def dp(i, j):\n if ...
{"fn_name": "mergeStones", "inputs": [[[3, 2, 4, 1], 2]], "outputs": [20]}
INTERVIEW
PYTHON3
LEETCODE
33,870
class Solution: def mergeStones(self, stones: List[int], K: int) -> int:
924d1c622b86ba29d2242ac112a22c0e
UNKNOWN
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3, t = 0 Output: true Example 2: Input: n...
["class Solution:\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n if len(nums) < 2 or k <= 0 or t < 0: return False\n if t == 0:\n visited = set...
{"fn_name": "containsNearbyAlmostDuplicate", "inputs": [[[1, 2, 3, 1], 3, 0]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
8,920
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
6462e71641b6b48dfc7448db2ef196a2
UNKNOWN
Given a string s, return the maximum number of unique substrings that the given string can be split into. You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique. A substrin...
["class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n self.x, n = 0, len(s)\n def maxUniqueSplit_(i=0, S=set()):\n if s[i:] not in S:\n self.x = max(self.x, len(S) + 1)\n \n for j in range(i + 1, n):\n if s[i : j] not in S and len(...
{"fn_name": "maxUniqueSplit", "inputs": [["\"ababccc\""]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
139,388
class Solution: def maxUniqueSplit(self, s: str) -> int:
be125d0cea00cc53f951fb843e486e98
UNKNOWN
Given an array of unique integers, each integer is strictly greater than 1. We make a binary tree using these integers and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of it's children. How many binary trees can we make?  Return the answer modu...
["class Solution:\n def numFactoredBinaryTrees(self, A: List[int]) -> int:\n \n mod = 10**9 + 7\n\n nums_set = set(A)\n nums = A.copy()\n nums.sort()\n counts = {}\n total = 0\n\n for n in nums:\n n_count = 1\n for d in nums:\n ...
{"fn_name": "numFactoredBinaryTrees", "inputs": [[[2, 4]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
50,634
class Solution: def numFactoredBinaryTrees(self, A: List[int]) -> int:
c3f51768a71d5ae47b65498af56377d0
UNKNOWN
Implement pow(x, n), which calculates x raised to the power n (xn). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note: -100.0 < x < 100.0 n is a 32-bit signed ...
["class Solution:\n def myPow(self, x, n):\n \"\"\"\n :type x: float\n :type n: int\n :rtype: float\n \"\"\"\n if n == 0:\n return 1\n if abs(n) == 1:\n if n == 1:\n return x\n else:\n return ...
{"fn_name": "myPow", "inputs": [[2.0, 10]], "outputs": [1024.0]}
INTERVIEW
PYTHON3
LEETCODE
6,705
class Solution: def myPow(self, x: float, n: int) -> float:
b208a1fa22089006bdc709e1a9ad5db0
UNKNOWN
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. An array A is a zigzag array if either: Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ... OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A...
["class Solution:\n def movesToMakeZigzag(self, nums):\n n = len(nums)\n res0 = 0\n for i in range(0, n, 2):\n nei = min(nums[j] for j in [i - 1, i + 1] if 0 <= j <= n-1)\n if nums[i] >= nei:\n res0 += nums[i] - nei + 1\n res1 = 0\n for i in ran...
{"fn_name": "movesToMakeZigzag", "inputs": [[[1, 2, 3]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
3,870
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int:
c03c0f4f8d143995fba080c59f088689
UNKNOWN
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False. ...
["class Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n n = nums[0]\n \n for i in nums:\n n = gcd(i,n)\n \n if n==1:\n return True\n return False\n", "class Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ...
{"fn_name": "isGoodArray", "inputs": [[[12, 5, 7, 23]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
16,306
class Solution: def isGoodArray(self, nums: List[int]) -> bool: