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
b03584db111705b28ce62085322db3dc
UNKNOWN
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0. During each playe...
["class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n N = len(graph)\n\n # What nodes could play their turn to\n # arrive at node (mouse, cat, turn) ?\n def parents(mouse, cat, turn):\n prev_turn = 3 - turn\n if prev_turn == MOUSE: \n ...
{"fn_name": "catMouseGame", "inputs": [[[[2, 5], [3], [0, 4, 5], [1, 4, 5], [2, 3], [0, 2, 3], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
146,024
class Solution: def catMouseGame(self, graph: List[List[int]]) -> int:
84efedc0788eb495f9f23d312e1f0c8c
UNKNOWN
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
["class Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n nums = nums1 + nums2\n nums.sort()\n if len(nums) % 2 == 1:\n return float(nums[len(nu...
{"fn_name": "findMedianSortedArrays", "inputs": [[[1, 3], [2]]], "outputs": [2.0]}
INTERVIEW
PYTHON3
LEETCODE
1,634
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
fe342a323d5acbd0283cf7113efd6d4a
UNKNOWN
Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Inpu...
["class Solution:\n def integerReplacement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n '''\n if n == 1:\n return 0\n if not (n & 1):\n return self.integerReplacement(n//2) + 1\n return min(self.integerReplacement(...
{"fn_name": "integerReplacement", "inputs": [[8]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
6,265
class Solution: def integerReplacement(self, n: int) -> int:
fa78880de401293ee0b93ad418db8b7b
UNKNOWN
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how ma...
["class Solution:\n def bulbSwitch(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0:\n return 0\n else:\n return int(n**0.5)\n \n", "class Solution:\n def bulbSwitch(self, n):\n \"\"\"\n :type n: ...
{"fn_name": "bulbSwitch", "inputs": [[3]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
2,713
class Solution: def bulbSwitch(self, n: int) -> int:
d1bbcc2b93e4869714e677d580f96c0e
UNKNOWN
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.   Example 1: Input: s = "eleetminicoworoep" Output: 13 Explanation: The longest substring is "leetminicowor" which contains two each of th...
["class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n s = s + 'a'\n bits, dp = {'a':0,'e':1,'i':2,'o':3,'u':4}, {0:-1}\n res = 0\n key = 0\n for i, char in enumerate(s): \n if char in bits:\n if key in dp:\n ...
{"fn_name": "findTheLongestSubstring", "inputs": [["\"eleetminicoworoep\""]], "outputs": [13]}
INTERVIEW
PYTHON3
LEETCODE
61,730
class Solution: def findTheLongestSubstring(self, s: str) -> int:
6aa60083e80dd0247df2298e0d7ffeca
UNKNOWN
Given a string s, return the last substring of s in lexicographical order.   Example 1: Input: "abab" Output: "bab" Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". Example 2: Input: "leetcode" Output: "tcode"   Note: 1 <= s.length <= 4 *...
["class Solution:\n def lastSubstring(self, s: str) -> str:\n #mx = \\\"\\\"\n #for i in range(len(s)):\n # mx = max(mx,s[i:])\n #return mx\n index = {c: i for i, c in enumerate(sorted(set(s)))}\n cur, radix, max_val, max_i = 0, len(index), 0, 0\n for i in range(le...
{"fn_name": "lastSubstring", "inputs": [["\"abab\""]], "outputs": ["bab\""]}
INTERVIEW
PYTHON3
LEETCODE
159,586
class Solution: def lastSubstring(self, s: str) -> str:
4032e3a94f135fbd87d159636a135f9c
UNKNOWN
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
["class Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n size = len(s)\n if size <= 1 or s == s[::-1]:\n return s\n start, maxlen = 0, 1\n for idx in range(1, size):\n add2 = s...
{"fn_name": "longestPalindrome", "inputs": [["\"babad\""]], "outputs": ["bab"]}
INTERVIEW
PYTHON3
LEETCODE
6,952
class Solution: def longestPalindrome(self, s: str) -> str:
3fd5db0c06513e89dece0b7be650e63f
UNKNOWN
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.   Example 1: Input: arr = [1,2,3,4], difference = 1 Output: 4 Explanation: The longest arithm...
["from collections import defaultdict\n\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n count_dict = defaultdict(int)\n for num in arr:\n count_dict[num] = count_dict[num-difference] + 1\n return max(count_dict.values())\n", "class Solution:\...
{"fn_name": "longestSubsequence", "inputs": [[[1, 2, 3, 4], 1]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
46,745
class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int:
6a9b185bf598fb558c7f39927d0b6b79
UNKNOWN
You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image.  After, the over...
["class Solution:\n def largestOverlap(self, A, B) -> int:\n leng = len(A[0])\n\n # convert A, B to binary\n a = 0\n b = 0\n for i in range(0, leng * leng):\n row = int(i % leng)\n col = int(i / leng)\n a = (a << 1) + A[col][row]\n b = (b...
{"fn_name": "largestOverlap", "inputs": [[[[1, 1, 0], [0, 1, 0], [0, 1, 0], [], []], [[0, 0, 0], [0, 1, 1], [0, 0, 1], [], []]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
34,668
class Solution: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
2133d7451a004c42b79ea8f042d6c272
UNKNOWN
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero. Example 1: Input: dividend = 10, divisor = 3 Output: 3 Example 2: Input: dividend = 7, d...
["class Solution:\n def get_half(self,dividend,divisor):\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n num = divisor\n num_temp=0\n result=1\n result_temp=0\n while (num<=dividend):\n num_temp=num\n num+=num\n ...
{"fn_name": "divide", "inputs": [[10, 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
9,101
class Solution: def divide(self, dividend: int, divisor: int) -> int:
dcb3cbb82bb8f62d6383330e2971d305
UNKNOWN
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this in a way such that the resulting number is a power of 2.   Example 1: Input: 1 Output: true Example 2: Input: 10 Output: false E...
["class Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n \n n_len = len(str(n))\n n = Counter(str(n))\n \n p = 1\n while len(str(p)) <= n_len:\n if len(str(p)) == n_len and Counter(str(p)) == n:\n return True\n p *= 2\n \...
{"fn_name": "reorderedPowerOf2", "inputs": [[1]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
16,930
class Solution: def reorderedPowerOf2(self, N: int) -> bool:
6913edbad9b9343ede2bd46f48d70f53
UNKNOWN
Given n orders, each order consist in pickup and delivery services.  Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: Unique order (P1, D1), Delivery 1 al...
["class Solution:\n def countOrders(self, n: int) -> int:\n \n if n == 1:\n return 1\n \n \n p = (n-1)*2+1\n \n dp = [0 for i in range(n+1)]\n dp[1] = 1\n M= 10**9+7\n for i in range(2,n+1):\n \n p = (i-1)*2+1\n ...
{"fn_name": "countOrders", "inputs": [[1]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
22,063
class Solution: def countOrders(self, n: int) -> int:
2e65d257de709495f9c90b7e606d1d16
UNKNOWN
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks. We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions.  We cannot walk outside the grid, or walk into a wal...
["import heapq\nfrom collections import deque, defaultdict\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n m,n = len(grid),len(grid[0])\n key_lock_loc = {ch:(i,j) for i,row in enumerate(grid) for j,ch in enumerate(row) if ch not in {'.','#'}}\n key_cnt = sum(key_lock ...
{"fn_name": "shortestPathAllKeys", "inputs": [[["\"@.a.#\"", "\"###.#\"", "\"b.A.B\""]]], "outputs": [8]}
INTERVIEW
PYTHON3
LEETCODE
109,007
class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int:
35fbdc28241f15131ad237be8e5785cf
UNKNOWN
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") a...
["class Solution:\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n :rtype: str\n \"\"\"\n s_count = collections.defaultdict(int)\n g_count = collections.defaultdict(int)\n bull_cnt = 0\n # first iteration ca...
{"fn_name": "getHint", "inputs": [["\"1807\"", "\"7810\""]], "outputs": ["3A3B"]}
INTERVIEW
PYTHON3
LEETCODE
7,494
class Solution: def getHint(self, secret: str, guess: str) -> str:
b43a38e314c93e1f292eb5cfbcdd5eba
UNKNOWN
Given a string S, count the number of distinct, non-empty subsequences of S . Since the result may be large, return the answer modulo 10^9 + 7.   Example 1: Input: "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". Example 2: Input: "aba" Output: 6 Explanation: Th...
["class Solution:\n def distinctSubseqII(self, s: str) -> int:\n n = len(s)\n MOD = 10**9 + 7\n seen = dict()\n \n a = 1\n for i in range(n):\n char = s[i]\n b = 2 * a\n if char in seen:\n b -= seen[char]\n \n ...
{"fn_name": "distinctSubseqII", "inputs": [["\"abc\""]], "outputs": [30]}
INTERVIEW
PYTHON3
LEETCODE
11,188
class Solution: def distinctSubseqII(self, S: str) -> int:
df998df14997908ab07a6c3edd25148a
UNKNOWN
Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A. Since the answer may be large, return the answer modulo 10^9 + 7.   Example 1: Input: [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimum...
["class Solution:\n def sumSubarrayMins(self, A: List[int]) -> int:\n stack = []\n result = 0\n A = [0] + A + [0]\n\n for i, x in enumerate(A):\n while stack and x < A[stack[-1]]:\n j = stack.pop()\n result += A[j] * (i - j) * (j - stack[-1])\n ...
{"fn_name": "sumSubarrayMins", "inputs": [[[3, 1, 2, 4, 0]]], "outputs": [17]}
INTERVIEW
PYTHON3
LEETCODE
93,673
class Solution: def sumSubarrayMins(self, A: List[int]) -> int:
0077e874aaf37b736aa537fa939b19a8
UNKNOWN
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers Return True if its possible otherwise return False.   Example 1: Input: nums = [1,2,3,3,4,4,5,6], k = 4 Output: true Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]...
["class Solution:\n def isPossibleDivide(self, s: List[int], k: int) -> bool:\n if len(s) % k != 0:\n return False\n \n ctr = collections.Counter(s)\n \n for _ in range(len(s) // k):\n mn = []\n for i in ctr:\n if mn == [] and ctr[i] ...
{"fn_name": "isPossibleDivide", "inputs": [[[1, 2, 3, 3, 4, 4, 5, 6], 4]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
103,844
class Solution: def isPossibleDivide(self, nums: List[int], k: int) -> bool:
2f6ac748a2f23b4b9625ce3a7812045e
UNKNOWN
Given an array of integers arr and two integers k and threshold. Return the number of sub-arrays of size k and average greater than or equal to threshold.   Example 1: Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 Output: 3 Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively...
["class Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n if len(arr) < k:\n return 0\n bar = k * threshold\n total = 0\n window = sum(arr[:k])\n if window >= bar:\n total += 1\n for i in range(k, len(arr)):\n ...
{"fn_name": "numOfSubarrays", "inputs": [[[2, 2, 2, 2, 5, 5, 5, 8], 3, 4]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
32,384
class Solution: def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
ab9670d6c8d5c0b76536618ac9f0379f
UNKNOWN
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.   Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 n...
["class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n if not 0 in nums:\n return len(nums) - 1\n ans = 0\n tot = 0\n prev = 0\n \n for n in nums:\n if n == 1:\n tot += 1\n else:\n ans = max(tot...
{"fn_name": "longestSubarray", "inputs": [[[1, 1, 0, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
52,969
class Solution: def longestSubarray(self, nums: List[int]) -> int:
275c54a2754d71963316c8cc4d9360fa
UNKNOWN
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.   Example 1: Input: A = [4,5,0,-2,-3,1], K = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by K = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] ...
["# Calculate the prefix sum and count it.\n# In c++ and java, a % K + K takes care of the cases where a < 0.\n# Python\n\nclass Solution: \n def subarraysDivByK(self, A, K):\n res = 0\n prefix = 0\n count = [1] + [0] * K\n for a in A:\n prefix = (prefix + a) % K\n r...
{"fn_name": "subarraysDivByK", "inputs": [[[4, 5, 0, -2, -3, 1], 5]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
27,272
class Solution: def subarraysDivByK(self, A: List[int], K: int) -> int:
96b4d7821a11f33fbc818a11c912fccb
UNKNOWN
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges (n) is divisible by 2 then you can eat  n/2 oranges. If the number of remaining oranges (n) is divisible by 3 then you can eat  2*(n/3) oranges. You can only choose ...
["import functools\nclass Solution:\n @functools.lru_cache()\n def minDays(self, n: int) -> int:\n if n <= 1:\n return n\n \n return 1 + min(n%2 + self.minDays(n//2), n%3 + self.minDays(n//3))\n \n", "memo={}; f=min\nclass Solution:\n def minDays(self, n: int) -> int:...
{"fn_name": "minDays", "inputs": [[10]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
127,308
class Solution: def minDays(self, n: int) -> int:
f21851472fe6df87637a0a329db70a6d
UNKNOWN
An encoded string S is given.  To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeatedly w...
["class Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n size = 0\n # Find size = length of decoded string\n for c in S:\n if c.isdigit():\n size *= int(c)\n else:\n size += 1\n for c in reversed(S):\n K %= size\n...
{"fn_name": "decodeAtIndex", "inputs": [["\"leet2code3\"", 10]], "outputs": ["t"]}
INTERVIEW
PYTHON3
LEETCODE
4,852
class Solution: def decodeAtIndex(self, S: str, K: int) -> str:
c99841acc864165f10a42aa2638d4b26
UNKNOWN
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are given an integer m and you need to ...
["class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n A = arr\n if m == len(A): \n return m\n length = [0] * (len(A) + 2)\n res = -1\n for i, a in enumerate(A):\n left, right = length[a - 1], length[a + 1]\n if left == m or ...
{"fn_name": "findLatestStep", "inputs": [[[3, 5, 1, 2, 4], 1]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
763,954
class Solution: def findLatestStep(self, arr: List[int], m: int) -> int:
b0fd1324c5bad6020a34555273dc028a
UNKNOWN
A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd. That is, the subarray is turbulent if the comparison sign flips between each...
["class Solution:\n def maxTurbulenceSize(self, A: List[int]) -> int:\n if len(A) == 1: return 1\n prev = A[1]\n maxcount = count = 1 + int(A[0] != A[1])\n print(count)\n lastcomp = A[0] < A[1]\n \n for a in A[2:]:\n comp = prev < a\n if prev == ...
{"fn_name": "maxTurbulenceSize", "inputs": [[[9, 4, 2, 10, 7, 8, 8, 1, 9]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
76,818
class Solution: def maxTurbulenceSize(self, A: List[int]) -> int:
33ca677418baafcd53cdecfa3ebf1b91
UNKNOWN
There is a special square room with mirrors on each of the four walls.  Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th rec...
["class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n while p % 2 == 0 and q % 2 == 0:\n p = p // 2\n q = q // 2\n if p % 2 == 1 and q % 2 == 0:\n return 0\n elif p % 2 == 1 and q % 2 == 1:\n return 1\n else :\n ret...
{"fn_name": "mirrorReflection", "inputs": [[2, 1]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
13,461
class Solution: def mirrorReflection(self, p: int, q: int) -> int:
1402a04eb3e6f1b4fcc412cbcddb1236
UNKNOWN
Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers? Example 1: Input: 5 Output: 2 Explanation: 5 = 5 = 2 + 3 Example 2: Input: 9 Output: 3 Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 Example 3: Input: 15 Output: 4 Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 N...
["class Solution:\n def consecutiveNumbersSum(self, N: int) -> int:\n res = 1\n \n # Remove all even factors\n while N % 2 == 0:\n N //= 2\n \n # Count all odd factors\n idx = 3 \n while idx * idx <= N:\n count = 0\n \n ...
{"fn_name": "consecutiveNumbersSum", "inputs": [[5]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
46,412
class Solution: def consecutiveNumbersSum(self, N: int) -> int:
037a67366ca6d3333396072bc2c9d2b8
UNKNOWN
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diago...
["class Solution:\n def minSwaps(self, grid: List[List[int]]) -> int:\n start=1\n swap=0\n n=len(grid)\n zeros_ingrid=n-1\n while zeros_ingrid>0:\n swapped_grid=False\n for i in range(len(grid)):\n if sum(grid[i][start:])==0:\n ...
{"fn_name": "minSwaps", "inputs": [[[[0, 0, 1], [1, 1, 0], [1, 0, 0], [], []]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
4,804
class Solution: def minSwaps(self, grid: List[List[int]]) -> int:
e6651c131c0888030fbf72b902888efe
UNKNOWN
There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if:  (rating[i] < rating[j] < rating[k]) or (ratin...
["class Solution:\n def increment_index(self, nums, index):\n index += 1\n while index < len(nums):\n nums[index] += 1\n index += (index & -index)\n\n def prefix_sum(self, nums, index):\n index += 1\n current_sum = 0\n while index > 0:\n current_...
{"fn_name": "numTeams", "inputs": [[[2, 5, 3, 4, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
248,636
class Solution: def numTeams(self, rating: List[int]) -> int:
a48fa007424545032ff273f5c1cbdb57
UNKNOWN
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will: Take their own seat if it is still available,  Pick other seats randomly when they find their seat occupied  What is the probability that the n-th person...
["class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1 / min(n, 2.0) \n \n", "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n if n == 1:\n return float(1)\n return float(0.5)", "class Solution:\n def nthPersonGetsNthSeat(self,...
{"fn_name": "nthPersonGetsNthSeat", "inputs": [[1]], "outputs": [1.0]}
INTERVIEW
PYTHON3
LEETCODE
10,538
class Solution: def nthPersonGetsNthSeat(self, n: int) -> float:
79b6f0771ad2f7f491c58bbe960c2608
UNKNOWN
Given an array nums, you are allowed to choose one element of nums and change it by any value in one move. Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.   Example 1: Input: nums = [5,3,2,4] Output: 0 Explanation: Change the array [5,3,2,4] to [2,2,2,2]. Th...
["class Solution:\n def minDifference(self, nums: List[int]) -> int:\n if len(nums) <= 4:\n return 0\n else:\n # nums = sorted(nums)\n nums.sort()\n threeZero = nums[-1] - nums[3]\n twoOne = nums[-2] - nums[2]\n oneTwo = nums[-3] - nums[...
{"fn_name": "minDifference", "inputs": [[[2, 3, 4, 5]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
35,748
class Solution: def minDifference(self, nums: List[int]) -> int:
bdfe05cf8bab82713b973c5791283dc7
UNKNOWN
Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.   Example 1: Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Remove the single 4, only 5 is left. Example 2: Input: arr = [4,3,1,1,3,3,2], k = 3 Output: 2 Explanation: Remove 4, 2 and eithe...
["# O(n) time and space\n# Hashmap and array\n# Count number then count occurrence:\n# Count the occurrences of each number using HashMap;\n# Keep a count of different occurences\n# From small to big, for each unvisited least frequent element, deduct from k the multiplication with the number of elements of same occurre...
{"fn_name": "findLeastNumOfUniqueInts", "inputs": [[[5, 5, 4], 1]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
77,571
class Solution: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
db6705901cb1239ff7be4f4e6cc125ee
UNKNOWN
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Input: "bcabc" Output: "abc" Example 2: Input: "cbacdcbc" Output: "a...
["class Solution:\n def removeDuplicateLetters(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n rindex = {c: i for i, c in enumerate(s)}\n result = ''\n for i, c in enumerate(s):\n if c not in result:\n while c < result[-1...
{"fn_name": "removeDuplicateLetters", "inputs": [["\"bcabc\""]], "outputs": ["\"abc"]}
INTERVIEW
PYTHON3
LEETCODE
5,850
class Solution: def removeDuplicateLetters(self, s: str) -> str:
e19eed4babcf147b37185de754d9b1ed
UNKNOWN
Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. Example 1: Input: [23, 2, 4, 6, 7], k=6 Output: True Explanation: Because [2, 4] is...
["class Solution:\n def checkSubarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if k==0:\n j=0\n for i in range(0,len(nums)):\n if nums[i]==0:\n if j<i:\n ...
{"fn_name": "checkSubarraySum", "inputs": [[[23, 2, 4, 6, 7], 6]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
9,548
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool:
45f233a62271108944da6dc86eafbdf8
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. You may assume no duplicate exists in the array. Example 1: Input: [3,4,5,1,2] Output: 1 Example 2: Input: [4,5,6,7,0,1,2] Output: 0
["class Solution:\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) <= 3:\n return min(nums)\n lo = 0\n hi = len(nums) - 1\n mid = (hi + lo) // 2\n if nums[mid] < nums[mid-1] and nums[...
{"fn_name": "findMin", "inputs": [[[3, 4, 5, 1, 2]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
7,700
class Solution: def findMin(self, nums: List[int]) -> int:
675289cda9c7cb5c86e50e8bb839b231
UNKNOWN
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. This is how the UTF-8 enc...
["class Solution:\n def validUtf8(self, data):\n \"\"\"\n :type data: List[int]\n :rtype: bool\n \"\"\"\n count=0\n for x in data:\n if count==0:\n if x>>5==0b110:\n count=1\n elif x>>4==0b1110:\n ...
{"fn_name": "validUtf8", "inputs": [[[197, 130, 1]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
9,829
class Solution: def validUtf8(self, data: List[int]) -> bool:
f41e90cd04547302e1f6bf463ca94200
UNKNOWN
Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. In general a rational number can be represented using up to three parts: an integer part, a ...
["import math\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n if len(S) == 0 or len(T) == 0:\n return False\n def process(s):\n if s[-1] == '.':\n s = s[:-1]\n stack, repeat_9 = [], False\n for i, x in enumerate(s):\n ...
{"fn_name": "isRationalEqual", "inputs": [["\"0.(52)\"", "\"0.5(25)\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
1,269
class Solution: def isRationalEqual(self, S: str, T: str) -> bool:
5cb991edc943918b65eb0a68e03349ca
UNKNOWN
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maxim...
["class Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n N = len(jobDifficulty)\n if N < d: \n return -1\n \n dp = [jobDifficulty[0]]\n for j in jobDifficulty[1:]:\n dp.append(max(dp[-1], j))\n\n for i in range(1, d):\n ...
{"fn_name": "minDifficulty", "inputs": [[[6, 5, 4, 3, 2, 1], 2]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
166,574
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
036c13087e81b70a7cfbff86c53bfdad
UNKNOWN
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that has been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. (For example: houses = [1,2,2,3,3...
["class Solution:\n def minCost(self, houses: List[int], Cost: List[List[int]], m: int, n: int, target: int) -> int:\n @lru_cache(None)\n def dfs(i, j, k):\n if i == len(houses):\n if j == target:\n return 0\n else:\n return...
{"fn_name": "minCost", "inputs": [[[0, 0, 0, 0, 0], [[1, 10], [10, 1], [10, 1], [1, 10], [5, 1], [], []], 5, 2, 3]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
107,841
class Solution: def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
c8f654a768ef10971bb3237d401fae4c
UNKNOWN
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: 9973 Output: 9973 Explanation: No swap. Note: The give...
["class Solution:\n def maximumSwap(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n s = str(num)\n nums = [int(_) for _ in s]\n dp = [-1]*len(nums)\n for i in range(len(nums)-1,-1,-1):\n if i==len(nums)-1:\n d...
{"fn_name": "maximumSwap", "inputs": [[2736]], "outputs": [7236]}
INTERVIEW
PYTHON3
LEETCODE
8,101
class Solution: def maximumSwap(self, num: int) -> int:
dd3fcf6aa0ab9fa7bc771117f2086439
UNKNOWN
There is a strange printer with the following two special requirements: On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. Once the printer has used a color for the above operation, the same color cannot be used again...
["from collections import deque\n\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n grids = targetGrid\n num_to_range = dict()\n for i, row in enumerate(targetGrid):\n for j, val in enumerate(row):\n if val not in num_to_range:\n ...
{"fn_name": "isPrintable", "inputs": [[[[1, 1, 1, 1], [1, 2, 2, 1], [1, 2, 2, 1], [1, 1, 1, 1], [], []]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
37,636
class Solution: def isPrintable(self, targetGrid: List[List[int]]) -> bool:
92b997ea2fc33efb85434bc64c7eb1b4
UNKNOWN
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on th...
["class Solution:\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n if stones == []: return False\n if len(stones) == 1: return True\n diff = [0]*len(stones)\n \n for i in range(1,len(stones)):\n ...
{"fn_name": "canCross", "inputs": [[[0, 1, 3, 4, 5, 7, 9, 10, 12]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
4,027
class Solution: def canCross(self, stones: List[int]) -> bool:
561e1264a9872592eeec1eed6e2d3290
UNKNOWN
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each ki...
["class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n n, res = len(coins), amount + 1\n\n def dfs(index, target, cnt):\n nonlocal res\n if cnt + (target + coins[index] - 1) // coins[index] >= res:\n retur...
{"fn_name": "coinChange", "inputs": [[[1, 2, 5], 11]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
440,935
class Solution: def coinChange(self, coins: List[int], amount: int) -> int:
26e611ca1f0bfae995c6a79e854501e4
UNKNOWN
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a con...
["class Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n need = sum(nums) % p\n if need == 0:\n return 0\n pos = {0: -1}\n total = 0\n ans = float('inf')\n for i, num in enumerate(nums):\n total = (total + num) % p\n targe...
{"fn_name": "minSubarray", "inputs": [[[3, 1, 4, 2], 6]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
63,787
class Solution: def minSubarray(self, nums: List[int], p: int) -> int:
c80ccdbd2763dc16871f450344052657
UNKNOWN
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations. Note: Both the string's length and k will not exceed 1...
["class Solution:\n def characterReplacement(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n if s == \"\":\n return 0\n count = {}\n lo = 0\n hi = 0\n max_letter = 0\n for hi in range(len...
{"fn_name": "characterReplacement", "inputs": [["\"ABAB\"", 2]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
2,166
class Solution: def characterReplacement(self, s: str, k: int) -> int:
e41562de108fa261bb7d81663b0d3e63
UNKNOWN
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]]...
["class Solution:\n def arrayNesting(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n best = 0\n n = len(nums)\n p = []\n for i in range(len(nums)):\n j = i\n current = 0\n while nums[j] != -1:\...
{"fn_name": "arrayNesting", "inputs": [[[5,4,0,3,1,6,2]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
4,198
class Solution: def arrayNesting(self, nums: List[int]) -> int:
d9d96e87eb2d8e2de086cc743c5b0f94
UNKNOWN
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company has is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed that the subordination...
["class Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n def dfs(i):\n if manager[i] != -1:\n informTime[i] += dfs(manager[i])\n manager[i] = -1\n return informTime[i]\n return max(list(map(d...
{"fn_name": "numOfMinutes", "inputs": [[1, 0, [-1], [0]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
213,291
class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
be9c3d58786265ee2d579714962e60ab
UNKNOWN
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other ser...
["#[Runtime: 452 ms, faster than 97.27%] Hash\n#O(MN)\n#1. traverse all cells and mark server as (x, y)\n#2. put each server (x, y) into serveral bucket named x1, x2, .., and y1, y2, ..\n# e.g. each xbucket[x1] maintains the number of servers on line x1\n#3. enumerate all server (x', y'), and see if there is at least 2...
{"fn_name": "countServers", "inputs": [[[[1, 0], [0, 1], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
8,176
class Solution: def countServers(self, grid: List[List[int]]) -> int:
1b46446ff65c462aa0687d684f557441
UNKNOWN
You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 <= i < nums.length-1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array.   Example 1: Input...
["class Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n n = len(nums)\n base = sum([abs(nums[i] - nums[i+1]) for i in range(n - 1)])\n if (n <= 2):\n return base\n \n #best = base\n #for i in range(n-1):\n # for j in range(i+1, n):\...
{"fn_name": "maxValueAfterReverse", "inputs": [[[2, 3, 1, 5, 4]]], "outputs": [10]}
INTERVIEW
PYTHON3
LEETCODE
12,871
class Solution: def maxValueAfterReverse(self, nums: List[int]) -> int:
9553e54723182408a78809873548ec19
UNKNOWN
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array e...
["class Solution:\n def minOperations(self, n: int) -> int:\n return (n*n)>>2\n \n", "class Solution:\n def minOperations(self, n: int) -> int:\n if n % 2 == 0:\n return (n//2)*(n//2)\n else:\n return (n-1)*(1+(n-1)//2)//2", "class Solution:\n def minOp...
{"fn_name": "minOperations", "inputs": [[3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
24,038
class Solution: def minOperations(self, n: int) -> int:
60832cf80c4636fbd302813a5604415a
UNKNOWN
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example: Input: "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
["class Solution:\n def minCut(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # acceleration\n if s == s[::-1]: return 0\n if any(s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1] for i in range(1, len(s))): return 1\n # algorithm\n cut...
{"fn_name": "minCut", "inputs": [["\"aab\""]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
7,029
class Solution: def minCut(self, s: str) -> int:
86fc23e482aa74b8ec8c65c9c9a59fca
UNKNOWN
We are given a personal information string S, which may represent either an email address or a phone number. We would like to mask this personal information according to the following rules: 1. Email address: We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-...
["class Solution:\n def maskPII(self, S: str) -> str:\n if '@' in S:\n name, domain = S.split('@')\n return name[0].lower() + '*****' + name[-1].lower() + '@' + domain.lower()\n else:\n number = ''\n for c in S:\n if c.isdigit():\n ...
{"fn_name": "maskPII", "inputs": [["\"LeetCode@LeetCode.com\""]], "outputs": ["\"*****e@leetcode.com\""]}
INTERVIEW
PYTHON3
LEETCODE
1,849
class Solution: def maskPII(self, S: str) -> str:
decc1f64b9273fc9f25e0b33aea3fdc7
UNKNOWN
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.   Example 1: Input: nums = [21,4,7] Output: 32 Explanation: 21 has 4 divisors: 1, 3, 7, 21 4 has 3 divisors: 1, 2, 4 7 has 2 divisors: 1, 7 The answe...
["# 1390. Four Divisors\n# version 2, with optimized prime-finding.\n\nimport math\n\ndef remove (lst, index):\n assert lst\n tail = len (lst) - 1\n lst[index], lst[tail] = lst[tail], lst[index]\n lst.pop ()\n\ndef swap_min (lst):\n if not lst: return\n argmin = min (range (len (lst)), key = lambda i:...
{"fn_name": "sumFourDivisors", "inputs": [[[21, 4, 7]]], "outputs": [32]}
INTERVIEW
PYTHON3
LEETCODE
96,464
class Solution: def sumFourDivisors(self, nums: List[int]) -> int:
610c9aa92364b11ca36c24adc23fd154
UNKNOWN
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Example 1: Input: numerator = 1, denominator = 2 Output: "0.5" Example 2: Input: numerator = 2, denominator = 1 Outpu...
["class Solution:\n def fractionToDecimal(self, numerator, denominator):\n \"\"\"\n :type numerator: int\n :type denominator: int\n :rtype: str\n \"\"\"\n if numerator*denominator < 0:\n add_negative = True\n else:\n add_negative = Fals...
{"fn_name": "fractionToDecimal", "inputs": [[1, 2]], "outputs": ["0.5"]}
INTERVIEW
PYTHON3
LEETCODE
13,575
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str:
9871079b2fd57bd76e2623a7f403f84a
UNKNOWN
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no v...
["class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \n leftset, rightset = set(leftChild), set(rightChild)\n roots = []\n for i in range(n):\n if i not in leftset and i not in rightset: \n roots.ap...
{"fn_name": "validateBinaryTreeNodes", "inputs": [[4, [1, -1, 3, -1], [2, -1, -1, -1]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
94,500
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
ecd035aea2b73afbd831f20a8bc9ede3
UNKNOWN
Given an integer array A, and an integer target, return the number of tuples i, j, k  such that i < j < k and A[i] + A[j] + A[k] == target. As the answer can be very large, return it modulo 109 + 7.   Example 1: Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (A[i], A[j],...
["class Solution:\n def threeSumMulti(self, A: List[int], target: int) -> int:\n counter = collections.Counter(A)\n i, res, l, ckey = 0, 0, len(counter), sorted(list(counter.keys()))\n if target % 3 == 0:\n res += math.comb(counter[target // 3], 3)\n for i in range(l):\n ...
{"fn_name": "threeSumMulti", "inputs": [[[1, 1, 2, 2, 3, 3, 4, 4, 5, 5], 8]], "outputs": [20]}
INTERVIEW
PYTHON3
LEETCODE
45,314
class Solution: def threeSumMulti(self, A: List[int], target: int) -> int:
6531ec3ea281babf45d243293f9ee10a
UNKNOWN
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Examp...
["class Solution:\n def expandIsland(self, grid, i, j):\n edges = [(i, j)]\n while edges:\n next_edges = []\n for edge in edges:\n ei, ej = edge\n if ei >= 0 and ei < len(grid) and ej >= 0 and ej < len(grid[ei]) and grid[ei][ej] == '1':\n ...
{"fn_name": "numIslands", "inputs": [[[["\"1\"", "\"1\"", "\"1\"", "\"1\"", "\"0\""], ["\"1\"", "\"1\"", "\"0\"", "\"1\"", "\"0\""], ["\"1\"", "\"1\"", "\"0\"", "\"0\"", "\"0\""], ["\"0\"", "\"0\"", "\"0\"", "\"0\"", "\"0\""], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
1,009
class Solution: def numIslands(self, grid: List[List[str]]) -> int:
8ea534d75c459975ff130a5de75723c7
UNKNOWN
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [4,2,3,0,3,...
["class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n \n dq = collections.deque([start])\n visited = set([start])\n \n while dq:\n \n curr = dq.pop()\n \n if arr[curr] == 0:\n return True\n ...
{"fn_name": "canReach", "inputs": [[[4, 2, 3, 0, 3, 1, 2], 5]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
40,112
class Solution: def canReach(self, arr: List[int], start: int) -> bool:
d362a7438512018f15fcdc41e009e9c8
UNKNOWN
Given an array of integers arr. We want to select three indices i, j and k where (0 <= i < j <= k < arr.length). Let's define a and b as follows: a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k] Note that ^ denotes the bitwise-xor operation. Return the number of triplets (i, j and k) ...
["class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n n = len(arr)\n res = xors = 0\n freq = collections.defaultdict(int, {0:1})\n _sum = collections.defaultdict(int)\n for i in range(n):\n xors ^= arr[i]\n res += freq[xors] * i - _sum[xors]\n ...
{"fn_name": "countTriplets", "inputs": [[[2, 3, 1, 6, 7]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
53,317
class Solution: def countTriplets(self, arr: List[int]) -> int:
361f27e04e2422ed9931f5b1c1fd1f22
UNKNOWN
Given a list of words, list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. ...
["class Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n let=Counter(letters)\n sc={}\n for i in range(26):\n sc[chr(i+ord('a'))]=score[i]\n word={}\n for w in words:\n word[w]=Counter(w)\n self.ans=0...
{"fn_name": "maxScoreWords", "inputs": [[["\"dog\"", "\"cat\"", "\"dad\"", "\"good\""], ["\"a\"", "\"a\"", "\"c\"", "\"d\"", "\"d\"", "\"d\"", "\"g\"", "\"o\"", "\"o\""], [1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
20,362
class Solution: def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
f0347b7fbd3b31043ae96b088399f67c
UNKNOWN
Given the array nums consisting of n positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the n...
["class Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n # B: partial sum of A\n # C: partial sum of B\n # Use prefix sum to precompute B and C\n A = nums\n B, C = [0] * (n + 1), [0] * (n + 1)\n for i in range(n):\n B[i + 1]...
{"fn_name": "rangeSum", "inputs": [[[1, 2, 3, 4], 4, 1, 5]], "outputs": [13]}
INTERVIEW
PYTHON3
LEETCODE
106,176
class Solution: def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
e3ac2f8ab08b095ad4b2951888a64463
UNKNOWN
N cars are going to the same destination along a one lane road.  The destination is target miles away. Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road. A car can never pass another car ahead of it, but it can catch up to it, and driv...
["class Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n if not position:\n return 0\n \n posToSpeed = {position[i]: speed[i] for i in range(len(position))}\n position.sort()\n \n leaderTime = (target - position[-1]) / p...
{"fn_name": "carFleet", "inputs": [[12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
21,925
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
866db07c9146e5a9bd3340a93dc779e6
UNKNOWN
Given two positive integers n and k, the binary string  Sn is formed as follows: S1 = "0" Si = Si-1 + "1" + reverse(invert(Si-1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, t...
["class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n i = n - 1\n invert = False\n while i > 0:\n half_len = (2**(i + 1) - 1) // 2 \n if k == half_len + 1:\n return '1' if not invert else '0'\n \n if k > half_len:\n ...
{"fn_name": "findKthBit", "inputs": [[3, 1]], "outputs": ["0"]}
INTERVIEW
PYTHON3
LEETCODE
36,302
class Solution: def findKthBit(self, n: int, k: int) -> str:
d639e0a36876c2acab4dcb4515301b30
UNKNOWN
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,3,2] Output: 3 Example 2: Input: [0,1,...
["class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n a = set(nums)\n a = sum(a)*3 - sum(nums)\n return int(a/2)", "class Solution:\n def singleNumber(self, nums):\n return (3*sum(set(nums))-sum...
{"fn_name": "singleNumber", "inputs": [[[2, 2, 3, 2]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
5,942
class Solution: def singleNumber(self, nums: List[int]) -> int:
557bb953ed55d5a405e899c770d69dec
UNKNOWN
There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. The brick wall is represented by a list of rows. Each row is a list of integers r...
["class Solution:\n def leastBricks(self, wall):\n \"\"\"\n :type wall: List[List[int]]\n :rtype: int\n \"\"\"\n d = {}\n for i in wall:\n suma = 0\n for j in range(len(i)-1):\n suma += i[j]\n if suma in d:\n ...
{"fn_name": "leastBricks", "inputs": [[[[1, 2, 2, 1], [3, 1, 2], [1, 3, 2], [2, 4], [3, 1, 2], [1, 3, 1, 1], [], []]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
5,430
class Solution: def leastBricks(self, wall: List[List[int]]) -> int:
150e6b690000a0af48b549a647c0a141
UNKNOWN
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place  (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your poi...
["# https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/569521/7-python-approaches-with-Time-and-Space-analysis\nclass Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n r = min(arrLen, steps // 2 + 1)\n dp = [0, 1]\n for t in range(steps...
{"fn_name": "numWays", "inputs": [[3, 2]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
104,884
class Solution: def numWays(self, steps: int, arrLen: int) -> int:
a37452eca38f7050557b0befb8ae106f
UNKNOWN
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to th...
["class Solution(object):\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n size = len(nums)\n if size < 3:\n return 0\n nums.sort()\n i = 0 # fix the first inde...
{"fn_name": "threeSumClosest", "inputs": [[[-4, -1, 1, 2], 1]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
15,358
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int:
6e5af1936a63b54d9285cc164738a02b
UNKNOWN
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree.  (Recall that a node is a leaf if and only if it has 0 children.) The value of each non-leaf node is equal to...
["class Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n if not arr: return 0\n \n res = []\n\n while len(arr) > 1:\n temp_res = []\n temp_res = [arr[i]*arr[i+1] for i in range(len(arr)-1)]\n idx = temp_res.index(min(temp_res))\n\n ...
{"fn_name": "mctFromLeafValues", "inputs": [[[6, 2, 4]]], "outputs": [32]}
INTERVIEW
PYTHON3
LEETCODE
56,592
class Solution: def mctFromLeafValues(self, arr: List[int]) -> int:
3a024a4f81c4569ca7a9bc4ac67ba818
UNKNOWN
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not...
["class Solution:\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n # l = []\n # maxH = 0\n # for i in range(len(height)-1, -1, -1):\n # if height[i] > maxH:\n # maxH = height[i]\n # ...
{"fn_name": "maxArea", "inputs": [[[1, 8, 6, 2, 5, 4, 8, 3, 7]]], "outputs": [49]}
INTERVIEW
PYTHON3
LEETCODE
10,644
class Solution: def maxArea(self, height: List[int]) -> int:
20e37183adb7190cc31fba7d3dc00f4d
UNKNOWN
Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.  For example, 2,3,5,7,11 and 13 are primes. Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.  For exam...
["import bisect\n\n\nclass Solution:\n def primePalindrome(self, N: int) -> int:\n return primes[bisect.bisect_left(primes, N)]\n\n\nprimes = [\n 2,\n 3,\n 5,\n 7,\n 11,\n 101,\n 131,\n 151,\n 181,\n 191,\n 313,\n 353,\n 373,\n 383,\n 727,\n 757,\n 787,\n ...
{"fn_name": "primePalindrome", "inputs": [[6]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
80,729
class Solution: def primePalindrome(self, N: int) -> int:
072fd9768aeff78575c787d58c908d81
UNKNOWN
In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of K-bit flips required so that there is no 0 in the array.  If it is not possible, return ...
["class Solution:\n def minKBitFlips(self, A: List[int], K: int) -> int:\n n = len(A)\n record = [0] * n\n flip = 0\n ans = 0\n for i in range(n):\n if i >= K: flip -= record[i-K]\n if A[i] == (flip % 2):\n if i > n - K: return -1\n ...
{"fn_name": "minKBitFlips", "inputs": [[[0, 1, 0], 1]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
76,315
class Solution: def minKBitFlips(self, A: List[int], K: int) -> int:
8786f8d028b1c566cbc901d2babf8615
UNKNOWN
Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.   Example 1: Input: S = "0110", N = 3 Output: true Example 2: Input: S = "0110", N = 4 Output: false   Note: 1 <...
["class Solution:\n def queryString(self, S: str, N: int) -> bool:\n for i in range(1,N+1):\n b = bin(i).replace('0b','')\n if b not in S:\n return False\n return True", "class Solution:\n def int_to_bin(self,x):\n ret=''\n if x==0:\n retu...
{"fn_name": "queryString", "inputs": [["\"0110\"", 3]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
7,591
class Solution: def queryString(self, S: str, N: int) -> bool:
30bcb3e8c9b42c1841a45ccc3ad07700
UNKNOWN
A string is called happy if it does not have any of the strings 'aaa', 'bbb' or 'ccc' as a substring. Given three integers a, b and c, return any string s, which satisfies following conditions: s is happy and longest possible. s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' ...
["class Solution:\n def longestDiverseString(self, a: int, b: int, c: int) -> str:\n if a == 0 and b == 0 and c == 0:\n return ''\n\n res = ''\n\n heap = [(-a, 'a'), (-b, 'b'), (-c, 'c')]\n heapq.heapify(heap)\n prev_val = 0\n prev_char = ''\n\n while heap:...
{"fn_name": "longestDiverseString", "inputs": [[1, 1, 7]], "outputs": ["ccaccbcc"]}
INTERVIEW
PYTHON3
LEETCODE
3,148
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str:
a86d467fdf93cc1717017465e9090233
UNKNOWN
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13....
["class Solution:\n def kthSmallest(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n arr = []\n for i in matrix:\n for j in i:\n arr.append(j)\n arr.sort()\n print(ar...
{"fn_name": "kthSmallest", "inputs": [[[[1, 5, 9], [10, 11, 13], [12, 13, 15], [], []], 8]], "outputs": [13]}
INTERVIEW
PYTHON3
LEETCODE
1,297
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
e7bbbd343fff952f53a00527393abb60
UNKNOWN
Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j].  The width of such a ramp is j - i. Find the maximum width of a ramp in A.  If one doesn't exist, return 0.   Example 1: Input: [6,0,8,2,1,5] Output: 4 Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 a...
["class Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n width = 0\n icandidate = [0]\n for i in range(len(A)):\n if A[i] < A[icandidate[-1]]:\n icandidate.append(i)\n for j in range(len(A) - 1, -1, -1):\n while icandidate and A[icandidate[-1...
{"fn_name": "maxWidthRamp", "inputs": [[[6, 0, 8, 2, 1, 5]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
33,339
class Solution: def maxWidthRamp(self, A: List[int]) -> int:
9bc814fce9631525e32617d2cf85d081
UNKNOWN
There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.  Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] = v opens ...
["class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n def dfs(node, visited):\n if node in visited:\n return\n visited.add(node)\n for nei in rooms[node]:\n if nei in visited:\n continue\n ...
{"fn_name": "canVisitAllRooms", "inputs": [[[[1], [2], [3], [], [], []]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
11,150
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
d44705abe2b454520f7be3c6e8046846
UNKNOWN
Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your...
["class Solution:\n def findSubstringInWraproundString(self, p):\n \"\"\"\n :type p: str\n :rtype: int\n \"\"\"\n pc = None\n sl = 0\n ll = {}\n \n for c in p:\n if pc and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):\n ...
{"fn_name": "findSubstringInWraproundString", "inputs": [["\"a\""]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
1,094
class Solution: def findSubstringInWraproundString(self, p: str) -> int:
5b1207c925726c15d0d1fd282d111e06
UNKNOWN
Given two integers A and B, return any string S such that: S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters; The substring 'aaa' does not occur in S; The substring 'bbb' does not occur in S.   Example 1: Input: A = 1, B = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all corr...
["class Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n if A >= 2*B:\n return 'aab'* B + 'a'* (A-2*B)\n elif A >= B:\n return 'aab' * (A-B) + 'ab' * (2*B - A)\n elif B >= 2*A:\n return 'bba' * A + 'b' *(B-2*A)\n else:\n return 'bb...
{"fn_name": "strWithout3a3b", "inputs": [[1, 2]], "outputs": ["bba"]}
INTERVIEW
PYTHON3
LEETCODE
1,185
class Solution: def strWithout3a3b(self, A: int, B: int) -> str:
d616cc040a8e44b4f92e7fe2e905e8db
UNKNOWN
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], ...
["class Solution:\n def findTargetSumWays(self, nums, S):\n \"\"\"\n :type nums: List[int]\n :type S: int\n :rtype: int\n \"\"\"\n c = [0]*1001\n c[0] = 1\n T = sum(nums)\n A = T+S\n if T<S or A&1:\n return 0\n A>>=1...
{"fn_name": "findTargetSumWays", "inputs": [[[1, 1, 1, 1, 1], 3]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
3,447
class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int:
f94bb70cc9cffffea340933371492570
UNKNOWN
Return the largest possible k such that there exists a_1, a_2, ..., a_k such that: Each a_i is a non-empty string; Their concatenation a_1 + a_2 + ... + a_k is equal to text; For all 1 <= i <= k,  a_i = a_{k+1 - i}.   Example 1: Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the ...
["class Solution:\n def longestDecomposition(self, text: str) -> int:\n n = len(text)\n splits = 0\n leftstart, leftend = 0, 0\n rightstart, rightend = n-1, n-1\n while leftend<rightstart:\n if text[leftstart:leftend+1] == text[rightstart:rightend+1]:\n le...
{"fn_name": "longestDecomposition", "inputs": [["\"ghiabcdefhelloadamhelloabcdefghi\""]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
7,809
class Solution: def longestDecomposition(self, text: str) -> int:
58cadd63532d06a57a78fc5a025646f1
UNKNOWN
We have a collection of rocks, each rock has a positive integer weight. Each turn, we choose any two rocks and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is: If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, an...
["class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n dp = {0}\n total = sum(stones)\n for stone in stones:\n dp |= {_sum + stone for _sum in dp}\n return min(abs(total - _sum - _sum) for _sum in dp)", "class Solution:\n def lastStoneWeightII(self, sto...
{"fn_name": "lastStoneWeightII", "inputs": [[[2, 7, 4, 1, 8, 1]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
13,673
class Solution: def lastStoneWeightII(self, stones: List[int]) -> int:
b694f183589a74387afcfac699caef21
UNKNOWN
Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1. Return the least number of moves to make every value in A unique.   Example 1: Input: [1,2,2] Output: 1 Explanation: After 1 move, the array could be [1, 2, 3]. Example 2: Input: [3,2,1,2,1,7] Output: 6 Explanation: After ...
["class Solution:\n def minIncrementForUnique(self, A: List[int]) -> int:\n if not A:\n return 0\n \n A.sort()\n prev = A[0]\n res = 0\n for num in A[1:]:\n if num <= prev:\n prev += 1\n res += prev-num\n\n else:...
{"fn_name": "minIncrementForUnique", "inputs": [[[1, 2, 2]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
56,139
class Solution: def minIncrementForUnique(self, A: List[int]) -> int:
d51268de15b01d89768f95e76eb3c0ba
UNKNOWN
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime , endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range. If you choose a jo...
["class Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n \n # max profit ending at time t\n dp = [(0,0)]\n \n task = [(startTime[i], endTime[i], profit[i]) for i in range(len(startTime))]\n task = sorted(task, key = l...
{"fn_name": "jobScheduling", "inputs": [[[1, 2, 3, 3], [3, 4, 5, 6], [50, 10, 40, 70]]], "outputs": [120]}
INTERVIEW
PYTHON3
LEETCODE
136,244
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
7fc874ae8261f28686d8939ba6ad34f2
UNKNOWN
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contac...
["class Solution:\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n return max(self.helper(nums[1:]), self.helper(nums[:-1]))\n \n ...
{"fn_name": "rob", "inputs": [[[2, 3, 2]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
9,884
class Solution: def rob(self, nums: List[int]) -> int:
4edc8f2b3870adae113f759de8ad97b8
UNKNOWN
Given an array of positive integers target and an array initial of same size with all zeros. Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation: Choose any subarray from initial and increment each value by one. The answer is guaranteed to fit w...
["class Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n prev = -1\n ans = 0\n for num in target:\n if prev == -1:\n prev = num\n ans += num\n continue\n if num > prev:\n ans += (num - prev)\n...
{"fn_name": "minNumberOperations", "inputs": [[[1, 2, 3, 2, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
29,362
class Solution: def minNumberOperations(self, target: List[int]) -> int:
e7a2f474c6461ecc9e80da03c155ffb5
UNKNOWN
Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7 Example 2: Input: " 3/2 " Output: 1 Example 3: Input: ...
["class Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n \n if not s:\n return 0\n \n pre_op = '+'\n stack = [0]\n cur_num = 0\n digits = '0123456789'\n s += '#'\n ...
{"fn_name": "calculate", "inputs": [["\"3+2*2\""]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
4,291
class Solution: def calculate(self, s: str) -> int:
87f022c16b58f70a1058e02a7c370507
UNKNOWN
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. Example 1: Input: "aacecaaa" Output: "aaacecaaa" Example 2: Input: "abcd" Output: "dcbabcd"
["class Solution:\n def shortestPalindrome(self, s):\n if len(s)<2:\n return s\n if len(s)==40002:\n return s[20000:][::-1]+s\n for i in range(len(s)-1,-1,-1):\n if s[i]==s[0]:\n j=0\n while j<(i+1)//2 and s[i-j]==s[j]:\n ...
{"fn_name": "shortestPalindrome", "inputs": [["\"aacecaaa\""]], "outputs": ["\"aaacecaa\"aacecaaa\""]}
INTERVIEW
PYTHON3
LEETCODE
6,233
class Solution: def shortestPalindrome(self, s: str) -> str:
3f3f38da6d916627c8af94badab19ced
UNKNOWN
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1. Some nodes initial are initially infected by malware.  Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware.  This spread of ...
["class Solution(object):\n def minMalwareSpread(self, graph, initial):\n # 1. Color each component.\n # colors[node] = the color of this node.\n\n N = len(graph)\n colors = {}\n c = 0\n\n def dfs(node, color):\n colors[node] = color\n for nei, adj in e...
{"fn_name": "minMalwareSpread", "inputs": [[[[1, 1, 0], [1, 1, 0], [0, 0, 1], [], []], [0, 1]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
65,765
class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
d54cafe9459ba56a1749d31ed6a4a7f0
UNKNOWN
Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have t...
["class Solution:\n def arrangeWords(self, text: str) -> str:\n p=text.split(' ')\n final=''\n j=sorted(p,key=len)\n temp=' '.join(j)\n if temp[0]>='a' and temp[0]<='z':\n s=temp[0].swapcase()\n final=final+s[0]\n else:\n final=final+temp[0]\...
{"fn_name": "arrangeWords", "inputs": [["\"Leetcode is cool\""]], "outputs": ["Is cool\" \"leetcode"]}
INTERVIEW
PYTHON3
LEETCODE
4,691
class Solution: def arrangeWords(self, text: str) -> str:
261ba42a1ecbf597c9623237f7585fdb
UNKNOWN
You are given a string s that consists of lower case English letters and brackets.  Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets.   Example 1: Input: s = "(abcd)" Output: "dcba" Example 2: Input: s = "(u(love)i)" Output: "iloveu"...
["class Solution:\n def reverseParentheses(self, s: str) -> str:\n \n \n stack = []\n curr = ''\n for c in s:\n if c=='(':\n stack.append(curr)\n curr = ''\n stack.append('(')\n elif c==')':\n stack.a...
{"fn_name": "reverseParentheses", "inputs": [["\"(abcd)\""]], "outputs": ["\"dcba\""]}
INTERVIEW
PYTHON3
LEETCODE
4,107
class Solution: def reverseParentheses(self, s: str) -> str:
0b381fb6e347f60d6215b93ae824687f
UNKNOWN
Given a string s of '(' , ')' and lowercase English characters.  Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, conta...
["class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n if not s: return s\n l=0\n r=0\n res=''\n for i,c in enumerate(s):\n if c=='(':\n l+=1\n if c==')':\n if l==r:\n continue\n els...
{"fn_name": "minRemoveToMakeValid", "inputs": [["\"lee(t(c)o)de)\""]], "outputs": ["\"lee(t(c)o)de\""]}
INTERVIEW
PYTHON3
LEETCODE
51,157
class Solution: def minRemoveToMakeValid(self, s: str) -> str:
758790410cb5ef1f87ef17e74474875f
UNKNOWN
Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interpre...
["class Solution:\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n base = \"0123456789\"\n plus = \"+\"\n minus = \"-\"\n sum = 0\n flag = 1\n bit = 0\n INT_MAX = 2147483647\n INT_MIN = -214748...
{"fn_name": "myAtoi", "inputs": [["\"42\""]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
9,147
class Solution: def myAtoi(self, s: str) -> int:
9e0a0d0e913cc8f2b60f4904265e2888
UNKNOWN
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: [3,3,7,7,10,11,11] Output: 10 Note: Your solution should run in O(lo...
["class Solution:\n def singleNonDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return self.singleNonDuplicateUtil(nums, 0, len(nums)-1)\n \n def singleNonDuplicateUtil(self, nums, l, r):\n if l < r:\n mid = in...
{"fn_name": "singleNonDuplicate", "inputs": [[[1, 1, 2, 3, 3, 4, 4, 8, 8]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
6,271
class Solution: def singleNonDuplicate(self, nums: List[int]) -> int:
214844d6037de4ce7db1e56916209328
UNKNOWN
There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at...
["from heapq import heapify, heappush, heappop\nimport sys\ninput = sys.stdin.readline\n\ndef solve():\n N, Q = list(map(int, input().split()))\n events = []\n for i in range(N):\n S, T, X = list(map(int, input().split()))\n events.append((S-X-0.5, 1, X))\n events.append((T-X-0.5, 0, X))\n...
{"inputs": ["4 6\n1 3 2\n7 13 10\n18 20 13\n3 4 2\n0\n1\n2\n3\n5\n8\n"], "outputs": ["2\n2\n10\n-1\n13\n-1\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
80,553
ccdbd649895ddf6a02614d3c0cb62c13
UNKNOWN
Given is an undirected connected graph with N vertices numbered 1 to N, and M edges numbered 1 to M. The given graph may contain multi-edges but not self loops. Each edge has an integer label between 1 and N (inclusive). Edge i has a label c_i, and it connects Vertex u_i and v_i bidirectionally. Snuke will write an int...
["import sys\nsys.setrecursionlimit(10**6)\n\nclass UnionFind():\n def __init__(self, n):\n self.n = n\n self.parents = [-1] * n\n\n def find(self, x):\n if self.parents[x] < 0:\n return x\n else:\n self.parents[x] = self.find(self.parents[x])\n return ...
{"inputs": ["3 4\n1 2 1\n2 3 2\n3 1 3\n1 3 1\n"], "outputs": ["1\n2\n1\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
84,840
e7c1fefb284de37a4b501b737e2abeac
UNKNOWN
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: - Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) - Type 2: answer the number of different characters occurring in the substring of S betwee...
["n = int(input())\ns = list(input())\ns = [ord(i)-97 for i in s]\n\ndic = {}\nfor i in range(26):\n dic[i] = []\n\nfor i in range(n):\n dic[s[i]].append(i)\n\nfor i in range(26):\n dic[i].append(float('inf'))\n\nfrom bisect import bisect_left\nq = int(input())\nfor i in range(q):\n x, y, z = input().split(...
{"inputs": ["7\nabcdbbd\n6\n2 3 6\n1 5 z\n2 1 1\n1 4 a\n1 7 d\n2 1 7\n"], "outputs": ["3\n1\n5\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
116,712
264298e52e82134053b9348bdbe50393
UNKNOWN
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even. Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written. Recently, they learned the operation called xor (exclusive OR).What is xor? For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\text...
["n=int(input())\na=list(map(int,input().split()))\n\nX=[]\nb=a[0]\nfor i in range(1,n) :\n b^=a[i]\n\nfor i in range(n) :\n x=b^a[i]\n X.append(x)\n\nfor i in X :\n print(i,end=\" \")\n", "def main():\n N = int(input())\n A = list(map(int, input().split()))\n\n scarf_0 = 0\n for a in A[1:]:\n ...
{"inputs": ["4\n20 11 9 24\n"], "outputs": ["26 5 7 22\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
22,887
6fd13332a1440f9f4ba91340a5ac5b8e
UNKNOWN
There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and...
["import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**5)\n\nN, Q = map(int, input().split())\n\npath = [[] for _ in range(N)]\n\nfor _ in range(N-1) :\n a, b, c, d = (int(i) for i in input().split())\n path[a-1].append((b-1, c-1, d))\n path[b-1].append((a-1, c-1, d))\n\n# doubling\u306b\u5fc5\u89...
{"inputs": ["5 3\n1 2 1 10\n1 3 2 20\n2 4 4 30\n5 2 1 40\n1 100 1 4\n1 100 1 5\n3 1000 3 4\n"], "outputs": ["130\n200\n60\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
108,703
abffda2a57466ff5835452f3ccefb22f
UNKNOWN
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem: - We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k...
["import bisect\nimport sys\nsys.setrecursionlimit(10**7)\n\ndef dfs(v):\n pos=bisect.bisect_left(dp,arr[v])\n changes.append((pos,dp[pos]))\n dp[pos]=arr[v]\n ans[v]=bisect.bisect_left(dp,10**18)\n for u in g[v]:\n if checked[u]==0:\n checked[u]=1\n dfs(u)\n pos,val=chang...
{"inputs": ["10\n1 2 5 3 4 6 7 3 2 4\n1 2\n2 3\n3 4\n4 5\n3 6\n6 7\n1 8\n8 9\n9 10\n"], "outputs": ["1\n2\n3\n3\n4\n4\n5\n2\n2\n3\n"]}
INTERVIEW
PYTHON3
ATCODER.JP
90,384
ecd41b0acc331599472d45375705b63e
UNKNOWN
Write a program to take two numbers as input and print their difference if the first number is greater than the second number otherwise$otherwise$ print their sum. -----Input:----- - First line will contain the first number (N1$N1$) - Second line will contain the second number (N2$N2$) -----Output:----- Output a sing...
["m = int(input())\nn = int(input())\nprint(m-n) if m>n else print(m+n)", "# cook your dish here\na = int(input())\nb = int(input())\nif a>b:\n print(a-b)\nelse:\n print(a+b)", "n1=int(input())\nn2=int(input())\nprint(n1-n2) if(n1>n2) else print(n1+n2)\n", "n1=int(input())\nn2=int(input())\nif(n1>n2):\n print(...
{"inputs": [["82", "28"]], "outputs": [["54"]]}
INTERVIEW
PYTHON3
CODECHEF
2,756
0129ae0012e2eaa8608485ae6c3584f4
UNKNOWN
Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is explor...
["# cook your dish here\ndef modular_pow(base, exponent, modulus):\n result = 1\n while exponent > 0:\n if(exponent %2 == 1):\n result = (result * base) % modulus\n exponent = exponent//2\n base = (base * base)%modulus\n return result\ndef passesMillerRabinTest(n, a):\n s = 0\n d = n-1\n while(d%2 == 0):\n s += 1...
{"inputs": [["3", "2", "3", "4"]], "outputs": [["2", "3", "3"]]}
INTERVIEW
PYTHON3
CODECHEF
934