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
190e965ba93c2df65c99cc1a5c99aa28
UNKNOWN
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev",...
["class Solution:\n def longestPrefix(self, strn: str) -> str:\n max_prefs = [0]*len(strn)\n\n curr = 0\n for idx in range(1, len(strn)):\n while True:\n if curr == 0:\n if strn[idx] == strn[0]:\n curr = 1\n m...
{"fn_name": "longestPrefix", "inputs": [["\"level\""]], "outputs": ["\""]}
INTERVIEW
PYTHON3
LEETCODE
42,292
class Solution: def longestPrefix(self, s: str) -> str:
36c88c0daf5a92e9bcb8de841112aa79
UNKNOWN
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How...
["class Solution:\n def numPermsDISequence(self, S):\n dp = [1] * (len(S) + 1)\n for a, b in zip('I' + S, S):\n dp = list(itertools.accumulate(dp[:-1] if a == b else dp[-1:0:-1]))\n return dp[0] % (10**9 + 7)\n", "class Solution:\n def numPermsDISequence(self, S: str) -> int:\n ...
{"fn_name": "numPermsDISequence", "inputs": [["\"DID\""]], "outputs": [61]}
INTERVIEW
PYTHON3
LEETCODE
19,114
class Solution: def numPermsDISequence(self, S: str) -> int:
13ac42989838437419e7414f0a5a4753
UNKNOWN
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are n...
["class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n a,b,n=[slices[0]],[0],len(slices)\n for i in range(1,n):\n a.append(max(a[-1],slices[i]))\n b.append(max(b[-1],slices[i]))\n for i in range(2,2*n//3,2):\n aa,bb=[0]*(n-1),[0]*n\n ...
{"fn_name": "maxSizeSlices", "inputs": [[[1, 2, 3, 4, 5, 6]]], "outputs": [10]}
INTERVIEW
PYTHON3
LEETCODE
42,850
class Solution: def maxSizeSlices(self, slices: List[int]) -> int:
8c2263df9511ae37f76c7db240cfec9a
UNKNOWN
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first ...
["class Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n A = stoneValue\n dp = [0] * 3\n for i in range(len(A) - 1, -1, -1):\n dp[i % 3] = max(sum(A[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3))\n \n if dp[0] > 0:\n return 'Alice'\n ...
{"fn_name": "stoneGameIII", "inputs": [[[1, 2, 3, 7]]], "outputs": ["Bob"]}
INTERVIEW
PYTHON3
LEETCODE
162,301
class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str:
e847c035323006b708dcfed4416c1420
UNKNOWN
Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums. Return the minimum number of function calls to make nums from arr. The answer is guaranteed to fit in a 32-bit signed integer.   Example 1: Input: nums = [1,5] Output: 5 Explanation: Increment by 1 (second eleme...
["class Solution:\n def minOperations(self, nums: List[int]) -> int:\n return sum(bin(x).count('1') for x in nums)+len(bin(max(nums)))-3\n", "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n add_count = sum(bin(v).count('1') for v in nums)\n mul_count = len(bin(max(nums)))...
{"fn_name": "minOperations", "inputs": [[[1, 5]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
313,591
class Solution: def minOperations(self, nums: List[int]) -> int:
f3fc46c4b2c200a3f3e9e8cd53e35655
UNKNOWN
Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa (in other words s2 can break s1). A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.   Example 1: Input: s1 = "ab...
["from collections import Counter\nclass Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n d1, d2 = Counter(s1), Counter(s2)\n return self.check(d1, d2) or self.check(d2, d1)\n \n def check(self, d1: dict, d2: dict) -> bool:\n s = 0\n for c in 'abcdefghijklmnopq...
{"fn_name": "checkIfCanBreak", "inputs": [["\"abc\"", "\"xya\""]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
23,362
class Solution: def checkIfCanBreak(self, s1: str, s2: str) -> bool:
47c89e2d828385e232244dd7c04666f6
UNKNOWN
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. Example 1: Input: nums = [1,3], n = 6 Output: 1 Explanation: Combinations...
["class Solution:\n def minPatches(self, nums, n):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :rtype: int\n \"\"\"\n res, cur, i = 0, 1, 0\n while cur <= n:\n if i < len(nums) and nums[i] <= cur:\n cur += nums[i]\n ...
{"fn_name": "minPatches", "inputs": [[[1, 3], 6]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
3,134
class Solution: def minPatches(self, nums: List[int], n: int) -> int:
c52545819825b90f69c84272ca4c5c5e
UNKNOWN
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Example 1: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
["class Solution:\n def isInterleave(self, s1, s2, s3):\n \"\"\"\n :type s1: str\n :type s2: str\n :type s3: str\n :rtype: bool\n \"\"\"\n if len(s3) != len(s1) + len(s2):\n return False\n if not s1 or not s2:\n return (s1 or s2...
{"fn_name": "isInterleave", "inputs": [["\"aabcc\"", "\"dbbca\"", "\"aadbbcbcac\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
22,257
class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
4d74f6a836023060e39ee876cfefd81e
UNKNOWN
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1. Example 1: Input: 12 Output: 21   Example 2: Input: 21 Output: -1
["class Solution:\n def nextGreaterElement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n s=[i for i in str(n)]\n exist=-1\n for i in range(len(s)-1,0,-1):\n if s[i-1]<s[i]:\n temp=sorted(s[i-1:])\n pivot...
{"fn_name": "nextGreaterElement", "inputs": [[12]], "outputs": [21]}
INTERVIEW
PYTHON3
LEETCODE
7,710
class Solution: def nextGreaterElement(self, n: int) -> int:
35db219a0d891efa24d8f30325f6d533
UNKNOWN
Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance. The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is...
["class Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n \n from collections import deque\n \n queue = deque()\n for i, row in enumerate(grid):\n for j, cell in enumerate(row):\n if cell == 1:\n queue.append((i, j, None...
{"fn_name": "maxDistance", "inputs": [[[[1, 0, 1], [0, 0, 0], [1, 0, 1], [], []]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
3,303
class Solution: def maxDistance(self, grid: List[List[int]]) -> int:
65e882a19a1e79aeda8ac74edae3b845
UNKNOWN
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conver...
["class Solution(object):\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if numRows == 1:\n return s\n zigzag = ['' for i in range(numRows)] \n row = 0 \...
{"fn_name": "convert", "inputs": [["\"PAYPALISHIRING\"", 3]], "outputs": ["\"PSIPYAIHRN\"ALIG"]}
INTERVIEW
PYTHON3
LEETCODE
4,448
class Solution: def convert(self, s: str, numRows: int) -> str:
c888322ecc7840fb958e61fdee0a8ce4
UNKNOWN
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, ...
["class Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n L, res, last = -1, 0, {}\n for R, char in enumerate(s):\n if char in last and last[char] > L:\n L = last[char]\n elif R-...
{"fn_name": "lengthOfLongestSubstring", "inputs": [["\"abcabcbb\""]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
5,139
class Solution: def lengthOfLongestSubstring(self, s: str) -> int:
d7ff823b7231c6e9468ec9c814b00a81
UNKNOWN
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list. Note: n will be less than 15,000. Example 1: Input: [1, 2, 3, 4] Output: ...
["class Solution:\n def find132pattern(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \n if len(nums) < 3:\n return False\n \n stack = [[nums[0], nums[0]]]\n minimum = nums[0]\n for num in nums[1:]:\n if num <= m...
{"fn_name": "find132pattern", "inputs": [[[1, 2, 3, 4]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
8,904
class Solution: def find132pattern(self, nums: List[int]) -> bool:
de6b7fb0997271a74a93410f2c6469a2
UNKNOWN
You are given a rows x cols matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (rows - 1, cols - 1), find the path with the maximum...
["class Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n if (rows == 0):\n return -1\n \n cols = len(grid[0])\n if (cols == 0):\n return -1\n \n dp = [(1,1)] * cols\n for r, col in enumerate(grid):\n...
{"fn_name": "maxProductPath", "inputs": [[[[-1, -2, -3], [-2, -3, -3], [-3, -3, -2], [], []]]], "outputs": [-1]}
INTERVIEW
PYTHON3
LEETCODE
2,499
class Solution: def maxProductPath(self, grid: List[List[int]]) -> int:
3cacd07ae5c6260191c7846cba51e986
UNKNOWN
Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. Update (2015-02-10): The signature of the C++ function ha...
["class Solution:\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n dot = False\n exp = False\n \n try:\n while s.startswith(' '):\n s = s[1:]\n while s.endswith(' '):\n s...
{"fn_name": "isNumber", "inputs": [["\"0\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
7,141
class Solution: def isNumber(self, s: str) -> bool:
155091cc668b699b3a7d1791440c905b
UNKNOWN
Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.   Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5 Example 4: Input: hour = 4, minut...
["class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n hour_angle = hour*30+(minutes/12)*6\n if hour_angle > 360:\n hour_angle -= 360\n min_angle = (minutes/5)*30\n if min_angle > 360:\n min_angle -= 360\n \n diff = abs(hour_a...
{"fn_name": "angleClock", "inputs": [[12, 30]], "outputs": [165.0]}
INTERVIEW
PYTHON3
LEETCODE
2,804
class Solution: def angleClock(self, hour: int, minutes: int) -> float:
02bccf8997db89800adc33c3ffb25254
UNKNOWN
Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Ex...
["class Solution:\n def countSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ret = 0\n left, right = 0, 0\n while left < len(s):\n while right < len(s) and s[right] == s[left]:\n right += 1\n ret +=...
{"fn_name": "countSubstrings", "inputs": [["\"abc\""]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
5,944
class Solution: def countSubstrings(self, s: str) -> int:
0d42a04ec24b129ea60faa310012347b
UNKNOWN
Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice ...
["from collections import deque\n\nclass Solution:\n def minJumps(self, arr: list) -> int:\n if len(arr) == 1:\n return 0\n graph = {}\n for i, n in enumerate(arr):\n if n in graph:\n graph[n].append(i)\n else:\n graph[n] = [i]\n ...
{"fn_name": "minJumps", "inputs": [[[100, -23, -23, 404, 100, 23, 23, 23, 3, 404]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
197,177
class Solution: def minJumps(self, arr: List[int]) -> int:
c199b776e15a187e8a52263a2c058a67
UNKNOWN
Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s. Return the minimum cost of deletions such that there are no two identical letters next to each other. Notice that you will delete the chosen characters at the same time, in other words, after deleting a characte...
["class Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n delete_cost = 0\n last = 0\n for i in range(1, len(s)):\n if s[last] == s[i]:\n if cost[last] < cost[i]:\n delete_cost += cost[last]\n last = i\n ...
{"fn_name": "minCost", "inputs": [["\"abaac\"", [1, 2, 3, 4, 5]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
92,865
class Solution: def minCost(self, s: str, cost: List[int]) -> int:
e8ba3b433704c53bed771acb4285e9dc
UNKNOWN
You are installing a billboard and want it to have the largest height.  The billboard will have two steel supports, one on each side.  Each steel support must be an equal height. You have a collection of rods which can be welded together.  For example, if you have rods of lengths 1, 2, and 3, you can weld them together...
["from functools import lru_cache\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n rods = sorted(rods)[::-1]\n n = len(rods)\n psum = rods.copy()\n for i in range(n-1)[::-1]:\n psum[i] += psum[i+1]\n\n @lru_cache(None)\n def dfs(idx, diff):...
{"fn_name": "tallestBillboard", "inputs": [[[1, 2, 3, 6]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
50,367
class Solution: def tallestBillboard(self, rods: List[int]) -> int:
1d1c0393aeffcca98e8fe16a68657ba6
UNKNOWN
Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.   Example 1: Input: s = "...
["class Solution:\n def minSteps(self, s: str, t: str) -> int:\n\n \n s_count=[s.count(chr(i)) for i in range(97,123)]\n t_count=[t.count(chr(i)) for i in range(97,123)]\n diff=[t_count[i]-s_count[i] for i in range(26) if t_count[i]-s_count[i]>0]\n sum=0\n for i in range(len...
{"fn_name": "minSteps", "inputs": [["\"bab\"", "\"aba\""]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
43,935
class Solution: def minSteps(self, s: str, t: str) -> int:
179db972fc815992fa9570bbde07915a
UNKNOWN
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas statio...
["class Solution:\n def canCompleteCircuit(self, gas, cost):\n \"\"\"\n :type gas: List[int]\n :type cost: List[int]\n :rtype: int\n \"\"\"\n if sum(gas) < sum(cost):\n return -1\n Rest = 0\n index = 0\n for i in range(len(gas)):\n ...
{"fn_name": "canCompleteCircuit", "inputs": [[[1, 2, 3, 4, 5], [3, 4, 5, 1, 2]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
9,781
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
b79fed204f74e91b4114b858757dbe44
UNKNOWN
Given the strings s1 and s2 of size n, and the string evil. Return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, retu...
["from functools import lru_cache\n\ndef failure(pat):\n i, target, n = 1, 0, len(pat)\n res = [0]\n while i < n:\n if pat[i] == pat[target]:\n target += 1\n res.append(target)\n i+=1\n elif target:\n target = res[target-1]\n else:\n r...
{"fn_name": "findGoodStrings", "inputs": [[2, "\"aa\"", "\"da\"", "\"b\""]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
26,047
class Solution: def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
c4cf10d5ba1a664011f99b3801d923e6
UNKNOWN
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules: Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length. Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where ...
["class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n \n def triplets(nums1, nums2):\n sq = collections.Counter(x * x for x in nums1)\n num = collections.Counter(nums2)\n \n res = 0\n keys = sorted(num.keys())\n ...
{"fn_name": "numTriplets", "inputs": [[[7, 4], [5, 2, 8, 9]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
356,379
class Solution: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
d0b121624d7b69b2659d72f37896d707
UNKNOWN
Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashe...
["class Solution:\n def simplifyPath(self, path):\n \"\"\"\n :type path: str\n :rtype: str\n \"\"\"\n stack=[]\n path=[p for p in path.split('/') if p]\n for f in path:\n if f == '.': continue\n elif f == '..': \n if sta...
{"fn_name": "simplifyPath", "inputs": [["\"/home/\""]], "outputs": ["/\"/home/\""]}
INTERVIEW
PYTHON3
LEETCODE
7,661
class Solution: def simplifyPath(self, path: str) -> str:
6039c8e1f57b312455dbc4e18639c3c9
UNKNOWN
Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.  Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note:   1 is typically treated as an ugly number. n ...
["class Solution:\n res=[1]\n idx=[0,0,0]\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n<=0:\n return None\n idx2,idx3,idx5=Solution.idx\n while len(Solution.res)<n:\n Solution.res.append(min...
{"fn_name": "nthUglyNumber", "inputs": [[10]], "outputs": [12]}
INTERVIEW
PYTHON3
LEETCODE
1,808
class Solution: def nthUglyNumber(self, n: int) -> int:
92427394fd480bd8e74404ff5d914a1a
UNKNOWN
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid board, made of only battleships or empty slots. Battleships can only be placed horizontally or vertically. In other words, ...
["class Solution:\n def countBattleships(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n count = 0\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] == 'X':\n ...
{"fn_name": "countBattleships", "inputs": [[[["\"X\"", "\".\"", "\".\"", "\"X\""], ["\".\"", "\".\"", "\".\"", "\"X\""], ["\".\"", "\".\"", "\".\"", "\"X\""], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
2,608
class Solution: def countBattleships(self, board: List[List[str]]) -> int:
e134a352ddb651bf35cbd5ed386663dc
UNKNOWN
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
["class Solution:\n def numSquares(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n while(n%4 == 0):\n n = n/4\n if n%8 == 7: return 4;\n a = int(0)\n while(a*a <= n):\n b = int(math.sqrt(n-a*a))\n if (a*a+...
{"fn_name": "numSquares", "inputs": [[12]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
33,593
class Solution: def numSquares(self, n: int) -> int:
179f1a9abf3e99e9b95da86cb2f667a6
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 = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions i...
["class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n dp = [(1, 1)] * len(A[0])\n for i in range(len(dp)):\n if i > 0:\n max_pre = None\n for pre in range(i - 1, -1, -1):\n for word in A:\n if word[pre] >...
{"fn_name": "minDeletionSize", "inputs": [[["\"babca\"", "\"bbazb\""]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
19,617
class Solution: def minDeletionSize(self, A: List[str]) -> int:
00cf0044897b668814ecc2f489a9910d
UNKNOWN
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. Note: If n is the length of array, assume the following constraints are satisfied: 1 ≤ n ≤ 1000 1 ≤ m ≤ min(5...
["class Solution:\n def splitArray(self, nums, m):\n \"\"\"\n :type nums: List[int]\n :type m: int\n :rtype: int\n \"\"\"\n accum = [0]\n N = len(nums)\n mmm = max(nums)\n if m >= N:\n return mmm\n res = 0\n for i in...
{"fn_name": "splitArray", "inputs": [[[7, 2, 5, 10, 8], 2]], "outputs": [18]}
INTERVIEW
PYTHON3
LEETCODE
9,547
class Solution: def splitArray(self, nums: List[int], m: int) -> int:
3d7e66e9da0ff1386f407aa33150b280
UNKNOWN
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays.   Example 1: Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. Example 2: Input: nums ...
["class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n # save all even subarray's length which between odds\n edge = []\n res = 0\n count = 0\n for i in nums:\n # odd\n if i % 2:\n # +1 because range from 0 to count w...
{"fn_name": "numberOfSubarrays", "inputs": [[[1, 1, 2, 1, 1], 3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
91,932
class Solution: def numberOfSubarrays(self, nums: List[int], k: int) -> int:
d63f3368d46d4dea50fa9e22e79b85dc
UNKNOWN
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Example 1: Input:s1 = "ab" s2 = "eidbaooo" Output:True Explanation: s2 contains one permutation of s1 ("ba"). Example 2: ...
["class Solution:\n def checkInclusion(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n if len(s2) < len(s1):\n return False\n c1 = [0] * 128\n n = 0\n for i in s1:\n c = ord(i)\n ...
{"fn_name": "checkInclusion", "inputs": [["\"ab\"", "\"eidbaooo\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
3,228
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool:
e97a3dd0c18a348c36382902e2c8697e
UNKNOWN
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum p...
["import sys\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n ignore=0\n not_ignore=0\n res=-sys.maxsize\n for i in arr:\n if i>=0:\n ignore+=i\n not_ignore+=i\n else:\n if ignore==0:\n ...
{"fn_name": "maximumSum", "inputs": [[[1, -2, 0, 3]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
33,485
class Solution: def maximumSum(self, arr: List[int]) -> int:
9ed5f2ae4c9376719704de7cd1a3d712
UNKNOWN
Given an array nums of integers, you can perform operations on the array. In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. You start with 0 points. Return the maximum number of points you can earn by applying such...
["class Solution:\n def deleteAndEarn(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(nums);#count is a dict [3,4,2]--> {2:1,3:1,4:1}\n prev = None;\n avoid = using = 0;\n for k in sorted(count):\n ...
{"fn_name": "deleteAndEarn", "inputs": [[[2, 3, 4]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
5,323
class Solution: def deleteAndEarn(self, nums: List[int]) -> int:
731c06090c95ce04ef234f40c512a043
UNKNOWN
Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K. (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.) Return the number of good subarrays of A.   Example 1: Input: A = [1,2,1,2,3], K = ...
["from collections import defaultdict\nclass Solution:\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n \n start_k = 0\n start = 0\n elem_dict = defaultdict(int)\n \n ans = 0\n \n for elem in A:\n elem_dict[elem] += 1\n \...
{"fn_name": "subarraysWithKDistinct", "inputs": [[[1, 2, 1, 2, 3], 2]], "outputs": [7]}
INTERVIEW
PYTHON3
LEETCODE
115,521
class Solution: def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
d9ab9525f2cf0600a9b282e21aadb99a
UNKNOWN
On a broken calculator that has a number showing on its display, we can perform two operations: Double: Multiply the number on the display by 2, or; Decrement: Subtract 1 from the number on the display. Initially, the calculator is displaying the number X. Return the minimum number of operations needed to display the...
["class Solution:\n def brokenCalc(self, X: int, Y: int) -> int:\n res = 0\n while X < Y:\n res += Y % 2 + 1\n Y = int((Y + 1) / 2)\n return res + X - Y\n", "class Solution:\n def brokenCalc(self, X: int, Y: int) -> int:\n result = 0\n while Y > X:\n ...
{"fn_name": "brokenCalc", "inputs": [[2, 3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
2,555
class Solution: def brokenCalc(self, X: int, Y: int) -> int:
b715ebdc66baa92bc9aa2a1ea2dd4170
UNKNOWN
Given a list of words, each word consists of English lowercase letters. Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac". A word chain is a sequence of words [word_1, word_2, ..., word_k] wi...
["class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n by_length = collections.defaultdict(set)\n for word in words:\n by_length[len(word)].add(word)\n\n longest = 1\n seen = {*()}\n mx = len(by_length)\n mn = min(by_length)\n\n for lengt...
{"fn_name": "longestStrChain", "inputs": [[["\"a\"", "\"b\"", "\"ba\"", "\"bca\"", "\"bda\"", "\"bdca\""]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
370,439
class Solution: def longestStrChain(self, words: List[str]) -> int:
f18436bdf5f01d4ff21635f53e976379
UNKNOWN
Given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal than target. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [3,5,6,7], target = 9 Output: 4 Exp...
["class Solution:\n MODS = 10 ** 9 + 7\n def numSubseq(self, nums: List[int], target: int) -> int:\n N = len(nums)\n cal_map = [1]\n for ii in range(1, N):\n cal_map.append(cal_map[-1] * 2 % self.MODS)\n left, right, res = 0, N - 1, 0\n nums.sort()\n while left...
{"fn_name": "numSubseq", "inputs": [[[3, 5, 6, 7], 9]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
177,418
class Solution: def numSubseq(self, nums: List[int], target: int) -> int:
db0ceddc6fd9e9a614af7ec12533c466
UNKNOWN
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.  Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained w...
["class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n a,b,m=[deque([0]*x) for x in rollMax],[1]*6,1000000007\n for x in a: x[-1]=1\n for _ in range(n-1):\n s=sum(b)%m\n for i,x in enumerate(a):\n x.append((s-b[i])%m)\n ...
{"fn_name": "dieSimulator", "inputs": [[2, [1, 1, 2, 2, 2, 3]]], "outputs": [34]}
INTERVIEW
PYTHON3
LEETCODE
268,726
class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int:
21892aaf24647b15272b01130ad54025
UNKNOWN
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. Note: 1 ≤ k ≤ n ≤ 109. Example: Input: n: 13 k: 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
["class Solution(object):\n def findKthNumber(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n s,nn=0,str(n)\n while nn:\n if not k: return s\n c,m=0,10**(len(nn)-1)\n mm,p,t=(m-1)//9,int(nn)//m,0...
{"fn_name": "findKthNumber", "inputs": [[13, 2]], "outputs": [10]}
INTERVIEW
PYTHON3
LEETCODE
3,431
class Solution: def findKthNumber(self, n: int, k: int) -> int:
d2fd669d21169e8f725ca13a9695b9c2
UNKNOWN
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7]...
["class Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or target is None:\n return False\n \n rows, cols = len(matrix), len(matrix[0])\n ...
{"fn_name": "searchMatrix", "inputs": [[[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50], [], []], 3]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
8,730
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
a01f5bd148ecd3cec65778341f58f9af
UNKNOWN
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and t...
["class Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n ans = 0 \n for seat, group in itertools.groupby(seats):\n if not seat:\n k = len(list(group))\n ans = max(ans, (k+1)//2)\n return max(ans, seats.index(1),seats[::-1].index(1))\n ...
{"fn_name": "maxDistToClosest", "inputs": [[[1, 0, 0, 0, 1, 0, 1]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
28,910
class Solution: def maxDistToClosest(self, seats: List[int]) -> int:
eababd35735f69a88514fcb5177e857f
UNKNOWN
To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size). Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y.  The rule is that if x starts at position i in the original string S, then we ...
["class Solution:\n def findReplaceString(self, s: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:\n l = []\n for i, tgt, rpl in zip(indexes, sources, targets):\n if s[i:i + len(tgt)] == tgt:\n l.append((i, tgt, rpl))\n l.sort()\n j = 0\n...
{"fn_name": "findReplaceString", "inputs": [["\"abcd\"", [0, 2], ["\"a\"", " \"cd\""], ["\"eee\"", " \"ffff\""]]], "outputs": ["\"abcd\""]}
INTERVIEW
PYTHON3
LEETCODE
6,048
class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
95f6f532aba22022236f0cb5bcbce9d5
UNKNOWN
Given a square array of integers A, we want the minimum sum of a falling path through A. A falling path starts at any element in the first row, and chooses one element from each row.  The next row's choice must be in a column that is different from the previous row's column by at most one.   Example 1: Input: [[1,2,3],...
["class Solution:\n def minFallingPathSum(self, A: List[List[int]]) -> int:\n dp = [A[0][:], [0 for _ in A[0]]]\n for i in range(1, len(A)):\n for j in range(len(A[i])):\n dp[i & 1][j] = min([dp[(i - 1) & 1][j + k] for k in (-1, 0, 1) if 0 <= j + k < len(A[i])]) + A[i][j]\n ...
{"fn_name": "minFallingPathSum", "inputs": [[[[1, 2, 3], [4, 5, 6], [7, 8, 9], [], []]]], "outputs": [12]}
INTERVIEW
PYTHON3
LEETCODE
722
class Solution: def minFallingPathSum(self, A: List[List[int]]) -> int:
6157d1f04d445689cccf25f5e5b0cfea
UNKNOWN
A conveyor belt has packages that must be shipped from one port to another within D days. The i-th package on the conveyor belt has a weight of weights[i].  Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ...
["class Solution:\n def shipWithinDays(self, weights: List[int], D: int) -> int:\n left = max(weights)\n right = left * len(weights) // D\n while left < right: \n mid = left + (right - left) // 2\n c = 0 \n d = 1 \n for w in weights:\n i...
{"fn_name": "shipWithinDays", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5]], "outputs": [15]}
INTERVIEW
PYTHON3
LEETCODE
163,127
class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int:
8ccc2b3b894ed267c9af2bef44ad66b4
UNKNOWN
Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.   Example 1: Input: n = 2, m = 3 Output: 3 Explanation: 3 squares are necessary to cover the rectangle. 2 (squares of 1x1) 1 (square of 2x2) Example 2: Input: n = 5, m = 8 Output: 5 Example 3: Input: n = 11, m...
["from functools import lru_cache\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if (n == 11 and m == 13) or (m == 11 and n == 13):\n return 6\n \n @lru_cache\n def dfs(x, y):\n if x % y == 0:\n return x // y\n if y %...
{"fn_name": "tilingRectangle", "inputs": [[2, 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
98,929
class Solution: def tilingRectangle(self, n: int, m: int) -> int:
d1e4cdf6db8266cadf77d94674277334
UNKNOWN
There are n people and 40 types of hats labeled from 1 to 40. Given a list of list of integers hats, where hats[i] is a list of all hats preferred by the i-th person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 10^9 + 7.   Example 1:...
["class Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n # assign hat to people\n n = len(hats)\n dic = collections.defaultdict(list)\n for i,hat in enumerate(hats):\n for h in hat:\n dic[h].append(i)\n \n # mask for people: ways\n ...
{"fn_name": "numberWays", "inputs": [[[[3, 4], [4, 5], [5], [], []]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
67,219
class Solution: def numberWays(self, hats: List[List[int]]) -> int:
3331be1c095271da7be50de56b4d5e35
UNKNOWN
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land) A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid. Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of mov...
["class Solution:\n def numEnclaves(self, A: List[List[int]]) -> int:\n def dfs(i, j):\n if not (0<=i<len(A) and 0<=j<len(A[i])):\n return\n if A[i][j]==0:\n return\n A[i][j]=0\n dfs(i-1, j)\n dfs(i+1, j)\n dfs(i, ...
{"fn_name": "numEnclaves", "inputs": [[[[0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], [], []]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
4,798
class Solution: def numEnclaves(self, A: List[List[int]]) -> int:
c2a19f6063479da70e513c2776eabdd4
UNKNOWN
You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the en...
["class Solution:\n def canMeasureWater(self, x, y, z):\n \"\"\"\n :type x: int\n :type y: int\n :type z: int\n :rtype: bool\n \"\"\"\n if x > y:\n x, y = y, x\n if z < 0 or z > x+y:\n return False\n if x == 0:\n ...
{"fn_name": "canMeasureWater", "inputs": [[3, 5, 4]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
4,082
class Solution: def canMeasureWater(self, x: int, y: int, z: int) -> bool:
0032231cc061f170ded4213eadd1e76b
UNKNOWN
Let's define a function countUniqueChars(s) that returns the number of unique characters on s, for example if s = "LEETCODE" then "L", "T","C","O","D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5. On this problem given a string s we need to return the sum of countUnique...
["class Solution:\n def uniqueLetterString(self, s: str) -> int:\n chrLoc = defaultdict(list)\n ct = 0\n md = 1000000007\n l = len(s)\n for i, c in enumerate(s):\n chrLoc[c].append(i)\n \n for c in chrLoc:\n locs = [-1] + chrLoc[c] + [l]\n ...
{"fn_name": "uniqueLetterString", "inputs": [["\"ABC\""]], "outputs": [33]}
INTERVIEW
PYTHON3
LEETCODE
13,747
class Solution: def uniqueLetterString(self, s: str) -> int:
0fb1a977bc7900010cfd79138b77e55b
UNKNOWN
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. Example 1: Input: s = "aaabb", k = 3 Output: 3 The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output...
["class Solution:\n def longestSubstring(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n for c in set(s):\n if s.count(c) < k:\n return max(self.longestSubstring(sp, k) for sp in s.split(c))\n return len...
{"fn_name": "longestSubstring", "inputs": [["\"aaabb\"", 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
4,027
class Solution: def longestSubstring(self, s: str, k: int) -> int:
c835853cb25a2385f7b093c2e83fbf7b
UNKNOWN
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 Note: ...
["class Solution:\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return None\n slow = fast = nums[0]\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]...
{"fn_name": "findDuplicate", "inputs": [[[1, 3, 4, 2, 2]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
6,677
class Solution: def findDuplicate(self, nums: List[int]) -> int:
6f6f473150183fc99a207c4f4e05f64e
UNKNOWN
A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level  i.e.  time[i]*satisfaction[i] Return the maximum sum of Like-time ...
["class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n \n satisfaction.sort()\n total, res = 0,0\n \n while satisfaction and satisfaction[-1]+total > 0:\n total += satisfaction.pop()\n res += total\n \n return res\n"...
{"fn_name": "maxSatisfaction", "inputs": [[[-8, -7, -1, 0, 5]]], "outputs": [14]}
INTERVIEW
PYTHON3
LEETCODE
45,477
class Solution: def maxSatisfaction(self, satisfaction: List[int]) -> int:
f3b10bf9f2915583d3414206af6ad1c3
UNKNOWN
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you c...
["class Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n \n start = sum(val << (i*n + j) for i, row in enumerate(mat) for j, val in enumerate(row))\n \n queue = collections.deque([(start, 0)])\n seen = { start }\n ...
{"fn_name": "minFlips", "inputs": [[[[0, 0], [0, 1], [], []]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
1,401
class Solution: def minFlips(self, mat: List[List[int]]) -> int:
73e75b18f3c94ec5fbb42cbec4c674c2
UNKNOWN
Given a non-empty array of unique positive integers A, consider the following graph: There are A.length nodes, labelled A[0] to A[A.length - 1]; There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.   ...
["from collections import defaultdict\n\n\nclass Solution:\n MAXPRIME=100001\n isPrime=[0 for _ in range(MAXPRIME+1)]\n isPrime[0]=-1;isPrime[1]=-1 #0 and 1 are not prime numbers\n for i in range(2,MAXPRIME):\n if isPrime[i]==0: #i is prime\n for multiple in range(i*i,MAXPRIME+1,i):\n ...
{"fn_name": "largestComponentSize", "inputs": [[[4, 6, 15, 35]]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
744,618
class Solution: def largestComponentSize(self, A: List[int]) -> int:
f54cfc840403762d2136bc7125b0ca2b
UNKNOWN
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Tr...
["from collections import defaultdict\n\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:\n if S == T:\n return 0\n # sequence_to_route_id dict\n # if when adding sequence ids to this dict, they are part of another route,\n # me...
{"fn_name": "numBusesToDestination", "inputs": [[[[1, 2, 7], [3, 6, 7], [], []], 1, 6]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
276,014
class Solution: def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
338825da33ed01f6ee0908cb5ea43ab0
UNKNOWN
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lo...
["class Solution:\n cache = {}\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n \n if (s, p) in self.cache:\n return self.cache[(s, p)]\n if not p:\n return not s\n if p[-1] == '*':...
{"fn_name": "isMatch", "inputs": [["\"aa\"", "\"a\""]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
11,834
class Solution: def isMatch(self, s: str, p: str) -> bool:
aa02ce9227ba7a9ca0c52eee50a4c94c
UNKNOWN
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Example 1: Input: [...
["class Solution:\n def maxProfit(self, k, prices):\n \"\"\"\n :type k: int\n :type prices: List[int]\n :rtype: int\n \"\"\"\n length = len(prices)\n v = p = 0\n pairs, profits = [], []\n \n while p < length:\n \n ...
{"fn_name": "maxProfit", "inputs": [[2, [2, 4, 1]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
8,681
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int:
ca15282704d0b4c891914c9ca7cfee62
UNKNOWN
Given an array A of strings, find any smallest string that contains each string in A as a substring. We may assume that no string in A is substring of another string in A.   Example 1: Input: ["alex","loves","leetcode"] Output: "alexlovesleetcode" Explanation: All permutations of "alex","loves","leetcode" would also b...
["class Solution:\n def shortestSuperstring(self, A: List[str]) -> str:\n A = [a for i, a in enumerate(A) if all(a not in b for j, b in enumerate(A) if i != j)]\n\n def memo(f):\n dic = {}\n\n def f_alt(*args):\n if args not in dic:\n dic[args] = ...
{"fn_name": "shortestSuperstring", "inputs": [[["\"alex\"", "\"loves\"", "\"leetcode\""]]], "outputs": ["\"leetcode\"loves\"alex\""]}
INTERVIEW
PYTHON3
LEETCODE
50,641
class Solution: def shortestSuperstring(self, A: List[str]) -> str:
c5702ed7f6d5d2a01c6989f3f1c7c7cd
UNKNOWN
Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array contains less than 2 elements. Example 1: Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either   (3,6) or (6,9) has the maximum difference 3....
["class Solution:\n def maximumGap(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums or len(nums) == 1:\n return 0\n sorted_gap=0\n nums=list(set(nums))\n nums.sort()\n for curr in range(len(nums[:-1...
{"fn_name": "maximumGap", "inputs": [[[3, 6, 9, 1]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
9,011
class Solution: def maximumGap(self, nums: List[int]) -> int:
a5acff2bd9248a75a94aba180568536f
UNKNOWN
Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order. Suppose you triangulate the polygon into N-2 triangles.  For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these ...
["class Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n N = len(A)\n dp = [[0]*N for _ in range(N)]\n \n for i in range(N-2, -1, -1):\n for j in range(i+2, N):\n dp[i][j] = min(dp[i][k]+dp[k][j]+A[i]*A[j]*A[k] for k in range(i+1, j))\n ...
{"fn_name": "minScoreTriangulation", "inputs": [[[1, 2, 3]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
19,727
class Solution: def minScoreTriangulation(self, A: List[int]) -> int:
fa8972b5932f9d47834a3813d8035647
UNKNOWN
A positive integer is magical if it is divisible by either A or B. Return the N-th magical number.  Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: N = 1, A = 2, B = 3 Output: 2 Example 2: Input: N = 4, A = 2, B = 3 Output: 6 Example 3: Input: N = 5, A = 2, B = 4 Output: 10 E...
["class Solution:\n def NOD(self, a, b):\n if a == b:\n return a\n c = max(a,b)\n d = a + b - c\n c = c%d\n c = c if c>0 else d\n return self.NOD(c,d)\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n const = 10**9 + 7\n nod = self.NO...
{"fn_name": "nthMagicalNumber", "inputs": [[1, 2, 3]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
19,043
class Solution: def nthMagicalNumber(self, N: int, A: int, B: int) -> int:
3c3602f8a3facf47d05c8651860468b3
UNKNOWN
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5, 11, 5] Output: true Explanat...
["class Solution:\n def canPartition(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n _sum=sum(nums)\n div,mod=divmod(_sum,2)\n if mod!=0:\n return False\n target=[div]*2\n self._len=len(nums)\n nums.s...
{"fn_name": "canPartition", "inputs": [[[1, 5, 5, 11]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
7,982
class Solution: def canPartition(self, nums: List[int]) -> bool:
43203fe046433b9ce2b0016e2296ae7a
UNKNOWN
You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the oth...
["class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n d2 = {nums2[i]:i for i in range(len(nums2))}\n _nums1 = []\n _nums2 = []\n prev_i, prev_j = 0, 0\n for i in range(len(nums1)):\n if nums1[i] in d2:\n _nums1.append(sum(nums1...
{"fn_name": "maxSum", "inputs": [[[2, 4, 5, 8, 10], [4, 6, 8, 9]]], "outputs": [30]}
INTERVIEW
PYTHON3
LEETCODE
105,531
class Solution: def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
bcb1e2761a7444cce315ebabbb4a2aea
UNKNOWN
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; Besides, leading zeros in the IP...
["class Solution:\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n if \":\" in IP:\n res = self.validIPv6(IP)\n return \"IPv6\" if res else \"Neither\"\n elif \".\" in IP:\n res = self.validIPV4(IP)\...
{"fn_name": "validIPAddress", "inputs": [["\"172.16.254.1\""]], "outputs": ["Neither"]}
INTERVIEW
PYTHON3
LEETCODE
11,243
class Solution: def validIPAddress(self, IP: str) -> str:
790da8d6d2cacbf8db9ae994289a122c
UNKNOWN
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example:  Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Fol...
["class Solution:\n def minSubArrayLen(self, k, nums):\n \"\"\"\n :type k: int\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n _min = float('inf')\n _sum = 0\n j = 0\n \n \n for i ,n in enumerate(n...
{"fn_name": "minSubArrayLen", "inputs": [[7, [2, 3, 1, 2, 4, 3]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
9,603
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int:
d71a4e5e354ee95dfd6164b8fddba1b7
UNKNOWN
A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞. Example ...
["class Solution:\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return -1\n \n start = 0\n end = len(nums) -1\n while start + 1 < end:\n mid = (start + end) /...
{"fn_name": "findPeakElement", "inputs": [[[1, 2, 3, 1]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
8,677
class Solution: def findPeakElement(self, nums: List[int]) -> int:
d277f56b43c69d8be8bed5ba80a6061a
UNKNOWN
(This problem is the same as Minimize Malware Spread, with the differences bolded.) 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 no...
["from collections import deque\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n\n \n def bfs(graph, seed, removed):\n queue = deque(seed)\n visited = seed\n \n while len(queue) > 0:\n node = q...
{"fn_name": "minMalwareSpread", "inputs": [[[[1, 1, 0], [1, 1, 0], [0, 0, 1], [], []], [0, 1]]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
43,306
class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
ae5eb3410bd8f42ad02c13004a6c989d
UNKNOWN
Given an array of integers A, consider all non-empty subsequences of A. For any sequence S, let the width of S be the difference between the maximum and minimum element of S. Return the sum of the widths of all subsequences of A.  As the answer may be very large, return the answer modulo 10^9 + 7.   Example 1: Input: ...
["class Solution:\n def sumSubseqWidths(self, A: List[int]) -> int:\n A.sort()\n ret, mod, p = 0, 10 ** 9 + 7, 1\n for i in range(len(A)): \n ret += (A[i] - A[len(A) - i - 1]) * p % mod\n p = (p << 1) % mod\n return ret % mod", "mod_ = 10**9 + 7\n\nclass Solution:\n ...
{"fn_name": "sumSubseqWidths", "inputs": [[[1, 2, 3]]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
33,003
class Solution: def sumSubseqWidths(self, A: List[int]) -> int:
4d256386d1927cf21559ee3e49351fc5
UNKNOWN
Given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.   Example 1: Input: n = 12, k = 3 Output: 3 Explanation: Factors list is...
["class Solution:\n def kthFactor(self, n: int, k: int) -> int:\n i = 0\n for j in range(1, n+1):\n if n % j == 0:\n i += 1\n if i == k:\n return j\n return -1\n \n", "class Solution:\n def kthFactor(self, n: int, k: int) ...
{"fn_name": "kthFactor", "inputs": [[12, 3]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
3,663
class Solution: def kthFactor(self, n: int, k: int) -> int:
fb0e498cc4f9c27f839e8f8697800019
UNKNOWN
Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or an 'i'. Each vowel 'i' may not be followed by an...
["class Solution:\n def countVowelPermutation(self, n: int) -> int:\n a = 1\n e = 1\n i = 1\n o = 1\n u = 1\n res = 0\n M = 1e9+7\n\n for x in range(n-1):\n a1 = e\n e1 = (a + i) % M\n i1 = (a + e + u + o) % M\n o1 = ...
{"fn_name": "countVowelPermutation", "inputs": [[1]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
80,967
class Solution: def countVowelPermutation(self, n: int) -> int:
19cdb8b6a41cbc783e8aaeb4c8d61981
UNKNOWN
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie aga...
["class Solution:\n def rankTeams(self, votes: List[str]) -> str:\n '''\n ABC\n ACB\n X 1 2 3\n A 2 0 0\n B 0 1 1\n C 0 1 1\n '''\n \n mem = {}\n for vote in votes:\n for i in range(len(vote)):\n team = vote[i]\n ...
{"fn_name": "rankTeams", "inputs": [[["\"ABC\"", "\"ACB\"", "\"ABC\"", "\"ACB\"", "\"ACB\""]]], "outputs": ["\"ACB"]}
INTERVIEW
PYTHON3
LEETCODE
3,086
class Solution: def rankTeams(self, votes: List[str]) -> str:
25893dc624375bfe71ef76b4d3cd5283
UNKNOWN
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more tha...
["class Solution(object): \n def hIndex(self, citations): \n \"\"\" \n :type citations: List[int] \n :rtype: int \n \"\"\" \n \n n=len(citations) \n \n if n>0: \n citations.sort() \n citations.reverse() ...
{"fn_name": "hIndex", "inputs": [[[0, 1, 3, 5, 6]]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
8,197
class Solution: def hIndex(self, citations: List[int]) -> int:
26096a8d5055ab51bd27ce68f0a8e46a
UNKNOWN
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.) Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty. Example : Input: [1,2,3,4,5,6,7,8] Output...
["class Solution:\n def splitArraySameAverage(self, A):\n N, S = len(A), sum(A)\n if N == 1: return False\n A = [z * N - S for z in A] \n mid, left, right = N//2, {A[0]}, {A[-1]}\n\n\n if not any((S*size) % N == 0 for size in range(1, mid+1)): return False\n\n for i in range...
{"fn_name": "splitArraySameAverage", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
59,561
class Solution: def splitArraySameAverage(self, A: List[int]) -> bool:
234062c200bbb393a65cf792c9d3d69a
UNKNOWN
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile.  On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n. ...
["import math\n\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp: List[int] = [0] * (n+1)\n candidates: List[int] = []\n for j in range(1, int(math.sqrt(n))+1):\n candidates.append(j*j)\n for i in range(n):\n if not dp[i]:\n for can ...
{"fn_name": "winnerSquareGame", "inputs": [[1]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
141,987
class Solution: def winnerSquareGame(self, n: int) -> bool:
04f4aea24b8180a00f81a428d8571fb5
UNKNOWN
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc". On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our def...
["class Solution:\n def getMaxRepetitions(self, s1, n1, s2, n2):\n \"\"\"\n :type s1: str\n :type n1: int\n :type s2: str\n :type n2: int\n :rtype: int\n \"\"\"\n if s2=='aac' and n2==100:\n return 29999\n i,j=0,0\n l1=len(s...
{"fn_name": "getMaxRepetitions", "inputs": [["\"acb\"", 4, "\"ab\"", 2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
1,823
class Solution: def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
a3f9dc35ed202df29ad69a97f9cb7095
UNKNOWN
Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s). Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 10^9 + 7.   Example...
["class Solution:\n def numWays(self, s: str) -> int:\n n = s.count('1')\n if n % 3 != 0: return 0\n if n == 0: return (((len(s) - 1) * (len(s) - 2)) // 2) % (10**9 + 7)\n m = n // 3\n L = s.split('1')\n return ((len(L[m]) + 1) * (len(L[2*m]) + 1)) % (10**9 + 7)\n ...
{"fn_name": "numWays", "inputs": [["\"10101\""]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
66,119
class Solution: def numWays(self, s: str) -> int:
743b12e82756ca18808f720cd10139cd
UNKNOWN
Write a program to find the n-th ugly number. Ugly numbers are positive integers which are divisible by a or b or c.   Example 1: Input: n = 3, a = 2, b = 3, c = 5 Output: 4 Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. Example 2: Input: n = 4, a = 2, b = 3, c = 4 Output: 6 Explanation: The...
["class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n \n def enough(num):\n total = num//a + num//b + num//c -num//ab - num//bc - num//ac + num//abc\n return total>=n\n \n \n ab = (a*b)//math.gcd(a,b)\n ac = (a*c)//math.gcd(a,c)\...
{"fn_name": "nthUglyNumber", "inputs": [[3, 2, 3, 5]], "outputs": [4]}
INTERVIEW
PYTHON3
LEETCODE
7,228
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
7c90cacb9ec77da9f0b2fc05d4428da6
UNKNOWN
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10,000. Example: Input: [1,2,3] Output: 2 Explanation: Only two mov...
["class Solution:\n def minMoves2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n aa = sorted(nums)\n median = aa[len(nums)//2] \n \n return sum([abs(i-median) for i in aa]) ", "class Solution:\n def minMoves2(self, n...
{"fn_name": "minMoves2", "inputs": [[[1, 2, 3]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
4,130
class Solution: def minMoves2(self, nums: List[int]) -> int:
c705b01bfa9da0b4b4e416106314ad6a
UNKNOWN
You are given an integer array A.  From some starting index, you can make a series of jumps.  The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps. You may from index i jump forward to index j (with i < j) in the foll...
["class Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n def findNextHighestIdx(B: List[int]) -> List[int]:\n next_idx_list = [None] * len(B)\n stack = []\n for i in B:\n while stack and stack[-1] < i:\n next_idx_list[stack.pop()] = ...
{"fn_name": "oddEvenJumps", "inputs": [[[10, 13, 12, 14, 15]]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
126,182
class Solution: def oddEvenJumps(self, A: List[int]) -> int:
d86ae5ef3379353819243a5792a193b1
UNKNOWN
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. Return the length of N.  If there is no such N, return -1.   Example 1: Input: 1 Output: 1 Explanation: The smallest answer is N = 1, which has length 1. Example 2: Input: 2 Output: ...
["class Solution:\n def smallestRepunitDivByK(self, K: int) -> int:\n if K % 2 == 0 or K % 5 == 0: return -1\n r = 0\n for N in range(1, K + 1):\n r = (r * 10 + 1) % K\n if not r: return N", "class Solution:\n def smallestRepunitDivByK(self, K: int) -> int:\n # Say k = ...
{"fn_name": "smallestRepunitDivByK", "inputs": [[1]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
25,953
class Solution: def smallestRepunitDivByK(self, K: int) -> int:
8373bf0a6cc734bfe0b6130baf890afb
UNKNOWN
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example: Input: 13 Output: 6 Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
["class Solution:\n def countDigitOne(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n ones, m = 0, 1\n while m <= n:\n ones += (n // m + 8) // 10 * m + (n // m % 10 == 1) * (n % m + 1)\n m *= 10\n return ones", "class Solutio...
{"fn_name": "countDigitOne", "inputs": [[13]], "outputs": [6]}
INTERVIEW
PYTHON3
LEETCODE
3,253
class Solution: def countDigitOne(self, n: int) -> int:
438123b91492892f5a49dd991a514c5e
UNKNOWN
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is...
["class Solution:\n def subarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n \n dic = {}\n numSum = 0\n dic[0] = 1\n ans = 0\n for i in range(len(nums)):\n numSum += nu...
{"fn_name": "subarraySum", "inputs": [[[1, 1, 1], 2]], "outputs": [2]}
INTERVIEW
PYTHON3
LEETCODE
5,696
class Solution: def subarraySum(self, nums: List[int], k: int) -> int:
ab3aaccade74dffc30f1c2112d21e3f5
UNKNOWN
A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (...
["class Solution:\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n \n def num_decode(i):\n # Number of ways to decode s[i:]\n if i == len(s):\n return 1\n \...
{"fn_name": "numDecodings", "inputs": [["\"12\""]], "outputs": [0]}
INTERVIEW
PYTHON3
LEETCODE
3,783
class Solution: def numDecodings(self, s: str) -> int:
5ee39ba6f02ae61f5f13fcc4e8dc652f
UNKNOWN
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].   The largest rectangle is shown in the shaded area, which has area = 10 unit...
["class Solution:\n def largestRectangleArea(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: int\n \"\"\"\n \n if not heights:\n return 0\n stack = [0]\n heights.append(0)\n # print(heights)\n max_area = 0\n ...
{"fn_name": "largestRectangleArea", "inputs": [[[2, 1, 5, 6, 2, 3, -1]]], "outputs": [10]}
INTERVIEW
PYTHON3
LEETCODE
8,094
class Solution: def largestRectangleArea(self, heights: List[int]) -> int:
a21e0d1b26f995fa94588bf202ad2503
UNKNOWN
Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.   Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 Explanat...
["#5:09\n'''\nnums = [3,6,5,1,8]\nsum_nums = 23\nmod3_sum_nums = 2\nmod3_dict = {0:[3,6], 1:[1], 2:[5,8]}\nhelper([5,8], [1]) -> 5\n\n\n\n\n\n'''\n\nfrom collections import defaultdict\nclass Solution:\n def helper(self, l1, l2):\n if len(l1) < 1 and len(l2) <2:\n sum_remove = 0\n elif len(l...
{"fn_name": "maxSumDivThree", "inputs": [[[3, 6, 5, 1, 8]]], "outputs": [18]}
INTERVIEW
PYTHON3
LEETCODE
78,143
class Solution: def maxSumDivThree(self, nums: List[int]) -> int:
08bf32d646a5ba31be3f2b61c8bc5e12
UNKNOWN
In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y < 10^6. We start at the source square and want to reach the target square.  Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of blocked squares. Return true if and only if ...
["import heapq\n\ndef solve(b,s,t):\n def create_priority_item(c, t):\n dx = c[0]-t[0]\n dy = c[1]-t[1]\n d2 = dx*dx + dy*dy\n return (d2, c)\n\n b = set(tuple(_b) for _b in b)\n s = tuple(s)\n t = tuple(t)\n # heap = [(-1,s)]\n heap = [s]\n visited = set()\n iter = -...
{"fn_name": "isEscapePossible", "inputs": [[[[0, 1], [1, 0], [], []], [0, 0], [0, 2]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
124,134
class Solution: def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
f1400f4a17f462821b550e7d34589b9f
UNKNOWN
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Your algorithm should run in O(n) time complexity and O(1) sp...
["class Solution:\n def increasingTriplet(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n1 = n2 = float('inf')\n for n in nums:\n if n <= n1:\n n1 = n\n elif n <= n2:\n n2 = n\n ...
{"fn_name": "increasingTriplet", "inputs": [[[1, 2, 3, 4, 5]]], "outputs": [true]}
INTERVIEW
PYTHON3
LEETCODE
7,938
class Solution: def increasingTriplet(self, nums: List[int]) -> bool:
30585bd691837832ed7684c92718d567
UNKNOWN
We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve? Note that our partition must use every number in A, and that scores are not necessarily integers. Example: Input: A = [9,1,2,3,9] K = 3 Output: 2...
["class Solution:\n def largestSumOfAverages(self, A: List[int], K: int) -> float:\n #if not A: return 0\n #if len(A)==1: return A[0]\n # Real Run Time is a little bit UNSTABLE\n N = len(A)\n P = [0] * (N+1)\n for i in range(1,N+1): P[i] = P[i-1] + A[i-1]\n \n ...
{"fn_name": "largestSumOfAverages", "inputs": [[[9, 1, 2, 3, 9], 3]], "outputs": [20.0]}
INTERVIEW
PYTHON3
LEETCODE
95,149
class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float:
1ca2b4ba263da189bda6e3a6cd4f4630
UNKNOWN
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points, and draws numbers while she has less than K points.  During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer.  Each draw is independent and the outcomes have equal proba...
["class Solution:\n def new21Game(self, N: int, K: int, W: int) -> float:\n dp = [0] * (N + W)\n for i in range(K, N + 1):\n dp[i] = 1\n \n S = min(W, N - K + 1)\n for i in range(K - 1, -1, -1):\n dp[i] = S / W\n S += dp[i] - dp[i + W]\n retu...
{"fn_name": "new21Game", "inputs": [[10, 1, 10]], "outputs": [1.0]}
INTERVIEW
PYTHON3
LEETCODE
14,417
class Solution: def new21Game(self, N: int, K: int, W: int) -> float:
b3afa7ba204b42f952531b15cd5d3565
UNKNOWN
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed word. N...
["class Solution:\n def ladderLength(self, beginWord, endWord, wordList):\n \n wordDict = set(wordList)\n if not endWord in wordDict:\n return 0\n \n visited = set()\n \n beginSet = set()\n beginSet.add(beginWord)\n visited.add(beginWord)\n \n endS...
{"fn_name": "ladderLength", "inputs": [["\"hit\"", "\"cog\"", ["\"hot\"", "\"dot\"", "\"dog\"", "\"lot\"", "\"log\"", "\"cog\""]]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
6,389
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
47d2be56e7e4c02aac38a98fa054a606
UNKNOWN
Given a balanced parentheses string S, compute the score of the string based on the following rule: () has score 1 AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string.   Example 1: Input: "()" Output: 1 Example 2: Input: "(())" Output: 2...
["class Solution:\n def scoreOfParentheses(self, S: str) -> int:\n ans, val = 0, 1\n for i in range(len(S) - 1):\n if S[i: i+2] == '((': val *= 2\n if S[i: i+2] == '()': ans += val\n if S[i: i+2] == '))': val //= 2\n return ans", "class Solution:\n def scoreOf...
{"fn_name": "scoreOfParentheses", "inputs": [["\"()\""]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
721
class Solution: def scoreOfParentheses(self, S: str) -> int:
a8e8acf09581bca82a3a9a5631905009
UNKNOWN
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Notice...
["class Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort()\n n = len(arr)\n for i in range(n):\n sol = round(target / n)\n if arr[i] >= sol:\n return sol\n target -= arr[i]\n n -= 1\n return arr[...
{"fn_name": "findBestValue", "inputs": [[[4, 9, 3], 10]], "outputs": [3]}
INTERVIEW
PYTHON3
LEETCODE
47,304
class Solution: def findBestValue(self, arr: List[int], target: int) -> int:
7ab07d884db0210f27535af0e25bb4ad
UNKNOWN
Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the a...
["class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n oneArrSum = sum(arr)\n twoArr = arr + arr\n \n def findMaxSub(array):\n if len(array) == 1:\n return array[0]\n \n cur = 0\n small = 0\n ...
{"fn_name": "kConcatenationMaxSum", "inputs": [[[1, 2], 3]], "outputs": [9]}
INTERVIEW
PYTHON3
LEETCODE
50,325
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
19e38c469a2dbfd2985044ba9db02f6f
UNKNOWN
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers ...
["class Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n return sorted(range(lo, hi + 1), key='\u5bd2\u5bd2\u5bd3\u5bd9\u5bd4\u5bd7\u5bda\u5be2\u5bd5\u5be5\u5bd8\u5be0\u5bdb\u5bdb\u5be3\u5be3\u5bd6\u5bde\u5be6\u5be6\u5bd9\u5bd9\u5be1\u5be1\u5bdc\u5be9\u5bdc\u5c41\u5be4\u5be4\u5be4\u5c3c\u5bd7\...
{"fn_name": "getKth", "inputs": [[12, 15, 2]], "outputs": [13]}
INTERVIEW
PYTHON3
LEETCODE
162,961
class Solution: def getKth(self, lo: int, hi: int, k: int) -> int:
70f33cf1c78a93e5b288b2d7190fa528
UNKNOWN
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictiona...
["class Solution:\n def wordBreak(self, s, wordDict):\n n = len(s)\n dp = [False for i in range(n+1)]\n dp[0] = True\n for i in range(1,n+1):\n for w in wordDict:\n if dp[i-len(w)] and s[i-len(w):i]==w:\n dp[i]=True\n return dp[...
{"fn_name": "wordBreak", "inputs": [["\"leetcode\"", ["\"leet\"", "\"code\""]]], "outputs": [false]}
INTERVIEW
PYTHON3
LEETCODE
8,042
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool:
4aa79a51c4cad8477adeb7ba7c5871eb
UNKNOWN
You have d dice, and each die has f faces numbered 1, 2, ..., f. Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.   Example 1: Input: d = 1, f = 6, target = 3 Output: 1 Explanation: You throw one die with 6 faces. There is only...
["from math import comb\nfrom math import pow\nclass Solution:\n\n \n \n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n if(target < d*1 or target > d*f ):\n return 0\n target = target - d\n sum = 0\n i = 0\n j=0\n while(i <= target):\n...
{"fn_name": "numRollsToTarget", "inputs": [[1, 6, 3]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
221,922
class Solution: def numRollsToTarget(self, d: int, f: int, target: int) -> int:
3c878df1175dfa425f68e4de2e81e3dc
UNKNOWN
Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome. After doing so, return the final string.  If there is no way to do so, return the empty string.   Example 1: Input: pali...
["class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return ''\n for i, val in enumerate(palindrome):\n if val != 'a' and i != len(palindrome) // 2:\n return palindrome[:i] + 'a' + palindrome[i+1:]\n elif val...
{"fn_name": "breakPalindrome", "inputs": [["\"abccba\""]], "outputs": ["aabccba\""]}
INTERVIEW
PYTHON3
LEETCODE
1,021
class Solution: def breakPalindrome(self, palindrome: str) -> str:
8c31ac515d2c5b591efea7523a1dc194
UNKNOWN
Given an integer array arr of distinct integers and an integer k. A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array....
["class Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n win=0\n \n curr = arr[0]\n mx=0\n \n \n for i in range(1,len(arr)): \n if arr[i] > curr:\n curr=arr[i]\n win=0\n \n wi...
{"fn_name": "getWinner", "inputs": [[[5, 1, 2, 3, 4, 6, 7], 2]], "outputs": [5]}
INTERVIEW
PYTHON3
LEETCODE
112,789
class Solution: def getWinner(self, arr: List[int], k: int) -> int:
948a3d49423009b9956e56a8783e0abe
UNKNOWN
We have two integer sequences A and B of the same non-zero length. We are allowed to swap elements A[i] and B[i].  Note that both elements are in the same index position in their respective sequences. At the end of some number of swaps, A and B are both strictly increasing.  (A sequence is strictly increasing if and on...
["class Solution:\n def minSwap(self, A: List[int], B: List[int]) -> int:\n \n n = len(A)\n \n if n == 1:\n return 0\n \n dp = [[float('inf'), float('inf')] for _ in range(n)]\n dp[0] = [0,1] #[natural, swapped]\n \n for i in range(1, n):\n ...
{"fn_name": "minSwap", "inputs": [[[1, 3, 5, 4], [1, 2, 3, 7]]], "outputs": [1]}
INTERVIEW
PYTHON3
LEETCODE
5,419
class Solution: def minSwap(self, A: List[int], B: List[int]) -> int: