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
1210b743ff3e9f943a7faf284f69e648
UNKNOWN
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).   Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(...
["class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if nums[0] > nums[1]:\n largest = nums[0]\n second_largest = nums[1]\n else:\n largest = nums[1]\n second_largest = nums[0]\n for i in range(2,len(nums)):\n if nums[i] > lar...
{"fn_name": "maxProduct", "inputs": [[[3, 4, 5, 2]]], "outputs": [12]}
INTRODUCTORY
PYTHON3
LEETCODE
38,114
class Solution: def maxProduct(self, nums: List[int]) -> int:
146b564a9362f5cb2b668098fa03275f
UNKNOWN
Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.   Example 1: Input: n...
["class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n res = 1\n for ind,n in enumerate(nums):\n temp = 1-sum(nums[:ind+1])\n if(temp > res):\n res = temp\n return res", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n ...
{"fn_name": "minStartValue", "inputs": [[[-3, 2, -3, 4, 2]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
4,753
class Solution: def minStartValue(self, nums: List[int]) -> int:
2c1550328e88c0db66332fb2cd2c9bb5
UNKNOWN
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inp...
["class Solution:\n def addStrings(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n if len(num1) < len(num2):\n num1, num2 = num2, num1\n addon = 0\n res = \"\"\n l = len(num2)\n for i...
{"fn_name": "addStrings", "inputs": [["\"0\"", "\"0\""]], "outputs": ["172"]}
INTRODUCTORY
PYTHON3
LEETCODE
1,592
class Solution: def addStrings(self, num1: str, num2: str) -> str:
9032f3100777a743fe2dc3e43e5cc29a
UNKNOWN
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does not contain any non-printable characters. Example: Input: "Hello, my name is John" Output: 5
["class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return len(s.split())", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count = 0\n ...
{"fn_name": "countSegments", "inputs": [["\"Hello, my name is John\""]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
3,404
class Solution: def countSegments(self, s: str) -> int:
0271fa372b5c0414a7e10858696f27d0
UNKNOWN
Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i]. After this process, we have some array B. Return the smallest possible difference between the maximum value of B and the minimum value of B.   Example 1: Input: A = [1], K = 0 Output: 0 Explanation: B = [1] ...
["class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n if len(A) == 1:\n return 0\n _min = min(A)\n _max = max(A)\n if _max - K <= _min + K:\n return 0\n return _max - _min - 2*K", "class Solution:\n def smallestRangeI(self, A: List[in...
{"fn_name": "smallestRangeI", "inputs": [[[1], 0]], "outputs": [0]}
INTRODUCTORY
PYTHON3
LEETCODE
8,232
class Solution: def smallestRangeI(self, A: List[int], K: int) -> int:
b7b5cd512aa2aab416fef98a92d675ec
UNKNOWN
Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain 0 and 1. The length of inpu...
["class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums == []:\n return 0\n \n count = 0\n countMax =0\n for ele in nums:\n if ele == 1:\n ...
{"fn_name": "findMaxConsecutiveOnes", "inputs": [[[1, 0, 1, 1, 0, 1]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
4,535
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
517bd519627d233503d4ce646aa1d0f2
UNKNOWN
Given a non-empty array of integers, every element appears twice except for one. 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,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4
["class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l = len(nums)\n if l == 1:\n return nums[0]\n \n # Attempt 1 - 80%\n # nums.sort()\n # i = 0\n # while i < l...
{"fn_name": "singleNumber", "inputs": [[[2, 2, 1]]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
6,065
class Solution: def singleNumber(self, nums: List[int]) -> int:
6af081e90f40a4086498984f40267bd0
UNKNOWN
A boomerang is a set of 3 points that are all distinct and not in a straight line. Given a list of three points in the plane, return whether these points are a boomerang.   Example 1: Input: [[1,1],[2,3],[3,2]] Output: true Example 2: Input: [[1,1],[2,2],[3,3]] Output: false   Note: points.length == 3 points[i].len...
["class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n x1, y1 = points[0]\n x2, y2 = points[1]\n x3, y3 = points[2]\n \n return (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1)\n", "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n ...
{"fn_name": "isBoomerang", "inputs": [[[[1, 1], [2, 3], [3, 2], [], []]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
741
class Solution: def isBoomerang(self, points: List[List[int]]) -> bool:
0a65ebfbf26115b9a4b786a002fb5ad5
UNKNOWN
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3:...
["class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n if n % 2 == 0:\n n = n >> 1\n \n cnt = 0\n a = n\n while (a>0):\n cnt += 1\n a = a >> 1\n ...
{"fn_name": "hasAlternatingBits", "inputs": [[5]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
4,384
class Solution: def hasAlternatingBits(self, n: int) -> bool:
a4f5e8612846f96de89f4ff28e9227d5
UNKNOWN
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There...
["class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n # import collections\n # unique_nums = set(nums)\n # count = 0\n # new_nums = collections.Counter(nums)\n # if k ...
{"fn_name": "findPairs", "inputs": [[[3, 1, 4, 1, 5], 2]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
11,791
class Solution: def findPairs(self, nums: List[int], k: int) -> int:
f96b61aa5466e2b28de3f13e7031d644
UNKNOWN
You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one round's score): Directly represents the number of points you get in this round. "+" (one round's score): Represents that the points you get in this round are the sum of the last two vali...
["class Solution:\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n sum = 0\n for i in range (len(ops)):\n op = ops[i]\n if self.isInt(op):\n sum = sum + int(op)\n elif op == 'C':\n ...
{"fn_name": "calPoints", "inputs": [[["\"5\"", "\"2\"", "\"C\"", "\"D\"", "\"+\""]]], "outputs": [0]}
INTRODUCTORY
PYTHON3
LEETCODE
2,712
class Solution: def calPoints(self, ops: List[str]) -> int:
3521fd69b95698da8248c79c92680b3b
UNKNOWN
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter...
["class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n # count_dash = 0\n # for item in S:\n # if item == '-':\n # count_dash += 1\n \n # S_l...
{"fn_name": "licenseKeyFormatting", "inputs": [["\"5F3Z-2e-9-w\"", 4]], "outputs": ["\"5-F3Z2-E9W\""]}
INTRODUCTORY
PYTHON3
LEETCODE
8,439
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str:
9f4e7d1c56a1340474e88e7b17f35b98
UNKNOWN
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Exa...
["class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n \n \"\"\"\n i = 0\n while i < len(bits)-1:\n if bits[i] == 1:\n i += 2\n \n else: ...
{"fn_name": "isOneBitCharacter", "inputs": [[[1, 0, 0]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
8,479
class Solution: def isOneBitCharacter(self, bits: List[int]) -> bool:
4792f27bc329a4d8a5c27d7333167cab
UNKNOWN
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.     Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a vali...
["class Solution:\n def generateTheString(self, n: int) -> str:\n \n \n \n if n%2 == 0:\n \n return ''.join(['a']*(n-1) + ['b'])\n \n else:\n if n == 1:\n return 'a'\n else:\n return ''.join(['a']*(n-2) + ...
{"fn_name": "generateTheString", "inputs": [[4]], "outputs": ["aaab"]}
INTRODUCTORY
PYTHON3
LEETCODE
1,003
class Solution: def generateTheString(self, n: int) -> str:
1cf1d5342065d5340569ab4cc826e88b
UNKNOWN
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false
["class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n cleanlist = [c for c in s.lower() if c.isalnum()]\n return cleanlist == cleanlist[::-1]", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :typ...
{"fn_name": "isPalindrome", "inputs": [["\"A man, a plan, a canal: Panama\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
4,228
class Solution: def isPalindrome(self, s: str) -> bool:
5d8255b7475b78c5f99d85a9bfa2bdbf
UNKNOWN
Given an array of positive integers arr,  find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Retu...
["import queue\n\n\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n streak = 0\n \n for i in range(len(arr)-m):\n if arr[i] == arr[i+m]:\n streak +=1\n else:\n streak = 0\n if streak == (k-1)*m:...
{"fn_name": "containsPattern", "inputs": [[[1, 2, 4, 4, 4, 4], 1, 3]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
7,364
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
8632e4f03ac59650f068bd94589f7f8c
UNKNOWN
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello World" Output: 5
["class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n x = s.split()\n return len(x[-1]) if len(x) > 0 else 0", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype:...
{"fn_name": "lengthOfLastWord", "inputs": [["\"Hello World\""]], "outputs": [6]}
INTRODUCTORY
PYTHON3
LEETCODE
4,640
class Solution: def lengthOfLastWord(self, s: str) -> int:
6f254d74707b2c2c7eae8af8b7156228
UNKNOWN
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an emp...
["class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if haystack == \"\" and needle == \"\":\n return 0\n if needle == \"\":\n return 0\n if haystack...
{"fn_name": "strStr", "inputs": [["\"hello\"", "\"ll\""]], "outputs": [-1]}
INTRODUCTORY
PYTHON3
LEETCODE
13,645
class Solution: def strStr(self, haystack: str, needle: str) -> int:
0d9ea713d77eac88157b0057126e8012
UNKNOWN
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 ...
["class Solution:\n \n dictionary = {}\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n number = 0\n if n == 0 or n == 1:\n return 1\n if n in self.dictionary:\n return self.dictionary[n]\n el...
{"fn_name": "climbStairs", "inputs": [[2]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
5,365
class Solution: def climbStairs(self, n: int) -> int:
9e724507ee151fd7ab50c4c9f69f7240
UNKNOWN
Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. To make the string good, you can choose two adjace...
["class Solution:\n def makeGood(self, s: str) -> str:\n \n stack=[]\n \n for i in s:\n if (stack!=[] and i.lower()==stack[-1].lower() and i!=stack[-1] ) :\n stack.pop()\n else:\n stack.append(i)\n return ''.join(stack)\n ...
{"fn_name": "makeGood", "inputs": [["\"leEeetcode\""]], "outputs": ["\"leetcode\""]}
INTRODUCTORY
PYTHON3
LEETCODE
2,957
class Solution: def makeGood(self, s: str) -> str:
13806b537b1bf1fedd5f62a7c6c0994a
UNKNOWN
Given a string s. You should re-order the string using the following algorithm: Pick the smallest character from s and append it to the result. Pick the smallest character from s which is greater than the last appended character to the result and append it. Repeat step 2 until you cannot pick more characters. Pick the...
["class Solution:\n def sortString(self, s: str) -> str:\n sforward = sorted(s)\n sbackward = sforward[-1]\n \n suniq = ''\n \n for i in s:\n if i not in suniq:\n suniq += i\n\n suniq = sorted(suniq)\n \n max_count = 0\n ...
{"fn_name": "sortString", "inputs": [["\"aaaabbbbcccc\""]], "outputs": ["\"abccba\"abccba"]}
INTRODUCTORY
PYTHON3
LEETCODE
17,202
class Solution: def sortString(self, s: str) -> str:
64f2901b698af387b274ba0c8574878b
UNKNOWN
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed.   Example 1: Input: text = "nlaebolko" Output: 1 Example 2: Input: text = "loonbalxballp...
["class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n memo = defaultdict(int)\n for t in text:\n if t in 'balon':\n memo[t] += 1\n count_once = min(memo['b'], memo['a'], memo['n'])\n count_twice = min(memo['l'], memo['o'])\n return min(cou...
{"fn_name": "maxNumberOfBalloons", "inputs": [["\"nlaebolko\""]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
2,625
class Solution: def maxNumberOfBalloons(self, text: str) -> int:
485241671c86dd3d886dacadfb36d2ce
UNKNOWN
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their...
["class Solution:\n def binaryGap(self, n: int) -> int:\n maxDist = 0\n currDist = 0\n while n:\n if n & 1 and currDist != 0:\n maxDist = max(maxDist, currDist)\n currDist = 1\n elif n & 1:\n currDist = 1\n elif not n ...
{"fn_name": "binaryGap", "inputs": [[22]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
2,506
class Solution: def binaryGap(self, n: int) -> int:
490d6bbdd26b47b5b432d0fed59e81cd
UNKNOWN
Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in th...
["class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n if len(word) == 0:\n return True\n elif word.isupper() or word.islower():\n return True\n elif len(word) > 1:\n retur...
{"fn_name": "detectCapitalUse", "inputs": [["\"USA\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
2,985
class Solution: def detectCapitalUse(self, word: str) -> bool:
9707c71732f6b9319970e89901d5faeb
UNKNOWN
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. Example 1: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: Th...
["class Solution:\n def findLHS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(nums)\n ret = 0\n for i in count:\n if i+1 in count:\n ret = max(ret, count[i]+count[i+1])\n \...
{"fn_name": "findLHS", "inputs": [[[1, 3, 2, 2, 5, 2, 3, 7]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
363
class Solution: def findLHS(self, nums: List[int]) -> int:
1325b6730467911fb671ba0732f453ee
UNKNOWN
Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not include the letter "y".
["class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n char_list = list(s)\n first, last = 0, len(char_list) - 1\n while first < last:\n ...
{"fn_name": "reverseVowels", "inputs": [["\"hello\""]], "outputs": ["\"holle\""]}
INTRODUCTORY
PYTHON3
LEETCODE
6,572
class Solution: def reverseVowels(self, s: str) -> str:
3c1eaf2781d1acd7a72d275e9c7f7487
UNKNOWN
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" ...
["class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n re = 0\n set_s = set(s)\n flag = False\n for x in set_s:\n if s.count(x) % 2 == 0:\n re += s.count(x)\n elif s....
{"fn_name": "longestPalindrome", "inputs": [["\"abccccdd\""]], "outputs": [9]}
INTRODUCTORY
PYTHON3
LEETCODE
4,948
class Solution: def longestPalindrome(self, s: str) -> int:
d8556b80162bf3a84572eab9e92935b1
UNKNOWN
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing i...
["class Solution:\n def removePalindromeSub(self, s: str) -> int:\n # 'a' 1\n # 'aa' 1\n # 'ab' 2\n # 'abb' 2\n # 'aabb' 2\n # 'abba' 1\n # 'abaaba'\n \n if len(s) == 0:\n return 0\n if s == s[::-1]:\n return 1\n retur...
{"fn_name": "removePalindromeSub", "inputs": [["\"ababa\""]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
1,248
class Solution: def removePalindromeSub(self, s: str) -> int:
b02bc6a419c4f9707597cbb6cdf0dc60
UNKNOWN
Given an array of unique integers salary where salary[i] is the salary of the employee i. Return the average salary of employees excluding the minimum and maximum salary.   Example 1: Input: salary = [4000,3000,1000,2000] Output: 2500.00000 Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. ...
["class Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n del salary[0]\n del salary[-1]\n return sum(salary)/len(salary)", "class Solution:\n def average(self, salary: List[int]) -> float:\n mx = 0\n mn = 100005\n sm = 0\n n = len...
{"fn_name": "average", "inputs": [[[1000, 2000, 3000, 4000]]], "outputs": [2500.0]}
INTRODUCTORY
PYTHON3
LEETCODE
3,274
class Solution: def average(self, salary: List[int]) -> float:
18b2f7b2c92eba8127f29cc00a861ee5
UNKNOWN
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note:...
["class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n ransome = set(ransomNote)\n for i in ransome:\n if ransomNote.count(i) > magazine.count(i):\n ...
{"fn_name": "canConstruct", "inputs": [["\"a\"", "\"b\""]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
6,482
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool:
cd4933859b965682ca79ea511d4d0856
UNKNOWN
We have a collection of stones, each stone has a positive integer weight. Each turn, we choose the two heaviest stones 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 d...
["class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n while True:\n if len(stones) == 1:\n return stones[0]\n if len(stones) == 0:\n return 0\n stones.sort()\n x = stones.pop()\n y = stones.pop()\n ...
{"fn_name": "lastStoneWeight", "inputs": [[[2,7,4,1,8,1]]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
4,824
class Solution: def lastStoneWeight(self, stones: List[int]) -> int:
946b3ca50a77b35760bbba82591db6c4
UNKNOWN
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle wh...
["class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n former = set()\n while True:\n h = 0\n while n > 0:\n d = n % 10\n h += (d*d)\n n = n // 10\n ...
{"fn_name": "isHappy", "inputs": [[19]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
6,632
class Solution: def isHappy(self, n: int) -> bool:
8b5f287ca0f9a6c0d83f39ccf6dd6dca
UNKNOWN
Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Output: "ZY"
["class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n ans = ''\n a = 0\n \n while n>0:\n if a>0:\n n = n//26\n p = n%26\n if p==0:\n p=26\...
{"fn_name": "convertToTitle", "inputs": [[1]], "outputs": ["A"]}
INTRODUCTORY
PYTHON3
LEETCODE
3,689
class Solution: def convertToTitle(self, n: int) -> str:
f1e7f049e3b8321861ffc728ecf23c6d
UNKNOWN
Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays...
["class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: \n res=0\n for start,end in zip(startTime,endTime):\n if(queryTime>=start and queryTime<=end):\n res+=1\n return res", "class Solution:\n def busyStudent(self,...
{"fn_name": "busyStudent", "inputs": [[[1, 2, 3], [3, 2, 7], 4]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
2,113
class Solution: def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
6db35824b9caf1dec94a7af39a698f2d
UNKNOWN
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "...
["class Solution:\n def backspaceCompare(self, S1, S2):\n i1 = len(S1) - 1 \n i2 = len(S2) - 1\n \n while i1 >= 0 or i2 >= 0:\n c1 = ''\n c2 = ''\n if i1 >= 0:\n c1, i1 = self.getChar(S1, i1)\n if i2 >= 0:\n c2, i2 ...
{"fn_name": "backspaceCompare", "inputs": [["\"ab#c\"", "\"ad#c\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
3,880
class Solution: def backspaceCompare(self, S: str, T: str) -> bool:
0570cdee5a1d622a1df904203db075a4
UNKNOWN
Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, we should return -1. If there are multiple p...
["class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left, right = 0, sum(nums)\n for index, num in enumerate(nums):\n right -= num\n if left == right:\n return index\n ...
{"fn_name": "pivotIndex", "inputs": [[[1, 7, 3, 6, 5, 6]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
4,963
class Solution: def pivotIndex(self, nums: List[int]) -> int:
86574657c7b0bb45c5d249bc30bfcc37
UNKNOWN
Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings.   Example 1: Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", ea...
["class Solution:\n def balancedStringSplit(self, s: str) -> int:\n lCount = rCount = 0\n retVal = 0\n \n for char in s:\n if char == 'R':\n rCount += 1\n else:\n lCount += 1\n \n if rCount == lCount:\n ...
{"fn_name": "balancedStringSplit", "inputs": [["\"RLRRLLRLRL\""]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
1,779
class Solution: def balancedStringSplit(self, s: str) -> int:
eaf8de10932296b592c50aef4b952c89
UNKNOWN
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; oth...
["class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num==0:\n return \"0\"\n res,n=[],0\n nums=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\n while n<8 and num!=0:\n ...
{"fn_name": "toHex", "inputs": [[26]], "outputs": ["1a"]}
INTRODUCTORY
PYTHON3
LEETCODE
5,581
class Solution: def toHex(self, num: int) -> str:
a9f537dc5a1b5132a71239688d8b28ee
UNKNOWN
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solu...
["class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # i = 0\n # i_keep = 0\n # j = 1\n # j_keep = 1\n # max_sum = nums[0]-1\n # while j < len(nums) and i < j:\n # temp_s...
{"fn_name": "maxSubArray", "inputs": [[[-2, 1, -3, 4, -1, 2, 1, -5, 4]]], "outputs": [6]}
INTRODUCTORY
PYTHON3
LEETCODE
8,463
class Solution: def maxSubArray(self, nums: List[int]) -> int:
ee104d1cd677b36f6965600b153f32a4
UNKNOWN
Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false
["class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n < 0:\n return False\n \n hasOne = False\n while n > 0:\n if n & 1:\n if hasOne == True:\n ...
{"fn_name": "isPowerOfTwo", "inputs": [[1]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
3,923
class Solution: def isPowerOfTwo(self, n: int) -> bool:
3e29a49712f5cff0a543257222274036
UNKNOWN
Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701
["class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n r, t = 0, 1\n for i in s:\n r = r*26 +(ord(i)-64)\n #t *= 26\n return r", "class Solution:\n def titleToNumber(self, s):\n \"\"...
{"fn_name": "titleToNumber", "inputs": [["\"A\""]], "outputs": [-20284]}
INTRODUCTORY
PYTHON3
LEETCODE
2,839
class Solution: def titleToNumber(self, s: str) -> int:
66a8c338c8793fdcc9b8fe138a44f43b
UNKNOWN
Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A is a mountain array if and only if: A.length >= 3 There exists some i with 0 < i < A.length - 1 such that: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1]   Example 1: Input: [2,1] ...
["class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n if A[1] < A[0]:\n return False\n is_up = True\n curr = A[0]\n for n in A[1:]:\n if n == curr:\n ...
{"fn_name": "validMountainArray", "inputs": [[[2, 1]]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
27,608
class Solution: def validMountainArray(self, A: List[int]) -> bool:
b4b2feca41cf5ad63feb234c6283114e
UNKNOWN
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number N on the chalkboard.  On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < N and N % x == 0. Replacing the number N on the chalkboard with N - x. Also, if a player cannot make a move,...
["class Solution:\n def divisorGame(self, N: int) -> bool:\n return N%2 == 0\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n m = 0 \n if N > 1: \n for x in range(1, N):\n N -= x \n m += 1 \n if m % 2 == 0:\n re...
{"fn_name": "divisorGame", "inputs": [[2]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
18,957
class Solution: def divisorGame(self, N: int) -> bool:
7d7215518475784292d87f9f249716dd
UNKNOWN
Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.   Example 1: Input: mat = [[1,2,3],   [4,5,6],   [7,8,9]] Output: 25 Expl...
["class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n rows = len(mat)\n columns = len(mat[0])\n sum_ = 0\n for r, c1, c2 in zip(list(range(rows)), list(range(columns)), list(range(columns - 1, -1, -1))):\n sum_ += mat[r][c1]\n if c1 != c2:\n ...
{"fn_name": "diagonalSum", "inputs": [[[[1, 2, 3], [4, 5, 6], [7, 8, 9], [], []]]], "outputs": [25]}
INTRODUCTORY
PYTHON3
LEETCODE
1,560
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int:
9f0c0033fd6920eaa5a2755d60c836d3
UNKNOWN
You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven th...
["# class Solution:\n# def specialArray(self, nums: List[int]) -> int:\n# nums.sort(reverse=True)\n# left, right = 0, len(nums)\n# while left < right:\n# mid = left + (right - left) // 2\n# if mid < nums[mid]:\n# left = mid + 1\n# else:\n# ...
{"fn_name": "specialArray", "inputs": [[[3, 5]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
6,563
class Solution: def specialArray(self, nums: List[int]) -> int:
72e79b85087265e9ec6c12551214edcd
UNKNOWN
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares (" "). The first player A always places "X" characters, while the second player B always places "O" characters. "X" and "O" characters are always placed into empty s...
["class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n # player one and two moves\n player_a, player_b = moves[0::2], moves[1::2]\n\n # possible wins\n possible_wins = {\n 0: [[0, 0], [1, 1], [2, 2]],\n 1: [[0, 0], [1, 0], [2, 0]],\n 2: ...
{"fn_name": "tictactoe", "inputs": [[[[0, 0], [2, 0], [1, 1], [2, 1], [2, 2], [], []]]], "outputs": ["A"]}
INTRODUCTORY
PYTHON3
LEETCODE
1,164
class Solution: def tictactoe(self, moves: List[List[int]]) -> str:
3f572644df29cd8c9669b2508ef1000c
UNKNOWN
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j]   Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is t...
["class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n found = {}\n for num in arr:\n if num * 2 in found:\n return True\n if num % 2 == 0 and num / 2 in found:\n return True\n found[num] = True\n return False", "class...
{"fn_name": "checkIfExist", "inputs": [[[10, 2, 5, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
7,755
class Solution: def checkIfExist(self, arr: List[int]) -> bool:
fa76ff5f0449e8be663e5a1225994f77
UNKNOWN
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to do...
["class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n set1={}\n \n sum1=0\n for i in dominoes:\n\n ri=list(reversed(i))\n i=tuple(i)\n ri=tuple(ri)\n if i in set1.keys():\n sum1+=set1[i]\n ...
{"fn_name": "numEquivDominoPairs", "inputs": [[[[1, 2], [2, 1], [3, 4], [5, 6], [], []]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
10,460
class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
569e15bb5473f621787f05933062fa16
UNKNOWN
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on...
["class Solution:\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n if len(nums) < 3:\n return max(nums)\n dp = [0] * len(nums)\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n \n for i in range(2, len(nums)):\n d...
{"fn_name": "rob", "inputs": [[[1, 2, 3, 1]]], "outputs": [4]}
INTRODUCTORY
PYTHON3
LEETCODE
4,846
class Solution: def rob(self, nums: List[int]) -> int:
200af9b129cd756631b1030472fa38f9
UNKNOWN
You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). ...
["class Solution:\n def checkRecord(self, s):\n count = 0\n for i in range(0,len(s)):\n if s[i] == \"A\":\n count += 1\n if count == 2:\n return False\n elif i >= 2 and s[i] == \"L\" and s[max(i-1,0)] == \"L\" and s[max(i-2,...
{"fn_name": "checkRecord", "inputs": [["\"PPALLP\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
4,155
class Solution: def checkRecord(self, s: str) -> bool:
68954367cccf72091d0e1866e6199d29
UNKNOWN
Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guaranteed that there are no consecutive repeating c...
["class Solution:\n def modifyString(self, s: str) -> str:\n if len(s) == 0:\n return s\n string = ['#']\n string.extend(list(s))\n string.append('#')\n for i in range(1,len(string)-1):\n if string[i] == '?':\n for j in range(97,123):\n ...
{"fn_name": "modifyString", "inputs": [["\"?zs\""]], "outputs": ["\"azs\""]}
INTRODUCTORY
PYTHON3
LEETCODE
3,265
class Solution: def modifyString(self, s: str) -> str:
51f3af001157f26bcebaca0b0b33d429
UNKNOWN
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanat...
["class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n return int(x**0.5)", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x<=1:\n return x\...
{"fn_name": "mySqrt", "inputs": [[4]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
4,335
class Solution: def mySqrt(self, x: int) -> int:
4ed6ffb7e2238f63f94ac0450abf250c
UNKNOWN
We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices. For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions...
["class Solution:\n def minDeletionSize(self, A: List[str]) -> int: \n return sum([list(col) != sorted(col) for col in zip(*A)])\n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int: \n return sum(list(col) != sorted(col) for col in zip(*A))\n ...
{"fn_name": "minDeletionSize", "inputs": [[["\"cba\"", "\"daf\"", "\"ghi\""]]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
18,750
class Solution: def minDeletionSize(self, A: List[str]) -> int:
cb763d343e93c3634c8d6a9cc98204ba
UNKNOWN
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.   Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime?
["class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num == 0:\n return 0\n return 1 + (num - 1) % 9", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtyp...
{"fn_name": "addDigits", "inputs": [[38]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
3,579
class Solution: def addDigits(self, num: int) -> int:
606e6851f9a0e5b3fc969caed6f51d92
UNKNOWN
You are given an array A of strings. A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S. Two strings S and T are special-equivalent if after any number of moves onto S, S == T. For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make ...
["class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(''.join(sorted(s[0::2])) + ''.join(sorted(s[1::2])) for s in A))\n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n signature = set()\n \n # Us...
{"fn_name": "numSpecialEquivGroups", "inputs": [[["\"abcd\"", "\"cdab\"", "\"cbad\"", "\"xyzz\"", "\"zzxy\"", "\"zzyx\""]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
16,264
class Solution: def numSpecialEquivGroups(self, A: List[str]) -> int:
6febd95c83a8c497d2bb3a09508ed9ad
UNKNOWN
Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
["class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n sums=sum([ord(i) for i in s]), sum([ord(i) for i in t])\n return chr(sum([ord(i) for i in t])-sum([ord(i) for i in s])) ", "class Solution:\n...
{"fn_name": "findTheDifference", "inputs": [["\"abcd\"", "\"abcde\""]], "outputs": ["e"]}
INTRODUCTORY
PYTHON3
LEETCODE
3,525
class Solution: def findTheDifference(self, s: str, t: str) -> str:
ea7fb118326766ad53278ea3253b3d93
UNKNOWN
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (do...
["class Solution:\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')", "class Solution:\n def judgeCircle(self, moves):\n \"\"\"\n :type...
{"fn_name": "judgeCircle", "inputs": [["\"UD\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
3,030
class Solution: def judgeCircle(self, moves: str) -> bool:
432a5b1f3b9c31af51cf32a41d94b42d
UNKNOWN
We have n chips, where the position of the ith chip is position[i]. We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to: position[i] + 2 or position[i] - 2 with cost = 0. position[i] + 1 or position[i] - 1 with cost = 1. Return the minimum co...
["class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n d = {}\n a = 0\n b = 0\n for i in position:\n if i not in d:\n d[i]=1\n else:\n d[i]+=1\n for i in d:\n if i%2==0:\n a +=d[i...
{"fn_name": "minCostToMoveChips", "inputs": [[[1, 2, 3]]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
5,033
class Solution: def minCostToMoveChips(self, position: List[int]) -> int:
63719e2ef29af16a0fe467981899d01e
UNKNOWN
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min...
["class Solution:\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n return sum(nums[::2])"]
{"fn_name": "arrayPairSum", "inputs": [[[1, 2, 3, 4]]], "outputs": [4]}
INTRODUCTORY
PYTHON3
LEETCODE
197
class Solution: def arrayPairSum(self, nums: List[int]) -> int:
9a42935c88068cdd0b108ade573bda10
UNKNOWN
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, r...
["class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n p = flowerbed.count(1)\n m = int(len(flowerbed) / 2)\n if p+n <= m+1:\n pos = 0\n while ...
{"fn_name": "canPlaceFlowers", "inputs": [[[1, 0, 0, 0, 1], 1]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
9,737
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
4c22e839ddafa3051a873823635e5feb
UNKNOWN
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.   Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Examp...
["from collections import defaultdict\nclass Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n occurences = defaultdict(int)\n for i in arr:\n occurences[i] += 1\n for i in occurences.values():\n if list(occurences.values()).count(i) > 1:\n r...
{"fn_name": "uniqueOccurrences", "inputs": [[[1, 2, 2, 1, 1, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
4,456
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool:
2ef573beed71ce2d630d909d4e1e3a66
UNKNOWN
For two strings s and t, we say "t divides s" if and only if s = t + ... + t  (t concatenated with itself 1 or more times) Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.   Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB...
["class Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n contender = ''\n for i in str1:\n contender += i\n if str1.count(contender) * len(contender) == len(str1) and str2.count(contender) * len(contender) == len(str2):\n break\n orig = cont...
{"fn_name": "gcdOfStrings", "inputs": [["\"ABCABC\"", "\"ABC\""]], "outputs": [""]}
INTRODUCTORY
PYTHON3
LEETCODE
2,241
class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str:
a8c24a73f871cc5bf8cb2a1b7be7b107
UNKNOWN
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).   Example 1: Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7]. Example 2: Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9]. ...
["class Solution:\n def countOdds(self, low: int, high: int) -> int:\n if low %2 != 0:\n low -=1\n if high %2 != 0:\n high +=1 \n \n return (high-low) // 2", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n return (high-high//2)-(lo...
{"fn_name": "countOdds", "inputs": [[3, 7]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
2,210
class Solution: def countOdds(self, low: int, high: int) -> int:
225c950a658685dadc0a1efafe1e2b8d
UNKNOWN
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.   Example 1: Input: num = 14 Output: 6 Explanation:  Step 1) 14 is even; divide by 2 and obtain 7.  Step 2) 7 is odd; subtract 1 and ob...
["class Solution:\n def numberOfSteps (self, num: int) -> int:\n steps = 0\n while num > 0:\n if num % 2 == 0:\n num /= 2\n else:\n num -= 1\n steps += 1\n return steps\n", "class Solution:\n def numberOfSteps (self, num: int) -> ...
{"fn_name": "numberOfSteps", "inputs": [[14]], "outputs": [6]}
INTRODUCTORY
PYTHON3
LEETCODE
3,147
class Solution: def numberOfSteps (self, num: int) -> int:
e1074bcf1dda4a2defc469a8b570d41f
UNKNOWN
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the...
["class Solution:\n def repeatedSubstringPattern(self, s):\n return s in (s + s)[1:-1]\n", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if not s:\n return False\n \n ss ...
{"fn_name": "repeatedSubstringPattern", "inputs": [["\"abab\""]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
4,877
class Solution: def repeatedSubstringPattern(self, s: str) -> bool:
731d4ed56e848669c69ee98b8fc85f0a
UNKNOWN
Given an array nums of integers, return how many of them contain an even number of digits.   Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits).  345 contains 3 digits (odd number of digits).  2 contains 1 digit (odd number of digits).  6 contains 1 digit (od...
["class Solution:\n \n def findNumbers(self, nums: List[int]) -> int:\n def has_even_digits(number: int):\n if number < 10:\n return False\n elif number < 100:\n return True\n elif number < 1000:\n return False\n elif nu...
{"fn_name": "findNumbers", "inputs": [[[12, 345, 2, 6, 7896]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
3,469
class Solution: def findNumbers(self, nums: List[int]) -> int:
b31be4c9f81c1264a7ae9bfbce2b01fb
UNKNOWN
Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: In...
["class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n n = len(prices)\n if n <=1:\n return 0\n else:\n minprice = prices[0]\n res = 0\n for i in range(1,n):\...
{"fn_name": "maxProfit", "inputs": [[[7, 1, 5, 3, 6, 4]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
6,483
class Solution: def maxProfit(self, prices: List[int]) -> int:
d519ad251a44fea13331394cdd1420e0
UNKNOWN
Given an integer n and an integer start. Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums.   Example 1: Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^" correspo...
["class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n \n if n == 0:\n return 0\n \n i = 1\n res = start\n while i != n:\n res = res ^ (2*i + start)\n i += 1\n return res\n", "class Solution:\n def xorOperation(sel...
{"fn_name": "xorOperation", "inputs": [[5, 0]], "outputs": [8]}
INTRODUCTORY
PYTHON3
LEETCODE
2,099
class Solution: def xorOperation(self, n: int, start: int) -> int:
54b234c99a9c3f655ae6c6eb9abb4aa5
UNKNOWN
Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2...
["class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n if len(A)!=len(B):\n return False\n if len(A)<2:\n return False\n if A==B:\n cnt = Counter(A)\n return bool([v for v in cnt.values() if v>1])\n diffs = []\n for i, a in...
{"fn_name": "buddyStrings", "inputs": [["\"ab\"", "\"ba\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
3,981
class Solution: def buddyStrings(self, A: str, B: str) -> bool:
deb375e8b913187b96a7f101478b7c6b
UNKNOWN
The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). "./" : Remain in the same folder. "x/" : Move to the child folder...
["class Solution:\n def minOperations(self, logs: List[str]) -> int:\n \n t=0\n for i in logs:\n if i=='../':\n t=t-1\n elif i=='./':\n t=t\n else:\n t=t+1\n if t<0:\n t=0\n return t", ...
{"fn_name": "minOperations", "inputs": [[["\"d1/\"", "\"d2/\"", "\"../\"", "\"d21/\"", "\"./\""]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
2,022
class Solution: def minOperations(self, logs: List[str]) -> int:
b0cf74147d6e247524aa4ee9faf9db8f
UNKNOWN
Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any thr...
["class Solution:\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n import heapq\n a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)\n return max(a[0]*a[1]*a[2], a[0]*b[0]*b[1])", "class Solution:\n def maxi...
{"fn_name": "maximumProduct", "inputs": [[[1, 2, 3]]], "outputs": [6]}
INTRODUCTORY
PYTHON3
LEETCODE
7,217
class Solution: def maximumProduct(self, nums: List[int]) -> int:
6914d1d39a601741db3d9a17f5413722
UNKNOWN
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]".   Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"   Constraints: The given address is a valid...
["class Solution:\n def defangIPaddr(self, address: str) -> str:\n return address.replace('.', '[.]')\n", "class Solution:\n def defangIPaddr(self, address: str) -> str:\n stringArr = address.split('.')\n \n return '[.]'.join(stringArr)\n \n \n \n \n", "cla...
{"fn_name": "defangIPaddr", "inputs": [["\"1.1.1.1\""]], "outputs": ["\"1[.]1[.]1[.]1\""]}
INTRODUCTORY
PYTHON3
LEETCODE
802
class Solution: def defangIPaddr(self, address: str) -> str:
39d08188b568d152f8a35cae6c971a2b
UNKNOWN
Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise.   Example 1: Input: target = [1,2,3,4], arr = [2,4,1,3] Output: true Expla...
["class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return sorted(target) == sorted(arr)", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if sorted(target) == sorted(arr):\n return True\n else:\n r...
{"fn_name": "canBeEqual", "inputs": [[[1, 2, 3, 4], [2, 4, 1, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
11,545
class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
12858527e054d2594919132a470e5acb
UNKNOWN
Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.   Example 1: Input: day = 31, mon...
["class Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n diff_year = (year - 1971) % 7 + int((year - 1968)/4)\n print(('year:', (year - 1971), ':', (year - 1971)%7))\n print(('num leaps:', int((year - 1968)/4)))\n print(('diff_year:', diff_year))\n mont...
{"fn_name": "dayOfTheWeek", "inputs": [[31, 8, 2019]], "outputs": ["Saturday"]}
INTRODUCTORY
PYTHON3
LEETCODE
2,215
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
ab2b41f577f714f25dae701eb809f230
UNKNOWN
Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.   Example 1: Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds. Example 2: Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,23] are three conse...
["class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n flag = False\n odd = 0\n i = 0\n while i < len(arr):\n if arr[i] % 2 == 1:\n if not flag:\n flag = True\n odd += 1\n i += 1\n ...
{"fn_name": "threeConsecutiveOdds", "inputs": [[[2, 6, 4, 1]]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
6,482
class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool:
1dc487779e15b39bff7cbf5ac83715fd
UNKNOWN
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted...
["class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n char_map = {char: i for i, char in enumerate(order)}\n for j in range(1, len(words)):\n prev, curr = words[j - 1], words[j]\n\n k = 0\n while k < min(len(prev), len(curr)):\n ...
{"fn_name": "isAlienSorted", "inputs": [[["\"hello\"", "\"leetcode\""], "\"hlabcdefgijkmnopqrstuvwxyz\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
8,339
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool:
20aacdaa9ecc2d0c7be34867c9f7b624
UNKNOWN
In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Each group has exactly X cards. All the cards in each group have the same integer.   Example 1: Input: deck = [1,2,3,4,4...
["class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n def findGCD(a,b):\n if b ==0:\n return a\n return findGCD(b, a%b)\n \n hash_cards = {}\n for card in deck:\n if card in hash_cards:\n hash_cards[card...
{"fn_name": "hasGroupsSizeX", "inputs": [[[1, 2, 3, 4, 4, 3, 2, 1]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
16,926
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool:
bc11a48646fdb5a21b3212be73d093ba
UNKNOWN
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string.   Example 1: Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only. Example 2: Input: s = "abbcccddddeee...
["class Solution:\n def maxPower(self, s: str) -> int:\n n = len(s) \n count = 0\n res = s[0] \n cur_count = 1\n \n # Traverse string except \n # last character \n for i in range(n): \n \n # If current character \n # matches with next...
{"fn_name": "maxPower", "inputs": [["\"leetcode\""]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
7,709
class Solution: def maxPower(self, s: str) -> int:
5c305f373110a49dab8e52278df4de3b
UNKNOWN
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the ...
["class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n for idx in range(0, len(s), 2*k):\n s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:]\n return s", "class Solution:\n def reverseStr(self...
{"fn_name": "reverseStr", "inputs": [["\"abcdefg\"", 2]], "outputs": ["a\"bcedfg\""]}
INTRODUCTORY
PYTHON3
LEETCODE
8,469
class Solution: def reverseStr(self, s: str, k: int) -> str:
a95dba298944ecd5b028eb4057352f18
UNKNOWN
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (...
["class Solution:\n def maxProfit(self, prices):\n profits = 0 \n ln = len(prices)\n if not ln:\n return 0\n elif ln == 2:\n return (prices[1]-prices[0]) if prices[1] > prices[0] else 0\n lastPrice = prices[0]\n for price in prices:\n ...
{"fn_name": "maxProfit", "inputs": [[[7, 1, 5, 3, 6, 4]]], "outputs": [7]}
INTRODUCTORY
PYTHON3
LEETCODE
6,414
class Solution: def maxProfit(self, prices: List[int]) -> int:
4dd7a5b98cab8bcc1ef16b8f3ea57dfe
UNKNOWN
Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings. A subsequence is a sequence that can be...
["class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n return max(len(a),len(b)) if a != b else -1", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :ty...
{"fn_name": "findLUSlength", "inputs": [["\"aba\"", "\"cdc\""]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
4,261
class Solution: def findLUSlength(self, a: str, b: str) -> int:
fd0f19a8cf88cc7bcb7689bbe78acd13
UNKNOWN
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. A subarray is a contiguous subsequence of the array. Return the sum of all odd-length subarrays of arr.   Example 1: Input: arr = [1,4,2,5,3] Output: 58 Explanation: The odd-length subarrays of arr and their sums are: [1] =...
["class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n \n # last = len(arr)\n # total = 0\n # for start in range(len(arr)):\n # end = start\n # while end < last:\n # total += sum(arr[start:end+1])\n # end += 2 '''\n # ...
{"fn_name": "sumOddLengthSubarrays", "inputs": [[[1, 4, 2, 5, 3]]], "outputs": [58]}
INTRODUCTORY
PYTHON3
LEETCODE
15,917
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int:
dbc70e8f31e409aca1f2da9a09506cd9
UNKNOWN
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if...
["class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n return not (rec1[0] >= rec2[2] or rec1[2] <= rec2[0] or rec1[1] >= rec2[3] or rec1[3] <= rec2[1])", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n \n r1x...
{"fn_name": "isRectangleOverlap", "inputs": [[[0, 0, 2, 2], [1, 1, 3, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
3,721
class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
b75066556dbe6cd82e0a2ec69d806aae
UNKNOWN
Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may ...
["class Solution:\n def isIsomorphic(self, s1, s2):\n return len(set(zip(s1, s2))) == len(set(s1)) == len(set(s2))\n", "class Solution:\n def isIsomorphic(self, s1, s2):\n \"\"\" Optimized version.\n Time complexity: O(n). Space complexity: O(1), n is len(s1) == len(s2).\n \"\"\"...
{"fn_name": "isIsomorphic", "inputs": [["\"egg\"", "\"add\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
12,414
class Solution: def isIsomorphic(self, s: str, t: str) -> bool:
7a817b30609fbe2648beeed80a9d9da6
UNKNOWN
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words.   Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The str...
["class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d={}\n for i in chars:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n l=0\n for i in words:\n flag = True\n for j in i:\n ...
{"fn_name": "countCharacters", "inputs": [[["\"cat\"", "\"bt\"", "\"hat\"", "\"tree\""], "\"atach\""]], "outputs": [10]}
INTRODUCTORY
PYTHON3
LEETCODE
62,524
class Solution: def countCharacters(self, words: List[str], chars: str) -> int:
d4b66992640efd857f9c5f9a396a0a32
UNKNOWN
Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Notice that when a group of students is selected they can reorder in any possible way between themselves an...
["class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n max_val = max(heights)\n \n freq = [0] * (max_val + 1)\n for num in heights:\n freq[num] += 1\n for num in range(1,len(freq)):\n freq[num] += freq[num-1]\n places = [0] * len(heig...
{"fn_name": "heightChecker", "inputs": [[[1, 1, 4, 2, 1, 3]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
4,686
class Solution: def heightChecker(self, heights: List[int]) -> int:
7ce8ad7ef228f30695d401fb8b1d29f5
UNKNOWN
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => ...
["class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n minx=min(nums)\n sums=sum(nums)\n return sums-len(nums)*minx\n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: Lis...
{"fn_name": "minMoves", "inputs": [[[1, 2, 3]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
4,178
class Solution: def minMoves(self, nums: List[int]) -> int:
315fecf12797c0d8b174612e14d6b2c6
UNKNOWN
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for...
["class Solution:\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return (n%4 != 0)", "class Solution:\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n % 4 == 0:\n ...
{"fn_name": "canWinNim", "inputs": [[4]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
1,953
class Solution: def canWinNim(self, n: int) -> bool:
a2728d8e2fcf3438dda17d60cc73fb91
UNKNOWN
In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element repeated N times.   Example 1: Input: [1,2,3,3] Output: 3 Example 2: Input: [2,1,2,5,3,2] Output: 2 Example 3: Input: [5,1,5,2,5,3,5,4] Output: 5   Note: 4 <= A.length <= 10000 0 <=...
["class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dict_ = dict()\n \n for a in A:\n if a in dict_:\n return a\n else:\n dict_[a] = 1\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n for i in r...
{"fn_name": "repeatedNTimes", "inputs": [[[1, 2, 3, 3]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
16,592
class Solution: def repeatedNTimes(self, A: List[int]) -> int:
61c8bee0f002bab313a2100ddae316cb
UNKNOWN
Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of ...
["class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n s = [];\n for email in emails:\n for i in range(len(email)):\n if email[i]=='@':\n localname = email[:i];\n domainname = email[i:];\n local = '';...
{"fn_name": "numUniqueEmails", "inputs": [[["\"test.email+alex@leetcode.com\"", "\"test.e.mail+bob.cathy@leetcode.com\"", "\"testemail+david@lee\n.tcode.com\""]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
6,230
class Solution: def numUniqueEmails(self, emails: List[str]) -> int:
c72dfa5afcbce629b094acd48e33942b
UNKNOWN
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Note: n is positive and will fit within the range of a 32-bit signed integer (n < 231). Example 1: Input: 3 Output: 3 Example 2: Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, ...
["class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n i=count=9\n while count < n:\n i *= 10\n count += i * len(str(i))\n div, mod = divmod(n-(count-i*len(str(i))), len(str(i)))\n print(...
{"fn_name": "findNthDigit", "inputs": [[3]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
11,682
class Solution: def findNthDigit(self, n: int) -> int:
0b6f5a5e5f27f4ad01152e0aed8b2669
UNKNOWN
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.   Example 1: Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 Output: 2 Exp...
["class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n flag=0\n for j in arr2:\n if abs(i-j)<=d:\n flag=1\n break\n if flag == 0:\n ...
{"fn_name": "findTheDistanceValue", "inputs": [[[4, 5, 8], [10, 9, 1, 8], 2]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
40,956
class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
ae1264ec534465aaa07930fd4bab6ede
UNKNOWN
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: If a word begins with a vowel (a, e, i, o, or u), append "ma...
["class Solution:\n def toGoatLatin(self, S: str) -> str:\n result = ''\n vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n aAppend = 'a'\n newWord = ''\n maAppend = ''\n lastC = ''\n for c in S:\n lastC = c\n fullAppend = maAppend + a...
{"fn_name": "toGoatLatin", "inputs": [["\"I speak Goat Latin\""]], "outputs": ["I\"maa peaksmaaa oatGmaaaa atin\"Lmaaaaa"]}
INTRODUCTORY
PYTHON3
LEETCODE
2,707
class Solution: def toGoatLatin(self, S: str) -> str:
8324a24aaf5ccb0a93dc8bcc065202cb
UNKNOWN
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true ...
["class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n s=set(nums)\n if len(s)==len(nums):return False\n d=dict()\n for num in nums:\n d[num]=d.get(n...
{"fn_name": "containsNearbyDuplicate", "inputs": [[[1, 2, 3, 1], 3]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
7,272
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
ace4d72e2d14d0263f188c73dc8edc38
UNKNOWN
The Tribonacci sequence Tn is defined as follows:  T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn.   Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n = 25 Output: 1389537   Constraints: 0 <= n <= 37 The answer ...
["class Solution:\n def tribonacci(self, n: int) -> int:\n if n == 0:\n return 0\n if n == 1:\n return 1\n ans = [0] * (n+1)\n ans[0] = 0 \n ans[1] = 1 \n ans[2] = 1 \n \n for i in range(3, n+1):\n ans[i] = ans[i-1] + ans[i-2] +...
{"fn_name": "tribonacci", "inputs": [[4]], "outputs": [4]}
INTRODUCTORY
PYTHON3
LEETCODE
3,474
class Solution: def tribonacci(self, n: int) -> int:
71b8c4c081e9e03d3aa6867f87978f4f
UNKNOWN
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] holds for every i (1 Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Exa...
["class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n possibility_flag = False\n for i in range(1, len(nums)):\n if nums[i] < nums[i-1]:\n if possibility_flag:\n ...
{"fn_name": "checkPossibility", "inputs": [[[4, 2, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
7,817
class Solution: def checkPossibility(self, nums: List[int]) -> bool:
5de98844f97a94b498ec2cb7864041ea
UNKNOWN
Given a sentence that consists of some words separated by a single space, and a searchWord. You have to check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence where searchWord is a prefix of this word (1-indexed). If searchWord is a prefix of more than one word, return the ind...
["class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n for i, w in enumerate(sentence.split(), 1):\n if w.startswith(searchWord):\n return i\n return -1\n", "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n...
{"fn_name": "isPrefixOfWord", "inputs": [["\"i love eating burger\"", "\"burg\""]], "outputs": [-1]}
INTRODUCTORY
PYTHON3
LEETCODE
1,859
class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
46294807c8f67f9664279c1cc924538c
UNKNOWN
Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For t...
["class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x < 0:\n y = -1 * int(str(-x)[::-1])\n else:\n y = int(str(x)[::-1]) \n \n if y > 2**31 or y < -2**31:\n y = 0\n ...
{"fn_name": "reverse", "inputs": [[123]], "outputs": [321]}
INTRODUCTORY
PYTHON3
LEETCODE
7,497
class Solution: def reverse(self, x: int) -> int:
5caf06df2c26f34dd29fee03a6a8c377
UNKNOWN
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the refo...
["class Solution:\n def reformat(self, s: str) -> str:\n n = [str(i) for i in range(0, 10)]\n a, b = [], []\n for i in s:\n if i in n:\n b.append(i)\n else:\n a.append(i)\n if abs(len(a) - len(b)) > 1:\n return ''\n r =...
{"fn_name": "reformat", "inputs": [["\"a0b1c2\""]], "outputs": [""]}
INTRODUCTORY
PYTHON3
LEETCODE
2,065
class Solution: def reformat(self, s: str) -> str:
ec3eb940d6f78a2b3b745bb82b2c4217
UNKNOWN
The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the c...
["class Solution:\n def countAndSay(self, n):\n s = '1'\n \n for _ in range(n-1):\n let, temp, count = s[0], \"\", 0\n for l in s:\n if let == l:\n count += 1\n else:\n temp += str(count) + let\n ...
{"fn_name": "countAndSay", "inputs": [[1]], "outputs": ["1"]}
INTRODUCTORY
PYTHON3
LEETCODE
8,782
class Solution: def countAndSay(self, n: int) -> str: