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)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3 | ["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] > largest:\n second_largest = largest\n largest = nums[i]\n elif nums[i] > second_largest:\n second_largest = nums[i]\n return (largest-1) * (second_largest -1)\n \n \n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_1 = max(nums)\n nums.remove(max_1)\n max_2 = max(nums)\n return (max_2-1)*(max_1-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n i=nums[0];j=nums[1]\n for num in range(2,len(nums)):\n if(nums[num]>i or nums[num]>j):\n if(nums[num]>i):\n if(i>j):\n j=i \n i=nums[num]\n #print(i)\n else:\n if(j>i):\n i=j \n j=nums[num]\n #print(j)\n #print (i,\\\" \\\",j)\n return (i-1)*(j-1)\n \n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prods=[]\n for i in range(0,len(nums)-1):\n for j in range(i+1, len(nums)):\n prods.append((nums[i]-1)*(nums[j]-1))\n return max(prods)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maximum_value=[]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n maximum_value.append((nums[i]-1)*(nums[j]-1))\n return max(maximum_value)", "from itertools import combinations\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n comb=list(combinations(nums,2))\n maxv=0\n for x in comb :\n if (x[0]-1)*(x[1]-1)>maxv :\n maxv=(x[0]-1)*(x[1]-1)\n return maxv\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n sum = 0\n for i, num in enumerate(nums):\n j = i + 1\n while j < len(nums):\n tempSum = (nums[i]-1)*(nums[j]-1)\n if sum < tempSum:\n sum = tempSum\n j = j + 1\n return sum\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n products = []\n \n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n products.append((nums[i] - 1) * (nums[j] -1)) \n \n return max(products)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n n = []\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n n.append((nums[i]-1)*(nums[j]-1))\n return max(n)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maximum = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n product = (nums[i]-1)*(nums[j]-1)\n if maximum < product:\n maximum = product\n return maximum", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n l=[]\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n s=(nums[i]-1)*(nums[j]-1)\n l.append(s)\n return max(l)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n k=[]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n l=(nums[i]-1)*(nums[j]-1)\n k.append(l)\n return max(k)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_pro=0\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n temp=(nums[i]-1)*(nums[j]-1)\n if temp>max_pro:\n max_pro=temp\n return(max_pro)\n \n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n k=[]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n \n #print((nums[i]-1),(nums[j]-1))\n k.append((nums[i]-1)*(nums[j]-1))\n \n print((max(k)))\n return(max(k))\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n new = []\n \n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n new.append(((nums[i] - 1)*(nums[j] - 1)))\n \n return max(new)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n lst = []\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n x = (nums[i]-1)*(nums[j]-1)\n lst.append(x)\n return max(lst)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if nums == []:\n return None\n max = None\n for idx, i in enumerate(nums):\n j = idx + 1\n while j < len(nums):\n product = (i - 1) * (nums[j] - 1)\n if max == None:\n max = product\n elif product > max:\n max = product\n j += 1\n return max\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n mp = float('-inf')\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n mp = max(mp, (nums[i]-1)*(nums[j]-1))\n return mp", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n ans = max(ans,(nums[i]-1)*(nums[j]-1))\n return ans", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_product = 0\n for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n max_product = max(max_product, (nums[i] - 1) * (nums[j] - 1))\n\n return max_product", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans = float('-inf')\n for i in range(0, len(nums)):\n for j in range(i+1, len(nums)):\n ans = max(ans, (nums[i]-1)*(nums[j]-1))\n \n return ans\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans = float('-inf')\n n = len(nums)\n for i in range(n):\n for j in range(i + 1, n):\n ans = max((nums[i] - 1) * (nums[j] - 1), ans)\n return ans", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n arr = sorted(nums)\n \n idx1 = nums.index(arr[-1])\n idx2 = nums.index(arr[-2])\n \n return (nums[idx1]-1)*(nums[idx2]-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n result = 0\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n # prod = (nums[i]-1) * (nums[j]-1)\n # if prod > result:\n # result = prod\n result = max(result, (nums[i]-1) * (nums[j]-1))\n return result\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n sol = 0\n \n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n sol = max(sol, (nums[i]-1)*(nums[j]-1))\n \n return sol", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n m = max(m, (nums[i] - 1) * (nums[j] - 1))\n return m", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_val = sys.maxsize * -1\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n max_val = max(max_val, (nums[i] - 1) * (nums[j] - 1))\n return max_val", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n #m = (nums[0]-1)*(nums[1]-1)\n m=0\n for i in range(0,len(nums)-1):\n for j in range(i+1,len(nums)):\n m = max(m, (nums[i]-1)*(nums[j]-1))\n return m\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n r=0\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n r=max(r,(nums[i]-1)*(nums[j]-1))\n return r", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n max_val = float('-inf') \n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n max_val = max(max_val,((nums[i]-1) * (nums[j]-1)))\n return max_val\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxNum = 0\n for i in range(len(nums)):\n for j in range(len(nums)):\n if (nums[i]-1)*(nums[j]-1) >= maxNum and i != j:\n maxNum = (nums[i]-1)*(nums[j]-1)\n return maxNum\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n swapped = True\n while swapped:\n swapped = False\n for i in range(len(nums)-1):\n if nums[i+1]>nums[i]:\n nums[i],nums[i+1]=nums[i+1],nums[i]\n swapped = True\n return (nums[0]-1)*(nums[1]-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_prod = 0\n for i in range(0, len(nums)-1):\n for j in range(i+1, len(nums)):\n prod=((nums[i]-1)*(nums[j]-1))\n max_prod = max(max_prod, prod)\n return max_prod", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n res = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if i !=j:\n res = max(res, (nums[i]-1) * (nums[j]-1))\n return res", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n req = 0\n for i in range(1,len(nums)):\n for j in range(i):\n req = max(req, (nums[i]-1)*(nums[j]-1))\n return req\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n n=len(nums)\n ans=float('-inf')\n for i in range(n-1):\n for j in range(i+1,n):\n ans=max((nums[i]-1)*(nums[j]-1),ans)\n return ans\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n b = 0\n for i in range(len(nums)):\n for j in range(len(nums)):\n a = (nums[i] - 1)*(nums[j]-1)\n if b<a and i!=j:\n b=a\n return(b)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max=0\n for x in range(len(nums)):\n for y in range(len(nums)):\n if(y>x):\n if((nums[x]-1)*(nums[y]-1)>max):\n max=(nums[x]-1)*(nums[y]-1)\n return max", "\nfrom itertools import combinations\n\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n\n combs = list(combinations(nums, 2))\n return max(list([(x[0]-1)*(x[1]-1) for x in combs]))\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n for i,v in enumerate(nums):\n nums[i]=nums[i]-1\n nums[i]=abs(nums[i])\n nums.sort(reverse=True)\n return (nums[0])*(nums[1])", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n first, second = 0, 0\n \n for number in nums:\n\n if number > first:\n # update first largest and second largest\n first, second = number, first\n\n else:\n # update second largest\n second = max( number, second)\n\n return (first - 1) * (second - 1)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max1 = nums.pop(nums.index(max(nums)))\n max2 = nums.pop(nums.index(max(nums)))\n return ((max1-1)*(max2-1))", "class Solution:\n def maxProduct(self, nums):\n result = 0\n altnums = []\n for num in nums:\n altnums.append(num)\n for i in range(len(nums)):\n if nums[i] == max(nums):\n altnums[i] = 0\n break\n print(altnums, nums)\n result = (max(nums)-1) * (max(altnums)-1)\n return result", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n s = sorted(nums, reverse = True)\n return (s[0]-1)*(s[1]-1)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n min_val = None\n max_val = None\n \n for i, val in enumerate(nums):\n if min_val is None or min_val[1] > val:\n min_val = [i, val]\n if max_val is None or max_val[1] < val:\n max_val = [i, val]\n \n answer = 0\n for i, val in enumerate(nums):\n if i != min_val[0]:\n answer = max(answer, (min_val[1]-1)*(val-1))\n if i != max_val[0]:\n answer = max(answer, (max_val[1]-1)*(val-1))\n return answer", "from itertools import combinations\nimport numpy\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n res = (nums[-1]-1)*(nums[-2]-1)\n return res\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n Max = max(nums)\n nums.remove(Max)\n return (Max-1)*(max(nums)-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n highest = max(nums)\n nums.pop(nums.index(max(nums)))\n second_highest = max(nums)\n \n return((highest-1)*(second_highest-1))", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[- 1] - 1) * (nums[- 2] - 1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n heap = []\n \n for num in nums:\n heapq.heappush(heap,-num)\n \n m1 = heapq.heappop(heap)\n m2 = heapq.heappop(heap)\n \n return -(m1+1) * -(m2+1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n a = max(nums)\n nums.remove(a)\n return (a-1)*(max(nums)-1)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if len([i for i, x in enumerate(nums) if x == max(nums)])>1:\n return (max(nums)-1)**2\n else:\n maxi = max(nums)\n other = nums\n nums.remove(maxi)\n return (maxi-1) * (max(other)-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n print(sorted(nums)[-1]-1*sorted(nums)[-2]-1)\n if len([i for i, x in enumerate(nums) if x == max(nums)])>1:\n return (max(nums)-1)**2\n else:\n maxi = max(nums)\n other = nums\n nums.remove(maxi)\n return (maxi-1) * (max(other)-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_nums=[]\n\n for num in nums:\n if num==max(nums):\n\n max_nums.append(num-1)\n nums.remove(num)\n for num in nums:\n if num == max(nums):\n max_nums.append(num - 1)\n nums.remove(num)\n return max_nums[0]*max_nums[1]\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n s = set([])\n m = 0\n for num in nums:\n x = num-1\n for y in s:\n p = x*y\n if m<p:\n m = p\n s.add(x)\n return m\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums = sorted(nums)\n l = len(nums)\n return (nums[l-1]-1)*(nums[l-2]-1) \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n largeNumber = 0\n secondNumber = 0\n \n for i in nums:\n if i > largeNumber:\n largeNumber = i \n for j in nums:\n if j > secondNumber and j != largeNumber:\n secondNumber = j\n \n for x in range(0, len(nums)):\n for y in range(x+1, len(nums)):\n if nums[x] == nums[y] and nums[x] == largeNumber:\n secondNumber = largeNumber\n \n return int((largeNumber - 1) * (secondNumber - 1))\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_nums = []\n for i in range(2):\n for num in nums:\n if num == max(nums):\n max_nums.append(num - 1)\n nums.remove(num)\n return max_nums[0] * max_nums[1]\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n k = nums[0]\n n = [i for i in range(2)]\n for i in range(len(nums)):\n for j in range(i):\n if nums[i]*nums[j]>k:\n n[0] = nums[j]\n n[1] = nums[i]\n k = nums[i]*nums[j]\n m = ((n[0]-1)*(n[1]-1))\n return m", "import itertools\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return max(x*y for x, y in itertools.combinations(map(lambda x: x-1, nums), 2))", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n candidates = [0, 0]\n highest = nums[0]\n \n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n product = nums[i] * nums[j]\n if product > highest:\n highest = product\n candidates[0] = i\n candidates[1] = j\n \n return (nums[candidates[0]] - 1) * (nums[candidates[1]] - 1)\n \n # i = 1\n # j = 3\n # product = 25\n # highest = 25\n # candidates = [1, 3]\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_prod = 0\n \n nums = [x-1 for x in nums]\n for first in range(len(nums)-1):\n for second in range(first+1, len(nums)):\n prod = nums[first] * nums[second]\n if prod > max_prod:\n max_prod = prod\n \n return max_prod\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n sorted_nums= sorted(nums)\n return (sorted_nums[-1]-1) * (sorted_nums[-2]-1)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n ix = 0\n iy = 0\n ma = 0\n \n for i in range(0,len(nums)):\n for j in range(i+1,len(nums)):\n if (nums[i]*nums[j]) > ma:\n ma = nums[i]*nums[j]\n ix = i\n iy = j\n \n result = (nums[ix]-1)*(nums[iy]-1)\n \n return result", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n second_largest = 0\n largest = 0\n max_product = 0\n for index1 in range(len(nums)-1):\n for index2 in range(index1+1, len(nums)):\n product = nums[index1] * nums[index2]\n if product > max_product:\n max_product = product\n if nums[index1] > nums[index2]:\n largest, second_largest = nums[index1], nums[index2]\n else:\n largest, second_largest = nums[index2], nums[index1]\n return ((largest-1) * (second_largest-1))\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n from itertools import combinations\n answer = None\n max_value = float('-inf')\n for x,y in combinations(list(range(len(nums))), 2):\n if (nums[x] * nums[y]) > max_value:\n answer = (nums[x]-1)*(nums[y]-1)\n max_value= nums[x] * nums[y]\n return answer\n \n", "from itertools import combinations\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n currentMaximum = 0\n for num_i, num_j in combinations(nums, 2):\n if (product := (num_i - 1)*(num_j - 1)) > currentMaximum:\n currentMaximum = product\n \n # for i, num_i in enumerate(nums):\n # for j, num_j in enumerate(nums):\n # if (currentProduct := (num_i - 1)*(num_j - 1)) > currentMaximum:\n # print(num_i, num_j)\n # currentMaximum = currentProduct\n return currentMaximum ", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n return (sorted(nums)[-1]-1) * (sorted(nums)[-2]-1)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxi = 0\n \n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if ((nums[i]-1) * (nums[j]-1)) > maxi:\n maxi = ((nums[i]-1) * (nums[j]-1))\n \n return maxi\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxx=0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if(((nums[i]-1)*(nums[j]-1))>maxx):\n maxx=(nums[i]-1)*(nums[j]-1)\n return maxx", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max = 0;\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if max < (nums[i]-1)*(nums[j]-1):\n max = (nums[i]-1)*(nums[j]-1)\n return max\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_product=0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if (nums[i]-1)*(nums[j]-1) > max_product:\n max_product = (nums[i]-1)*(nums[j]-1)\n return max_product\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n res = (nums[0]-1)*(nums[1]-1)\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n if res < (nums[i]-1)*(nums[j]-1):\n res = (nums[i]-1)*(nums[j]-1)\n return res\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxim = 0\n for i in range(len(nums)): \n for j in range(i + 1, len(nums)): \n if (nums[i]-1)*(nums[j]-1) > maxim: \n print(i)\n print(j)\n maxim = (nums[i]-1)*(nums[j]-1)\n \n return maxim", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n high = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if (nums[i]-1)*(nums[j]-1) > high:\n high = (nums[i]-1)*(nums[j]-1)\n return high \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n n = len(nums)\n current_max = -2147483647\n for i in range(n-1):\n for j in range(i+1, n):\n temp = (nums[i]-1)*(nums[j]-1)\n if(temp > current_max):\n current_max = temp\n return current_max", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxNum = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n temp = (nums[i]-1)*(nums[j]-1)\n if temp > maxNum:\n maxNum = temp\n return maxNum", "#optimal, one-pass, without sorting\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if nums[0] > nums[1]:\n max1 = nums[0]\n max2 = nums[1]\n else:\n max1 = nums[1]\n max2 = nums[0]\n \n for i in range(2, len(nums)):\n if nums[i] > max1:\n max2 = max1\n max1 = nums[i]\n elif nums[i] > max2:\n max2 = nums[i]\n \n return (max1 - 1)*(max2 - 1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max = 0\n for i in range(0 , len(nums)-1):\n for j in range(i+1 , len(nums)):\n product = (nums[i]-1) * (nums[j]-1)\n if product > max:\n max = product\n return max\n \n # 0 1 2 3 4 5 len=6 \n # 2 3 5 6 8 9\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n result = 0\n for n in range(len(nums)-1):\n for m in range(n+1, len(nums)):\n product = (nums[n] - 1) * (nums[m] -1)\n if product > result:\n result = product\n return result", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n highest = (nums[0]-1) * (nums[1]-1)\n c = 0\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n c = (nums[i] - 1) * (nums[j] -1)\n if c >= highest:\n highest = c\n \n return highest\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxRes = float('-inf')\n for x in range(len(nums)):\n for y in range(x + 1, len(nums)):\n output = (nums[x] - 1) * (nums[y] - 1)\n if output > maxRes:\n maxRes = output\n return maxRes\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans=0\n for i in range(0,len(nums)):\n for j in range(i+1,len(nums)):\n if ans<(nums[i]-1)*(nums[j]-1):\n ans=(nums[i]-1)*(nums[j]-1)\n return ans\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prod = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if (nums[i]-1) * (nums[j]-1) > prod:\n prod = (nums[i]-1) * (nums[j]-1)\n return prod", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n n = len(nums)\n \n max_product = (nums[0] - 1) * (nums[1] - 1)\n \n for i in range(n-1):\n for j in range(i+1, n):\n product = (nums[i] - 1) * (nums[j] - 1)\n if(product > max_product):\n max_product = product\n \n return max_product ", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n my_list = []\n for index, num in enumerate(nums):\n for n in nums[index+1:]:\n my_list.append((num-1)*(n-1))\n return max(my_list)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prod = 0\n for index in range(len(nums) - 1):\n for subindex in range(index + 1, len(nums)):\n cache = (nums[index] - 1) * (nums[subindex] - 1)\n if cache > prod:\n prod = cache\n return prod\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return max([(nums[i] - 1) * (nums[j] - 1) \n for i in range(len(nums))\n for j in range(i + 1, len(nums))\n ])", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if nums[0] > nums[1]:\n max1 = nums[0]\n max2 = nums[1]\n else:\n max1 = nums[1]\n max2 = nums[0]\n \n for i in range(2, len(nums)):\n if nums[i] > max1:\n max2 = max1\n max1 = nums[i]\n elif nums[i] > max2:\n max2 = nums[i]\n \n return (max1 - 1)*(max2 - 1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_sum = 0\n n = len(nums)\n \n for i in range(n):\n for j in range(i+1, n):\n sum = (nums[i] - 1) * (nums[j] - 1)\n if sum > max_sum:\n max_sum = sum\n return max_sum\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return max((nums[i]-1)*(nums[j]-1) for i in range(len(nums)-1) for j in range(i+1, len(nums)))", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n d = len(nums)\n m = None\n \n for i in range(d):\n for j in range(i+1, d):\n mn = (nums[i] - 1) * (nums[j] - 1)\n if m is None:\n m = mn\n elif m < mn:\n m = mn\n return m\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n n = len(nums)\n ans = 0\n \n for i in range(n-1):\n for j in range(i+1,n):\n \n temp = (nums[i] -1) * (nums[j] -1)\n \n if temp > ans:\n ans = temp\n \n return ans", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n list1 = [((nums[i]-1)*(nums[j]-1)) for i in range(len(nums)) for j in range(i+1,len(nums))]\n return max(list1)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return max((nums[i]-1)*(nums[j]-1) for i in range(len(nums)) for j in range(i+1, len(nums)))", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n for i in range(len(nums)): \n for j in range(0, len(nums)-i-1): \n if nums[j] > nums[j+1] : \n nums[j], nums[j+1] = nums[j+1], nums[j] \n \n a = nums.pop(len(nums)-1)-1\n b = nums.pop(len(nums)-1)-1 \n return a*b", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n curr_product = 0\n max_product = 0\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n if i == 0 and j == 0:\n max_product = (nums[i]-1)*(nums[j]-1)\n else:\n curr_product = (nums[i]-1)*(nums[j]-1)\n if curr_product > max_product:\n max_product = curr_product\n \n return max_product", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n max_val = 0\n curr_val = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if i == 0 and j == 0:\n max_val = (nums[i]-1) * (nums[j]-1)\n else:\n curr_val = (nums[i]-1) * (nums[j]-1)\n if curr_val > max_val:\n max_val = curr_val\n \n return max_val", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n \n return (nums[-1]-1)*(nums[-2]-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxValue = 0\n max_return = 0\n for nr_idx in range(len(nums)):\n for nr_id in range(nr_idx + 1, len(nums)):\n if nr_id != nr_idx:\n max_Value = (nums[nr_idx] - 1) * (nums[nr_id] - 1)\n if max_Value > max_return:\n max_return = max_Value\n return max_return", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max= 0\n \n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n curr = (nums[i] - 1) * (nums[j] -1)\n if curr > max:\n max = curr\n \n return max", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maxx=float('-inf')\n for i in range(0,len(nums)-1):\n for j in range(i+1,len(nums)):\n if maxx<(nums[i]-1)*(nums[j]-1):\n maxx=(nums[i]-1)*(nums[j]-1)\n return maxx\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n result = 0\n for i in range(len(nums)):\n for k in range(i+1,len(nums)):\n if(nums[i]-1)*(nums[k]-1) > result:\n result = (nums[i]-1) * (nums[k]-1)\n return result", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n maximum = (nums[0] - 1)*(nums[1] - 1)\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if (nums[i] - 1)*(nums[j] - 1) > maximum:\n maximum = (nums[i] - 1)*(nums[j] - 1)\n return maximum\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if len(set(nums))==1 and set(nums)=={1}:\n return 0\n maxi=1\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n if (nums[i]-1)*(nums[j]-1)>maxi:\n maxi=(nums[i]-1)*(nums[j]-1)\n return maxi", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n result = [] # variabel untuk menampung hasil perhitungan rumus\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n result.append((nums[i]-1)*(nums[j]-1))\n return max(result) # mengambil nilai maximum dari rumus\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n product_list = []\n \n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n product_list.append((nums[i]-1)*(nums[j]-1))\n return max(product_list)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n mpr = []\n \n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n mpr.append((nums[i]-1)*(nums[j]-1))\n return max(mpr)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n p = []\n for count, n in enumerate(nums):\n for i in range(count+1,len(nums)):\n p.append((nums[i] -1)* (n-1))\n return max(p)", "class Solution:\n def maxProduct(self, L: List[int]) -> int:\n max=0\n x=0\n y=0\n for i in range(len(L)):\n for j in range(len(L)):\n if L[i]*L[j]>max and i!=j:\n max=L[i]*L[j]\n x,y=i,j\n return (L[x]-1)*(L[y]-1)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n max_product = 0\n num_len = len(nums)\n for i in range(num_len):\n for j in range(i, num_len):\n product = (nums[i] - 1) * (nums[j] - 1)\n if i != j and product > max_product:\n max_product = product\n return max_product", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n res=0\n for i in range(len(nums)-1):\n for j in range(i+1,len(nums)):\n if (nums[i]-1)*(nums[j]-1)>res:\n res=(nums[i]-1)*(nums[j]-1)\n return res\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n mularray = []\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n mularray.append((nums[i]-1)*(nums[j]-1))\n return max(mularray)\n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n products = []\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n products.append((nums[i]-1)*(nums[j]-1))\n return max(products)", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n l=[]\n for i in range(0,len(nums)):\n for j in range(i+1,len(nums)):\n l.append((nums[i]-1)*(nums[j]-1))\n return max(l)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if not nums: return 0\n max_val=i_value=y_value = 0\n for i_idx, i_val in enumerate(nums):\n for y_idx, y_val in enumerate(nums):\n if i_idx == y_idx:\n continue\n if i_val * y_val > max_val : \n max_val = i_val * y_val\n i_value,y_value=i_val,y_val\n return (i_value-1)*(y_value-1)\n \n", "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n n=[i-1 for i in nums]\n res=0\n for i,j in itertools.combinations(n, 2):\n res=max(res,i*j)\n return res\n", "from itertools import combinations\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \n arr = combinations(nums, 2)\n res = []\n \n for x in arr:\n res.append((x[0] - 1) * (x[1] - 1))\n \n return max(res)"] | {"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: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1 | (5 -3 ) = 2 | -3
(1 +2 ) = 3 | (2 +2 ) = 4 | 2
(3 -3 ) = 0 | (4 -3 ) = 1 | -3
(0 +4 ) = 4 | (1 +4 ) = 5 | 4
(4 +2 ) = 6 | (5 +2 ) = 7 | 2
Example 2:
Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive.
Example 3:
Input: nums = [1,-2,-3]
Output: 5
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100 | ["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 minVal=1\n t=0\n for num in nums:\n t+=num\n if(t<0):\n minVal=max(1-t,minVal)\n return minVal\n \n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n pSum = 0\n minSum = 0;\n for num in nums:\n pSum += num\n minSum = min(pSum, minSum)\n return 1 - minSum", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n num=1; i=0;sum = num; #flag=False;\n while i<len(nums):\n sum+=nums[i] \n if sum<1:\n flag = False\n i=0;num+=1;sum=num; #flag=True\n \n else:\n i+=1\n \n #if i<len(nums) and flag==False:\n #i=0;num+=1;sum=num;flag=True\n \n return num\n \n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n num=1; i=0;sum = num; #flag=False;\n while i<len(nums):\n sum+=nums[i] \n if sum<1:\n flag = False\n i=0;num+=1;sum=num; #flag=True\n \n else:\n i+=1 \n return num\n \n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n n = len(nums)\n \n startValue = 1\n \n while startValue < float('inf'):\n get = True\n tmp = startValue\n for i in range(n):\n if nums[i] + tmp < 1:\n get = False\n break\n tmp = nums[i] + tmp\n if not get: \n startValue += 1\n else:\n return startValue", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n \n init = 1\n \n \n while init > 0:\n temp = init\n for i in nums:\n temp = temp + i\n if temp <= 0:\n break\n else:\n return init\n \n \n init += 1", "class Solution:\n \n def minStartValue(self, nums: List[int]) -> int:\n start =1\n s=1\n for n in nums:\n s+=n\n if s<1:\n start+=1-s\n s=1\n return start", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n pref=[0]*len(nums)\n pref[0]=nums[0]\n for i in range(1,len(nums)):\n pref[i]=pref[i-1]+nums[i]\n \n return max(1, 1-min(pref))", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n \n running_min = nums[0]\n reduction = 0\n for i in nums:\n reduction += i\n running_min = min(running_min, reduction)\n \n return 1 if running_min >= 1 else 1 - running_min", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n # return -min(0, min(accu for accu in itertools.accumulate(nums))) + 1\n return 1 - min(accumulate(nums, initial=0))", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n min_sum = 0\n temp = 0\n for num in nums:\n temp += num\n min_sum = min(temp, min_sum)\n \n return abs(min_sum)+1\n\n\n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n for i in range(1,1000000):\n flag = 0\n n=i\n for j in nums:\n n+=j\n if n < 1:\n flag=1\n break\n if flag==0:\n return i\n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n for i in range(1,1000001):\n flag=0\n sum=i;\n for j in nums:\n sum+=j\n if sum<1:\n flag=1\n break\n if flag==0:\n return i\n", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n res = 0\n cur = 0\n for num in nums:\n cur += num\n if cur < 1:\n res += 1 - cur\n cur += 1 - cur\n if res == 0:\n return 1\n return res\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 inputs to integer directly. | ["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 in range(l):\n s = ord(num2[l - i - 1]) + ord(num1[len(num1) - i - 1]) - 2 * ord(\"0\") + addon\n addon = s // 10\n res = chr(s % 10 + ord(\"0\")) + res\n for i in range(l, len(num1)):\n s = ord(num1[len(num1) - i - 1]) - ord(\"0\") + addon \n addon = s // 10\n res = chr(s % 10 + ord(\"0\")) + res\n if addon > 0:\n res = \"1\" + res\n return res\n \n", "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 in range(l):\n s = ord(num2[l - i - 1]) + ord(num1[len(num1) - i - 1]) - 2 * ord(\"0\") + addon\n addon = s // 10\n res = chr(s % 10 + ord(\"0\")) + res\n for i in range(l, len(num1)):\n s = ord(num1[len(num1) - i - 1]) - ord(\"0\") + addon \n addon = s // 10\n res = chr(s % 10 + ord(\"0\")) + res\n if addon > 0:\n res = \"1\" + res\n return res\n \n"] | {"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 finished = True\n for c in s:\n if finished:\n if c is \" \": continue\n else:\n finished = False\n count += 1\n else:\n if c is \" \":\n finished = True\n else:\n continue\n return count\n", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return len(s.split())\n", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count = 0\n finished = True\n for c in s:\n if finished:\n if c is \" \": continue\n else:\n finished = False\n count += 1\n else:\n if c is \" \":\n finished = True\n else:\n continue\n return count\n", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return len(s.split())\n # lmao is me\n", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n '''\n counter = 0\n wasspace = 1\n for char in s:\n if char == \" \":\n wasspace = 1\n continue\n if wasspace == 1:\n counter += 1\n wasspace = 0\n return counter\n '''\n return len(s.split())", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n c=0\n l=s.split(\" \")\n for i in l:\n if i!=\"\":\n c+=1\n return c", "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 if len(s)==0:\n return 0\n seen_character = False\n count = 0\n for char in s:\n if seen_character and char == ' ':\n count += 1\n seen_character = False\n elif seen_character == False and char != \" \":\n seen_character = True\n if seen_character:\n count += 1\n return count\n", "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 mylist = s.split()\n return len(mylist)"] | {"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]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000 | ["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[int], K: int) -> int:\n if (min(A)+abs(K)) > (max(A)-abs(K)):\n return 0\n else:\n return (max(A)-abs(K))-(min(A)+abs(K))", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(max(A)-min(A)-2*K, 0)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n small,large = 10001,-1\n for x in A:\n small,large = min(x,small),max(x,large)\n return max(large - small - 2*K,0)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n Max = max(A)\n Min = min(A)\n res = (Max - K) - (Min + K)\n if res < 0:\n return 0\n return res", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max((max(A)-K) - (min(A)+K), 0)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(max(A) - min(A) - 2*K, 0)\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n min_val = max_val = A[0]\n \n for a in A:\n if a < min_val: min_val = a\n elif a > max_val: max_val = a\n # min_val = min(min_val, a)\n # max_val = max(max_val, a)\n \n return max(max_val - min_val - 2 * K, 0) \n \n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n avg = round((min(A) + max(A)) / 2)\n mn, mx = float('Inf'), float('-Inf')\n for n in A:\n d = min(K, abs(avg-n))\n n += d * (-1 if n > avg else 1)\n mn, mx = min(mn, n), max(mx, n)\n\n return mx - mn\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n A.sort()\n return A[-1] - A[0] - 2 * K if A[-1] - A[0] > 2 * K else 0", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n a, b = max(A), min(A)\n diff = a - b\n coverage = 2 * K\n if diff <= coverage:\n return 0\n else:\n return diff - coverage\n \n \n \n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n mx, mn = max(A), min(A)\n\n return max(mx - mn - 2 * K, 0)\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(0, max(A)-min(A)-2*K)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n v_min, v_max = min(A), max(A)\n if v_max - v_min >= 2*K:\n return v_max - v_min - 2*K\n else:\n return 0", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n M, m = max(A), min(A)\n if M-m <= 2*K:\n return 0\n else:\n return (M-K)-(m+K)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n if (max(A)-min(A)) > K*2:\n return max(A)-min(A) - K*2\n else:\n return 0", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n max_value = max(A) - K\n min_value = min(A) + K\n if max_value > min_value:\n return max_value - min_value\n else:\n return 0", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n min_element, max_element = min(A), max(A)\n return max(0, max_element - min_element - 2*K)\n \n \n \n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(0, max(A) - min(A) - 2 * K)\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(max(A) - min(A) - 2 * K, 0)\n# min_val = max_val = A[0]\n \n# for a in A:\n# if a < min_val: min_val = a\n# elif a > max_val: max_val = a\n# # min_val = min(min_val, a)\n# # max_val = max(max_val, a)\n \n# return max(max_val - min_val - 2 * K, 0) \n \n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n mx = max(A)\n mi = min(A)\n return 0 if mx - mi <= 2*K else mx - mi - 2*K", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n return max(0,max(A)-min(A)-2*K)\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n ks = [K for a in A]\n ks_left = True\n last_change = 0\n while ks_left and max(A) - min(A) > 0 and (max(A) - min(A)) != last_change:\n last_change = max(A) - min(A)\n # print(ks, A)\n ks_left = False\n average = sum(A) / len(A)\n for i in range(len(A)):\n difference = A[i] - average\n if -ks[i] <= difference <= ks[i]:\n A[i] = average\n # print(A[i], ks[i], difference)\n ks[i] = abs(ks[i] - abs(difference))\n # print(A[i], ks[i], difference)\n elif -ks[i] > difference:\n A[i] += ks[i]\n ks[i] = 0\n else:\n A[i] -= ks[i]\n ks[i] = 0\n if ks[i] > 0:\n ks_left = True\n print((ks, A))\n return int(max(A) - min(A))\n \n # if K == 0:\n # return max(A) - min(A)\n # max_A = max(A)\n # max_I = A.index(max_A)\n # min_A = min(A)\n # min_I = A.index(min_A)\n # if -K <= max_A - min_A <= K:\n # A[max_I] -= (max_A - min_A) / 2\n # A[min_I] += (max_A - min_A) / 2\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n A = sorted(A)\n min1 = set()\n max1 = set()\n for i in range(K+1):\n min1.add(A[0]+i)\n \n for i in range(K,-1,-1):\n max1.add(A[-1]-i)\n \n #print(min1,max1)\n \n s1 = min1 & max1\n if len(s1) > 0:\n return 0\n else:\n return min(list(max1)) - max(list(min1))\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n dist = max(A) - min(A)\n return dist - 2 * K if dist > 2 * K else 0", "class Solution:\n def smallestRangeI(self, a: List[int], k: int) -> int:\n a = sorted(a)\n a[-1] = max(a)\n a[0]= min(a)\n #print(a,a[-1])\n if a[-1]-k<=(a[0]+k):\n return 0\n return (a[-1]-k)-(a[0]+k)\n", "class Solution:\n def smallestRangeI(self, a: List[int], k: int) -> int:\n a = sorted(a)\n #print(a,a[-1])\n if a[-1]-k<=(a[0]+k):\n return 0\n return (a[-1]-k)-(a[0]+k)\n", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n if K == 0:\n return max(A) - min(A)\n # if len(set(A)) == 1:\n # return 0\n mean = (max(A) + min(A)) // 2\n B = []\n for num in A:\n if num + K <= mean:\n B.append(num + K)\n elif num - K >= mean:\n B.append(num - K)\n else:\n B.append(mean)\n return max(B) - min(B)", "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n if K == 0:\n return max(A) - min(A)\n if len(set(A)) == 1:\n return 0\n mean = (max(A) + min(A)) // 2\n B = []\n for num in A:\n if num + K < mean:\n B.append(num + K)\n elif num - K > mean:\n B.append(num - K)\n else:\n B.append(mean)\n return max(B) - min(B)"] | {"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 input array is a positive integer and will not exceed 10,000 | ["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 count += 1\n else:\n if count > countMax:\n countMax = count\n count = 0\n \n if count > countMax:\n countMax = count\n \n return countMax\n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n cur=0\n ans=0\n for num in nums:\n if num==1:\n cur=cur+1\n ans = max(ans,cur)\n else:cur=0\n return ans\n \n \n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = 0\n max_count = 0\n for num in nums:\n if num == 1:\n count += 1\n else:\n if count > max_count:\n max_count = count\n count = 0\n \n if count > max_count:\n max_count = count\n \n return max_count", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n cnt = 0\n max_cnt = 0\n for x in nums:\n if x == 1:\n cnt+=1\n else:\n if max_cnt < cnt:\n max_cnt = cnt\n cnt = 0\n if max_cnt < cnt:\n max_cnt = cnt\n return max_cnt", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ans=0\n c= 0\n for i in nums:\n c=i*c+i\n if c >ans:\n ans = c\n return ans", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_c = 0\n cur = 0\n \n for n in nums:\n if n == 1:\n cur += 1\n \n if n == 0:\n max_c = max(max_c, cur)\n cur = 0\n \n max_c = max(max_c, cur)\n \n return max_c\n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_c = 0\n cur = 0\n \n for n in nums:\n if n == 1:\n cur += 1\n \n if n == 0:\n max_c = max(max_c, cur)\n cur = 0\n \n max_c = max(max_c, cur)\n \n return max_c\n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_c = 0\n cur = 0\n \n for n in nums:\n if n == 1:\n cur += 1\n \n if n == 0:\n max_c = max(max_c, cur)\n cur = 0\n \n max_c = max(max_c, cur)\n \n return max_c\n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n sum = 0\n max = 0\n for i in range(0,len(nums)):\n if nums[i]==1:\n sum += 1\n else:\n sum = 0\n if sum > max:\n max = sum\n else:\n max = max\n return max\n \n \n", "class Solution:\n def findMaxConsecutiveOnes(self, nums):\n max_final = 0\n max_here = 0\n \n for num in nums:\n if num == 1:\n max_here+=1\n max_final = max(max_final, max_here)\n else:\n max_here = 0\n return max_final\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:\n # if i+1 == l:\n # return nums[i]\n # elif nums[i] != nums[i+1]:\n # #either i or i+1\n # if nums[i+2] == nums[i+1]:\n # return nums[i]\n # else: \n # i+=2\n \n # Attempt 2 - 100%\n result = 0\n for num in nums:\n result ^= num\n return result\n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n single = 0\n for n in nums:\n single ^= n\n return single", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = 0\n for key in nums:\n count = count ^ key\n return count\n \n \n \n \n \n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for i in nums:\n result ^= i\n return result", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = 0\n for i in range(len(nums)):\n res ^= nums[i]\n return res", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n return(sum(set(nums))*2-sum(nums))", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return\n s = set(nums)\n t = nums.copy()\n i = 0\n while s and i < len(t):\n if t[i] in s:\n s.remove(t.pop(i))\n else:\n i += 1\n return (set(nums) - set(t)).pop()\n", "class Solution:\n def singleNumber(self,nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n \n if len(nums) == 1:\n return nums[0]\n \n for i in range(0,len(nums),2):\n if i == len(nums)-1:\n return nums[i]\n if nums[i] != nums[i+1]:\n return nums[i]\n \n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = 0\n for num in nums:\n res ^= num\n return res\n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n single_one={nums[0]}\n for i in nums[1:]:\n if i in single_one:\n single_one.remove(i)\n continue\n else:\n single_one.add(i)\n if single_one=={}:\n single_one.add(i)\n return single_one.pop()\n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dic = dict()\n for num in nums:\n if num not in list(dic.keys()):\n dic[num]=1\n else:\n dic[num]+=1\n for key, val in list(dic.items()):\n if val == 1:\n return key\n \n \n \n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n mydict = {}\n for i in nums:\n if i not in mydict.keys():\n mydict[i] = 1\n else:\n if mydict[i] >= 2:\n return i\n mydict[i] = mydict[i] + 1\n for key, value in mydict.items():\n if value != 2:\n return key", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n \n for i in range(len(nums)):\n if not (i + 1 < len(nums) and (nums[i] == nums[i+1] or nums[i] == nums[i-1])):\n return nums[i]\n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # 1,3,1,2,4,3,4\n _dict = {}\n for num in nums:\n try:\n del _dict[num]\n except:\n _dict[num] = True\n return list(_dict.keys())[0]", "class Solution:\n def singleNumber(self, nums):\n dic = {}\n ans = 0\n \n for i in range(len(nums)):\n if str(nums[i]) in dic:\n dic[str(nums[i])] += 1\n else:\n dic[str(nums[i])] = 1\n \n for num in dic:\n if dic[num] == 1:\n ans = int(num)\n \n return ans\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n", "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n from collections import Counter\n a = Counter(nums)\n print(a)\n for k,i in list(a.items()):\n if i < 2:\n return k\n \n"] | {"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].length == 2
0 <= points[i][j] <= 100 | ["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 return points[0][0] * (points[1][1] - points[2][1]) + points[1][0] * (points[2][1] - points[0][1]) + points[2][0] * (points[0][1] - points[1][1]) != 0 #determinant is non-zero", "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 (y1 - y2) * (x1 - x3) != (y1 - y3) * (x1 - x2)"] | {"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:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010. | ["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 \n if cnt % 2 == 0:\n return False\n \n c = 1\n for i in range(1, cnt):\n c = c << 1\n if i % 2 == 0:\n c += 1\n \n return c == n\n", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n before = None\n while n != 0:\n d = n%2\n if not before:\n before = d + 1\n else:\n if before == d + 1:\n return False\n before = d + 1\n n = n >> 1\n \n return True\n", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n res = []\n while n > 0:\n res.append(str(n % 2))\n n //= 2\n for i in range(1, len(res)):\n if res[i] == res[i - 1]:\n return False\n return True\n", "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 \n if cnt % 2 == 0:\n return False\n \n c = 1\n for i in range(1, cnt):\n c = c << 1\n if i % 2 == 0:\n c += 1\n \n return c == n\n", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n prev = n % 2\n n = n // 2\n while n > 0:\n now = n % 2\n if now == prev:\n return False\n n = n // 2\n prev = now\n return True", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n # n = bin(n)[2:]\n # a = n[0::2]\n # b = n[1::2]\n # return (a.count(a[0]) == len(a) if a else True) and (b.count(b[0]) == len(b) if b else True) and (a[0] != b[0] if a and b else True)\n return '00' not in bin(n) and '11' not in bin(n)", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n i = n % 2\n while n > 0:\n if i % 2 == 0:\n n /= 2\n else:\n n = (n - 1) / 2\n i += 1\n return n == 0", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n now = n & 1\n while n:\n print(n , n & 1)\n n >>= 1\n if n & 1 == now:\n return False\n else:\n now = n & 1\n return True", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n bin1 = str(bin(n)[2:])\n length = len(bin1)\n for i in range(0,length-1):\n if bin1[i]==bin1[i+1]:\n return False\n \n return True\n \n", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n bits = bin(n)\n return all(bits[i] != bits[i+1] for i in range(len(bin(n)) - 1) )", "class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n prev = None\n while n:\n curr = n % 2\n if curr == prev:\n return False\n prev = curr\n n //= 2\n \n return True\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 are two 2-diff pairs in the array, (1, 3) and (3, 5).Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7]. | ["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 == 0:\n # for i in unique_nums:\n # if new_nums[i] > 1:\n # count +=1\n # return count\n # elif k < 0:\n # return 0\n # elif k > 0:\n # for i in unique_nums:\n # if i+k in unique_nums:\n # count += 1\n # return count\n \n # \u7528counter\u6765\u505a\n # import collections\n # count = 0\n # list_nums = set(nums)\n # if k == 0:\n # nums = collections.Counter(nums)\n # for each in nums:\n # if nums[each] > 1:\n # count += 1\n # return count\n # elif k < 0:\n # return 0\n # elif k > 0:\n # for i in list_nums:\n # if i + k in list_nums:\n # count += 1\n # return count\n \n # \u7528dict\u6765\u505a\n \n count = 0\n if k < 0 :\n return count\n if k == 0:\n new_nums = collections.defaultdict(int)\n for i in nums:\n new_nums[i] +=1\n for value in new_nums:\n if new_nums[value] > 1:\n count += 1\n return count\n if k > 0 :\n nums = set(nums)\n for i in nums:\n if i+k in nums:\n count += 1\n return count\n \n # if k < 0:\n # return 0\n # if k == 0:\n # dict = collections.defaultdict(int)\n # for i in nums:\n # dict[i] += 1\n # ans = 0\n # for value in dict.values():\n # if value > 1:\n # ans += 1\n # return ans\n # nums = set(nums)\n # ans = 0\n # for item in nums:\n # if item+k in nums:\n # ans += 1\n # return ans\n", "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 == 0:\n # for i in unique_nums:\n # if new_nums[i] > 1:\n # count +=1\n # return count\n # elif k < 0:\n # return 0\n # elif k > 0:\n # for i in unique_nums:\n # if i+k in unique_nums:\n # count += 1\n # return count\n \n # \u7528counter\u6765\u505a\n # import collections\n # count = 0\n # list_nums = set(nums)\n # if k == 0:\n # nums = collections.Counter(nums)\n # for each in nums:\n # if nums[each] > 1:\n # count += 1\n # return count\n # elif k < 0:\n # return 0\n # elif k > 0:\n # for i in list_nums:\n # if i + k in list_nums:\n # count += 1\n # return count\n \n # \u7528dict\u6765\u505a\n \n count = 0\n if k < 0 :\n return count\n if k == 0:\n new_nums = collections.defaultdict(int)\n for i in nums:\n new_nums[i] +=1\n for j in new_nums:\n if new_nums[j] > 1:\n count += 1\n return count\n if k > 0 :\n nums = set(nums)\n for i in nums:\n if i+k in nums:\n count += 1\n return count\n \n # if k < 0:\n # return 0\n # if k == 0:\n # dict = collections.defaultdict(int)\n # for i in nums:\n # dict[i] += 1\n # ans = 0\n # for value in dict.values():\n # if value > 1:\n # ans += 1\n # return ans\n # nums = set(nums)\n # ans = 0\n # for item in nums:\n # if item+k in nums:\n # ans += 1\n # return ans\n", "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 count = 0\n list_nums = set(nums)\n if k == 0:\n nums = collections.Counter(nums)\n for each in nums:\n if nums[each] > 1:\n count += 1\n return count\n elif k < 0:\n return 0\n elif k > 0:\n for i in list_nums:\n if i + k in list_nums:\n count += 1\n return count\n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n dic = {}\n count = 0\n if(k<0):\n return 0\n if(len(nums) == 1 or len(nums) == 0):\n return 0\n dic[nums[0]] = 1\n if(k == 0):\n for i in range(1,len(nums)):\n if(nums[i] in dic and dic[nums[i]]==1):\n dic[nums[i]] += 1\n count += 1\n elif(nums[i] not in dic):\n dic[nums[i]] = 1\n else:\n dic[nums[i]] += 1\n \n else:\n for i in range(1,len(nums)):\n if((nums[i]-k) in dic and nums[i] not in dic):\n count += 1\n if((nums[i]+k) in dic and nums[i] not in dic):\n count += 1\n dic[nums[i]] = 1\n \n \n return count", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k < 0:\n return 0\n result, lookup = set(), set()\n for num in nums:\n if num+k in lookup:\n result.add(num)\n if num-k in lookup:\n result.add(num-k)\n lookup.add(num)\n return len(result)\n \n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k < 0:\n return 0\n \n from collections import Counter\n c = Counter(nums)\n \n if k == 0:\n return sum([1 for num, count in list(c.items()) if count > 1])\n else:\n return sum([1 for num, _ in list(c.items()) if num + k in c])\n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n \n if k < 0:\n return 0\n \n unique = {}\n for num in nums:\n unique[num] = unique.get(num, 0) + 1\n \n res = 0\n for num in unique:\n if k == 0:\n if unique[num] > 1:\n res += 1\n else:\n if num+k in unique :\n res += 1\n \n return res ", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n \n ### 2 pointers\n # result = 0;\n # nums.sort()\n # for i in range(len(nums) - 1):\n # if i == 0 or (i != 0 and nums[i] != nums[i - 1]):\n # for j in range(i + 1, len(nums)):\n # if nums[j] - nums[i] == k:\n # result += 1\n # break\n # elif nums[j] - nums[i] > k:\n # break\n # return result\n \n ### map\n result = 0\n c = collections.Counter(nums)\n for i in c:\n if k > 0 and i + k in c or k == 0 and c[i] > 1:\n result += 1\n return result\n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\" Returns number of unique k-diff pairs(i, j) such as |i - j| = k.\n Algorithm based on hashing.\n \n Time complexity: O(n). Space complexity: O(n), n is len(nums).\n \"\"\"\n num_count = dict()\n for n in nums:\n num_count[n] = num_count.get(n, 0) + 1\n \n total = 0\n for n in num_count:\n if k == 0 and num_count[n] > 1:\n total += 1\n elif k > 0 and (n + k) in num_count:\n total += 1\n return total\n \n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n s = set(nums)\n total = 0\n if k < 0:\n return 0\n if k:\n for x in s:\n if x + k in s:\n total += 1\n else:\n counter = collections.Counter(nums)\n for k, v in counter.items():\n if v > 1:\n total += 1\n return total", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n \n if len(nums) < 2 or k < 0:\n return 0\n \n count = 0\n nums.sort()\n i, j = 0, 1\n while i < len(nums) - 1 and j < len(nums):\n j = max(i+1, j)\n d = nums[j] - nums[i]\n if d < k:\n j += 1\n elif d == k:\n count += 1\n while (i + 1) < len(nums) and nums[i] == nums[i + 1]:\n i += 1\n i += 1\n else:\n i += 1\n \n \n return count\n", "class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k<0:\n return 0\n \n pairs={}\n \n cnt = 0\n \n for a in nums: \n if not a in pairs:\n if a+k in pairs and a not in pairs[a+k]:\n pairs[a+k].append(a)\n cnt +=1\n if a-k in pairs and a not in pairs[a-k]:\n pairs[a-k].append(a)\n cnt +=1\n pairs[a]=[]\n else:\n if not a+k in pairs[a]:\n if a+k in pairs and a not in pairs[a+k]:\n pairs[a+k].append(a)\n cnt +=1\n if not a-k in pairs[a]:\n if a-k in pairs and a not in pairs[a-k]:\n pairs[a-k].append(a)\n cnt+=1\n \n return cnt"] | {"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 valid round's points.
"D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.
Each round's operation is permanent and could have an impact on the round before and the round after.
You need to return the sum of the points you could get in all the rounds.
Example 1:
Input: ["5","2","C","D","+"]
Output: 30
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The sum is: 5.
Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
Round 4: You could get 5 + 10 = 15 points. The sum is: 30.
Example 2:
Input: ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get -2 points. The sum is: 3.
Round 3: You could get 4 points. The sum is: 7.
Operation 1: The round 3's data is invalid. The sum is: 3.
Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.
Round 5: You could get 9 points. The sum is: 8.
Round 6: You could get -4 + 9 = 5 points. The sum is 13.
Round 7: You could get 9 + 5 = 14 points. The sum is 27.
Note:
The size of the input list will be between 1 and 1000.
Every integer represented in the list will be between -30000 and 30000. | ["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 for j in range(i-1 ,-1,-1):\n if self.isInt(ops[j]):\n sum = sum - int(ops[j])\n ops[j] = 'x'\n break\n elif op == 'D':\n for j in range(i-1 ,-1,-1):\n if self.isInt(ops[j]):\n ops[i] = str(int(ops[j]) * 2)\n sum = sum + int(ops[i])\n break\n elif op == '+':\n for j in range(i-1 , -1,-1):\n if self.isInt(ops[j]):\n for k in range(j-1, -1,-1):\n if self.isInt(ops[k]):\n ops[i] = str(int(ops[j]) + int(ops[k]))\n sum = sum + int(ops[i])\n break\n break\n \n return sum\n \n \n def isInt(self,x):\n try:\n return type(int(x)) == int\n except ValueError:\n return False", "class Solution:\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n def isint(num):\n try:\n int(num)\n return True\n except ValueError:\n return False\n score_board = []\n for i in ops:\n if isint(i):\n score_board.append(int(i))\n elif i == 'C':\n score_board.pop()\n elif i == 'D':\n score_board.append(score_board[-1] * 2)\n elif i == '+':\n score_board.append(sum(score_board[-2:]))\n return sum(score_board)", "class Solution:\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n ans = []\n for op in ops:\n try:\n integer = int(op)\n except ValueError:\n if op == 'C':\n ans.pop()\n elif op == 'D':\n ans.append(ans[-1] * 2)\n else:\n ans.append(sum(ans[-2:])) \n else:\n ans.append(integer)\n return sum(ans)"] | {"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 than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Example 1:
Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: S = "2-5g-3-J", K = 2
Output: "2-5G-3J"
Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Note:
The length of string S will not exceed 12,000, and K is a positive integer.
String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
String S is non-empty. | ["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_len = len(S) - count_dash\n \n # ans = ''\n # second_from = 0\n \n # frist_group = S_len % K\n # if frist_group != 0:\n # count = 0\n # for i in range(len(S)):\n # if S[i] != '-':\n # ans = ans + S[i].upper()\n # count += 1\n # if count == frist_group:\n # second_from = i + 1\n # ans += '-'\n # break\n # count_k = 0\n # for j in range(second_from,len(S)):\n # if S[j] != '-':\n # ans = ans + S[j].upper()\n # count_k += 1\n # if count_k == K:\n # ans = ans + '-'\n # count_k = 0\n \n # return ans[:-1]\n S = S.replace('-', '')[::-1].upper()\n return '-'.join([S[i:i+K] for i in range(0, len(S), K)])[::-1]\n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.upper().replace('-','')\n size = len(S)\n s1 = K if size%K==0 else size%K\n res = S[:s1]\n while s1<size:\n res += '-'+S[s1:s1+K]\n s1 += K\n return res", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.upper().replace(\"-\",\"\")\n s1 = len(S) % K if len(S) % K else K\n res = S[:s1]\n while s1<len(S):\n res +='-'+S[s1:s1+K]\n s1+=K\n return res", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.upper().replace(\"-\",\"\")\n i = 0\n res = []\n start = len(S) % K\n if start:\n res.append(S[:start])\n i = start\n \n while i < len(S):\n res.append(S[i:i+K])\n i += K\n \n return \"-\".join(res)\n \n \n \n \n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n s = list(''.join(S.split('-')))\n tmp = [''.join(s[:len(s) % K])] + [''.join(s[i:i+K]) for i in range(len(s) % K, len(s), K)] \n return '-'.join(filter(None, tmp)).upper()", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n char_list = self.getChars(S)\n num_groups = len(char_list) // K\n group_1_cnt = len(char_list) % K\n \n output = \"\"\n if group_1_cnt > 0:\n output += char_list[0:group_1_cnt]\n if num_groups > 0:\n output += \"-\"\n \n for i in range(1, num_groups + 1):\n start = i * K + group_1_cnt - K\n finish = start + K\n output += char_list[start:finish]\n if i != num_groups:\n output += \"-\"\n \n return output\n \n def getChars(self, S):\n char_list = \"\"\n \n for char in S:\n if char != \"-\":\n char_list += char.upper()\n \n return char_list\n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n key = list(S.replace('-', '').upper())\n offset = len(key) % K\n if offset == 0:\n offset = K\n new_key = []\n i = 0\n while i < len(key):\n if i == 0:\n new_key.extend(key[:offset])\n i = offset\n else:\n new_key.append('-')\n new_key.extend(key[i:i + K])\n i = i + K\n return ''.join(new_key)\n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.upper().replace('-', '')\n first = len(S) % K\n if first == 0:\n first = K\n blocks = [S[:first]]\n pos = first\n for k in range(len(S) // K):\n block = S[pos:pos+K]\n if len(block) > 0:\n blocks.append(block)\n pos += K\n return '-'.join(blocks)", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.upper().replace('-', '')\n index = K if len(S) % K == 0 and len(S) > 0 else len(S) % K\n result = S[:index]\n while index < len(S):\n result += '-' + S[index : index + K]\n index += K\n return result", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = S.replace(\"-\", \"\")\n l = len(S)\n res = l % K\n if res == 0:\n return \"-\".join([S[i*K: (i+1)*K].upper() for i in range(l//K)])\n else:\n lst = [S[0:res].upper()]\n return \"-\".join(lst + [S[i*K + res: (i+1)*K + res].upper() for i in range(l//K)])\n \n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n S = \"\".join(S.split(\"-\")) # remove dash\n S = S.upper() # change to upper character\n num_group = len(S) // K\n start_idx = len(S) % K\n \n ans = \"\" if start_idx == 0 else S[:start_idx]\n for i in range(num_group):\n end_idx = start_idx + K\n if start_idx > 0:\n ans += \"-\"\n ans += S[start_idx:end_idx]\n start_idx = end_idx\n return ans\n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n \n s = list(S.upper())\n s = [c for c in s if c != '-']\n \n groups = []\n while s:\n group = s[-K:]\n groups.append(''.join(group))\n s[-K:] = []\n \n groups.reverse()\n return '-'.join(groups)\n", "class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n \n if(len(S)<=1):\n return S.upper().strip('-')\n S = S.upper()\n n_dash = S.count('-')\n n = len(S)-n_dash\n form_S = \"\"\n if(n%K == 0):\n begin_at = K-1\n else:\n left = n%K\n begin_at = left-1\n steps = 0 \n abs_ind = 0\n norm_ind = 0\n \n while(abs_ind <=begin_at and norm_ind < len(S)):\n if(S[norm_ind]=='-'):\n norm_ind +=1\n continue\n form_S += S[norm_ind]\n abs_ind +=1\n norm_ind +=1\n form_S += '-'\n for char_ind in range(norm_ind, len(S)):\n if(S[char_ind] ==\"-\"):\n continue\n \n elif(steps == K-1 and abs_ind > begin_at):\n form_S += S[char_ind]+'-'\n steps =0\n else:\n form_S += S[char_ind]\n steps += 1\n \n abs_ind += 1\n \n \n return form_S.strip('-')"] | {"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.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
Example 2:
Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
Note:
1 .
bits[i] is always 0 or 1. | ["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: # bits[i] is 0\n i += 1\n # index: 0,1,2,..., L-2, L-1, where L denotes len(bits)\n if i == len(bits): # i comes from i+=2 case, bits[L-2] is 1, current i is one more of the last index, i.e. len(bits)\n return False # ...10\n \n else: # i comes from i+=1 case, bits[L-2] is 0, current i is the last index, len(bits)-1\n return True # ...00\n \"\"\"\n \n # Approach 2, much faster, scan from the back, till see a zero or exhaust the list\n # count how many one's there is.\n # Reason: ????...???0xxxx0 Only xxxx0 matters. After a 0, start the process again.\n # 0 always marks the end of the earlier bits.\n count = 0\n i = len(bits)-2 # s[len(s)-1] the last item in s is always 0.\n while i>=0 and bits[i] is not 0:\n count += 1\n i -= 1\n \n if (count % 2) == 0:\n return True\n else:\n return False\n \n \n \n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n if not bits: return False\n n = len(bits)\n \n index = 0\n while index < n:\n if index == n-1 : return True\n if bits[index] == 1: \n index += 2 \n else: index += 1\n return False", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n bits.insert(0,0)\n for i in range(len(bits)-2,-1,-1):\n if bits[i]==0 or i==0:\n return (len(bits)-i)%2==0\n def isOneBitCharacter(self, bits):\n parity = bits.pop()\n while bits and bits.pop(): parity ^= 1\n return parity == 0\n def isOneBitCharacter(self, bits):\n i = 0\n while i < len(bits) - 1:\n i += bits[i] + 1\n return i == len(bits) - 1", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n if not bits: return False\n n = len(bits)\n index = 0\n while index < n:\n if index == n-1 : return True\n if bits[index] == 1: \n index += 2 \n else: index += 1\n return False\n \n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n i = 0\n n = len(bits)\n while i < n-1:\n if bits[i]==1: i+=2\n else: i+=1\n return i==n-1\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n l = len(bits) \n if l == 1:\n if bits[0]==0:\n return True\n else:\n return False\n i = 0\n while 1 :\n if bits[i]==1:\n l -= 2\n i += 2\n else:\n l -= 1\n i += 1\n if l == 1:\n return True\n if l == 0:\n return False", "class Solution:\n def isOneBitCharacter(self, bits):\n n = len(bits)\n if bits[n-1] != 0:\n return False\n else:\n i = 0\n while i < n-2: # -1 for we have considered the last bit, another -1, we may use two bits at a time\n print((bits[i], ', '))\n if bits[i] == 1:\n if bits[i+1] == 0 or bits[i+1] == 1:\n i += 1\n else:\n return False\n elif bits[i] == 0:\n pass\n i += 1\n if bits[i] == 1:\n return False\n return True\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n if len(bits)==1 and bits[0]==1: \n return False\n n = len(bits)\n i = 0\n while(i < n):\n if i == n-1: return True\n else:\n if bits[i] == 1:\n i += 2\n else: i+=1\n return False", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n i = 0\n while i < len(bits) - 1:\n if bits[i] == 0: i += 1\n elif bits[i] == 1: i += 2\n return i==len(bits)-1\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n i=len(bits)\n res=False\n while bits != []:\n e=bits.pop(0)\n if bits==[] and e == 0:\n return True\n if e == 1 and bits!=[]:\n bits.pop(0)\n i-=1\n return res", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n n=len(bits)\n flag=[0 for i in range(n)]\n i=0\n while i <n-1:\n print(i)\n if bits[i]==1:\n flag[i+1]=1\n i=i+1+flag[i+1]\n result=True if flag[-1]==0 else False\n return result\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n bits = ''.join(map(str, bits))\n return self.dfs(bits)\n \n def dfs(self, bits):\n if len(bits) == 0:\n return False\n elif len(bits) == 1:\n if bits[0] == '0':\n return True\n else:\n if bits[:2] == '10':\n if self.dfs(bits[2:]):\n return True\n elif bits[:2] == '11':\n if self.dfs(bits[2:]):\n return True\n elif bits[0] == '0':\n if self.dfs(bits[1:]):\n return True\n return False\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n n = len(bits)\n i = 0\n current = 0\n \n while i < n:\n if bits[i] == 1:\n current = 2\n i += 2\n else:\n current = 1\n i += 1\n \n if current == 1:\n return True\n else:\n return False\n", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n i = 0\n while i < (len(bits)-1):\n if bits[i] == 1:\n i += 2\n else:\n i += 1\n if i == len(bits):\n return False\n else:\n return True", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n n = 0\n for i in range(-2, -len(bits)-1, -1):\n if bits[i] == 1:\n n += 1\n else:\n break\n return n % 2 == 0", "class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n bits.insert(0,0)\n for i in range(len(bits)-2,-1,-1):\n if bits[i]==0 or i==0:\n return (len(bits)-i)%2==0\n \n"] | {"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 valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".
Example 2:
Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".
Example 3:
Input: n = 7
Output: "holasss"
Constraints:
1 <= n <= 500 | ["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) + ['bc'])", "class Solution:\n def generateTheString(self, n: int) -> str:\n if (n&0x1)==1:\n return 'a'*n\n else:\n return (n-1)*'a'+'b'", "class Solution:\n def generateTheString(self, n: int) -> str:\n \n \n \n if n%2 == 0:\n \n return 'a'*(n-1) + 'b'\n \n else:\n if n == 1:\n return 'a'\n else:\n return 'a'*(n-2) + 'bc'", "import random\nimport string\n\nclass Solution:\n def generateTheString(self, n: int) -> str:\n if n%2!=0:\n return 'a'*n \n else:\n return 'a'*(n-1) + 'b'\n"] | {"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 :type s: str\n :rtype: bool\n \"\"\"\n s = s.lower()\n s = [c for c in s if c.isalnum()]\n return s == s[::-1]\n", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = [symbol for symbol in s.lower() if 'a' <= symbol <= 'z' or '0' <= symbol <= '9']\n \n return s == s[::-1]", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = s.strip().lower()\n if s == '': return True\n wordsR = []\n for item in s:\n if item.isalnum() == True:\n wordsR.append(item)\n if wordsR == []: return True\n words = wordsR[:]\n wordsR.reverse()\n if words == wordsR:\n return True\n else:\n return False\n \n", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n b=0\n t=len(s)-1\n while b<t:\n while b<t and not s[b].isalnum():\n b=b+1\n while b<t and not s[t].isalnum():\n t=t-1\n if s[b].lower() != s[t].lower():\n return False\n b=b+1\n t=t-1\n return True", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s) == 0:\n return True\n pt1 = 0\n pt2 = len(s) - 1\n while pt1 < pt2:\n while pt1 < pt2 and not s[pt1].isalnum():\n pt1 = pt1 + 1\n while pt1 < pt2 and not s[pt2].isalnum():\n pt2 = pt2 - 1\n if pt1 < pt2 and s[pt1].lower() != s[pt2].lower():\n return False\n pt1 = pt1 + 1\n pt2 = pt2 - 1\n return True", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n left, right = 0, len(s) - 1\n while left < right:\n while left < len(s) and not s[left].isalnum():\n left += 1\n \n while right >= 0 and not s[right].isalnum():\n right -= 1\n \n if left >= len(s) or right < 0:\n return True\n \n if s[left].lower() != s[right].lower():\n return False\n left += 1\n right -= 1\n \n return True\n", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n i = 0\n j = len(s) - 1\n while(i < j):\n while(i <= len(s) - 1 and not s[i].isalnum()):\n i += 1\n while(j >= 0 and not s[j].isalnum()):\n j -= 1\n \n if i < j and s[i].lower() != s[j].lower():\n return False\n \n i += 1\n j -= 1\n return True\n", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = s.lower()\n i = 0\n j = len(s) - 1\n while i < j:\n if not self._is_alphanumeric(s[i]):\n i += 1\n continue\n if not self._is_alphanumeric(s[j]):\n j -= 1\n continue\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n \n def _is_alphanumeric(self, c):\n if (ord(c) >= 97 and ord(c) <= 122) or (ord(c) >= 48 and ord(c) <= 57):\n return True"] | {"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.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
Example 4:
Input: arr = [1,2,3,1,2], m = 2, k = 2
Output: false
Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.
Example 5:
Input: arr = [2,2,2,2], m = 2, k = 3
Output: false
Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
Constraints:
2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100 | ["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:\n return True\n \n return False", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n streak = 0\n for i in range(len(arr)-m):\n streak = streak + 1 if arr[i] == arr[i+m] else 0\n if streak == (k-1) *m:\n return True\n return False\n \n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n l=list(map(str,arr))\n n=len(l)\n for i in range((n-m)+1):\n d=[]\n for j in range(i,n,m):\n x=l[j:j+m]\n print(x)\n if len(x)>=m:\n if d==[]:\n d.append(x)\n elif d[-1]==x:\n d.append(x)\n if len(d)>=k:\n return True\n else:\n d=[x]\n return False \n \n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n for i in range(0, len(arr)-(k-1)*m-m+1):\n found = True\n for j in range(0, m):\n for n in range(1, k):\n #print(i, j, n, i+j, m*n + i+j)\n if arr[i+j] != arr[m*n + i+j]:\n found = False\n if found:\n return True\n return False\n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n for i in range(0, len(arr)-(k-1)*m-m+1):\n found = True\n j = 0\n while found and j < m:\n n = 1\n while found and n < k:\n if arr[i+j] != arr[m*n + i+j]:\n found = False\n n += 1\n j += 1\n if found:\n return True\n return False\n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n if arr is None:\n return False\n if m<=len(arr) and k*m<=len(arr):\n for s in range(len(arr)-m):\n rec={}\n for i in range(s,len(arr)-m+1):\n if tuple(arr[i:i+m]) not in rec:\n rec[tuple(arr[i:i+m])]=1\n else:\n if arr[i:i+m]==arr[i-m:i]:\n rec[tuple(arr[i:i+m])]+=1\n else:\n break\n tmp=list(rec.values())\n if k in tmp:\n return True\n return False\n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n L = len(arr)\n cnt = 0\n for i in range(L - m):\n if arr[i] == arr[i + m]:\n cnt += 1\n else:\n cnt = 0\n if cnt == m * (k - 1):\n return True\n return False \n \n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n for i in range(len(arr)-m+1):\n p = arr[i:i+m]\n c = 1\n for j in range(i+m, len(arr)-m+1):\n if arr[j:j+m] == p:\n c += 1\n if c == k:\n return True\n else:\n break\n return False", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n L = len(arr)\n for i in range(L - m * k + 1):\n offset = 0\n iFlag = True\n for ki in range(1, k):\n offset += m\n kFlag = True\n for mi in range(m):\n if arr[i + mi] != arr[i + offset + mi]:\n kFlag = False\n break\n if not kFlag:\n iFlag = False\n break\n if iFlag:\n return True\n return False\n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n = len(arr)\n if n<m*k:\n return False\n \n def is_matched(a,b,c):\n if c==0:\n return True\n \n if arr[b:b+m]!=arr[a:a+m]:\n return False\n \n return is_matched(a, b+m, c-1)\n \n for a in range(0, n-k*m+1):\n if is_matched(a, a+m, k-1):\n return True\n \n return False\n \n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n l=list(map(str,arr))\n n=len(l)\n for i in range((n-m)+1):\n d=[]\n for j in range(i,n,m):\n x=l[j:j+m]\n if len(x)>=m:\n if d==[]:\n d.append(x)\n elif d[-1]==x:\n d.append(x)\n if len(d)>=k:\n return True\n else:\n d=[x]\n return False \n \n", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n for i in range(len(arr)):\n if i + m * k - 1 >= len(arr):\n break\n if arr[i:i+m] * k == arr[i:i+m*k]:\n return True\n return False", "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n arrstr = [str(v) for v in arr]\n patterns = defaultdict(int)\n start = end = 0\n n = len(arrstr)\n \n while end < n:\n if (end-start)+1 > m:\n start += 1\n \n if (end-start)+1 == m:\n substring = ','.join(arrstr[start:end+1])\n pstart = start-m\n if pstart >= 0 and ','.join(arrstr[pstart:start]) == substring:\n patterns[substring] += 1\n else:\n patterns[substring] = 1\n if patterns[substring] >= k:\n return True\n end += 1\n \n return False", "class Solution:\n def containsPattern(self, arr: List[int], k: int, m: int) -> bool:\n i = 0\n \n n = len(arr)\n while(i + k < n):\n s = 0\n c = i\n lx = arr[c:c + k]\n while(c + k<= n):\n if(lx == arr[c:c + k]):\n s += 1\n else:\n break\n c += k\n if(s >= m):\n return True\n i += 1\n return False\n \n \n \n"] | {"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: int\n \"\"\"\n '''\n if s == None: return 0\n count = 0\n for item in s[-1::-1]:\n if item == ' ':\n break\n count += 1\n return count\n '''\n count = len(s.strip().split(' ')[-1])\n return count\n \n \n \n", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return len(s.strip(' ').split(' ')[-1])", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ans,tail=0,len(s)-1\n while tail>=0 and s[tail]==' ':\n tail-=1\n while tail>=0 and s[tail]!=' ':\n ans+=1\n tail-=1\n return ans", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n \n s = s.rstrip()\n s = s.lstrip()\n \n for i in range(0,len(s))[::-1]:\n if s[i] == ' ':\n return len(s)-1-i\n return len(s)\n \n \n", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n spaces = 0\n word_started = False\n # Traverse through string from back\n # Count number of spaces encountered before first word starts\n # Keep going through characters until next space is found\n # Return that index (minus one, not counting the space)\n # And subtract the number of spaces\n for i in range(1, len(s) + 1):\n if s[-i] == \" \" and word_started is False:\n spaces += 1\n elif s[-i] == \" \" and word_started is True:\n return i - 1 - spaces\n else:\n word_started = True\n if word_started is True:\n return len(s) - spaces\n else:\n return 0", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n words = s.split()\n if not words:\n return 0\n return len(words[-1])", "class Solution:\n def lengthOfLastWord(self, s):\n res = 0;\n last = 0;\n for i in s:\n if(i == ' '):\n res = 0;\n else:\n res += 1;\n last = res;\n \n return last;\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = s.split(' ')\n while l:\n if l[-1]:\n return len(l[-1])\n else:\n l.pop(-1)\n return 0", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v = s.split()\n if not v:\n return 0\n else:\n return len(v[-1])\n", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = len(s)\n n_c=0\n for i in range(l-1,-1,-1):#\u4ece\u672b\u5c3e\u5f00\u59cb\u8ba1\u6570\n if s[i]!=' ':\n n_c += 1\n elif s[i]==' ' and n_c == 0 :\n pass\n elif s[i]==' ' and n_c != 0 : #\u9047\u5230\u7a7a\u683c\uff0c\u4e14\u5b57\u7b26\u8ba1\u6570\u975e\u96f6\u65f6\uff0c\u8fd4\u56de\u8ba1\u6570\u503c\n return n_c\n return n_c", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n s = s.strip()\n if s == None: return 0\n count = 0\n for item in s[-1::-1]:\n if item == ' ':\n break\n count += 1\n return count\n \n \n \n"] | {"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 empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). | ["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 == \"\" or needle == \"\" or len(haystack.split(needle)) == 1:\n return -1\n return len(haystack.split(needle)[0])\n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n # if needle in haystack:\n # for i in range(len(haystack)-len(needle)+1):\n # if haystack[i:i+len(needle)]==needle:\n # return i\n # else:\n # return -1\n \n return haystack.find(needle)\n \n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n for i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n return i\n \n return -1\n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if not needle:\n return 0\n \n for i in range(0, len(haystack)-len(needle)+1):\n match = True\n for j in range(len(needle)):\n if haystack[i+j] != needle[j]:\n match = False\n break\n if match:\n return i\n \n return -1\n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n \n if needle == \"\":\n return 0 \n for i in range(len(haystack) - len(needle) + 1):\n for j in range(len(needle)):\n if haystack[i+j] == needle[j]:\n if j == len(needle) - 1:\n return i \n else:\n break\n \n return -1\n \n \n", "class Solution:\n def makeNext(self,s):\n k = -1; i = 0;\n next = [None for i in range(len(s))]\n next[0] = -1\n while(i < (len(s)-1)):\n while(k>=0 and s[i] != s[k]):\n k = next[k]\n i += 1; k+= 1;\n if(s[i] == s[k]):\n next[i] = next[k]\n else:\n next[i] = k\n return next\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if(needle == \"\"):\n return 0\n Next = self.makeNext(needle)\n length = len(needle)\n \n for i in range(len(haystack)):\n count = 0\n while(haystack[i + count] == needle[count]):\n count += 1 \n if(count + i >= len(haystack)) and (count < length):\n return -1\n break\n if (count >= length):\n return i\n break\n return -1\n \n \n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if not needle:\n return 0\n \n nexts = [0] * len(needle)\n nexts[0] = -1;\n if len(needle) > 1:\n nexts[1] = 0;\n left = 0; right = 2;\n while right < len(needle):\n if needle[left] == needle[right - 1]:\n nexts[right] = left + 1\n left += 1\n right += 1\n else:\n if nexts[left] > 0:\n left = nexts[left]\n else:\n nexts[right] = 0\n left = 0\n right += 1\n \n i = 0; j = 0\n while i <= len(haystack) - len(needle):\n if j == len(needle):\n return i\n \n if haystack[i + j] == needle[j]:\n j += 1\n else:\n # ababdef i=0\n # ababc j=4\n # x0012\n # ababc i=2,j=2\n if nexts[j] > 0:\n i = i + j - nexts[j]\n j = nexts[j]\n else:\n i = i + 1\n j = 0\n \n return -1\n \n", "class Solution:\n def myNext(self, T):\n next = [-1] # a next array with first is -1\n l = len(T) # the kid str length\n i, j = 0, -1 # i is last , j is first\n while i < l:\n if j == -1 or T[i] == T[j]:\n i += 1\n j += 1\n next.append(int(j)) # the same str\n else:\n j = next[j]\n return next\n \n def strStr(self, haystack, needle):\n if needle == \"\":\n return 0\n arr = Solution().myNext(needle)\n l1 = len(haystack)\n l2 = len(needle)\n i, j = 0, 0\n while i < l1 and j < l2:\n if j == -1 or haystack[i] == needle[j]:\n i += 1\n j += 1\n if j == l2:\n return i - l2\n else:\n j = arr[j]\n return -1", "class Solution:\n def makeNext(self,s):\n k = -1; i = 0;\n next = [None for i in range(len(s))]\n next[0] = -1\n while(i < (len(s)-1)):\n while(k>=0 and s[i] != s[k]):\n k = next[k]\n i += 1; k+= 1;\n if(s[i] == s[k]):\n next[i] = next[k]\n else:\n next[i] = k\n return next\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if(needle == \"\"):\n return 0\n Next = self.makeNext(needle)\n length = len(needle)\n \n for i in range(len(haystack)):\n count = 0\n while(haystack[i + count] == needle[count]):\n count += 1 \n if(count + i >= len(haystack)) and (count < length):\n return -1\n break\n if (count >= length):\n return i\n break\n return -1\n \n \n", "class Solution(object):\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if len(haystack) == len(needle):\n if haystack == needle:\n return 0\n else:\n return -1\n \n for i in range(0,len(haystack)):\n k=i\n j=0\n while j<len(needle) and k<len(haystack) and haystack[k] == needle[j]:\n j+=1\n k+=1\n if j==len(needle):\n return i\n return -1 if needle else 0", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n \n if needle == \"\":\n return 0 \n for i in range(len(haystack) - len(needle) + 1):\n for j in range(len(needle)):\n if haystack[i+j] == needle[j]:\n if j == len(needle) - 1:\n return i \n else:\n break\n \n return -1\n \n \n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if len(haystack) < len(needle):\n return -1\n if needle == '':\n return 0\n \n for i in range(len(haystack)):\n if haystack[i] == needle[0]:\n res = True\n j = 1\n try:\n while (j < len(needle)):\n if haystack[i+j] == needle[j]:\n j += 1\n else:\n res = False\n break\n if res:\n return i\n except:\n return -1\n return -1", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n \n # KMP\n i, j, m, n = -1, 0, len(haystack), len(needle)\n # construct jump array\n jump = [-1]*n\n while j < n-1: # j is increased by one\n if i == -1 or needle[i] == needle[j]:\n i, j = i+1, j+1\n jump[j] = jump[i] if needle[i]==needle[j] else i\n else:\n i = jump[i]\n \n # swipe\n i, j = 0, 0 # both start at 0\n while i < m and j < n: # CAUTION j < n\n if j == -1 or haystack[i] == needle[j]:\n i, j = i+1, j+1\n else:\n j = jump[j]\n return i-j if j == n else -1", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n next = self.next(needle)\n i = 0\n j = 0\n while i < len(haystack) and j < len(needle):\n if j == -1 or haystack[i] == needle[j]:\n i += 1\n j += 1\n else:\n j = next[j]\n if j == len(needle):\n return i - j\n else:\n return -1\n \n \n def next(self, p):\n next = []\n next.append(-1)\n i = 0\n k = -1\n while i < len(p) - 1:\n if k == -1 or p[i] == p[k]:\n i += 1\n k += 1\n next.append(k)\n else:\n k = next[k]\n return next", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n \n if not needle:\n return 0\n \n if not haystack:\n return -1\n \n if len(haystack) < len(needle):\n return -1\n \n N = len(haystack)\n for i in range(N):\n if needle == haystack[i:i+len(needle)]:\n return i\n \n return -1\n \n", "class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if needle == '':\n return 0\n substr_len = len(needle)\n for index, char in enumerate(haystack):\n if haystack[index:index+substr_len] == needle:\n return index\n return -1", "class Solution:\n \n def prefixTable(self, s):\n t = [0 for _ in s]\n j = 0\n i = 1\n while i < len(s):\n if j == 0 and s[i] != s[j]:\n t[i] = 0\n i += 1\n elif s[i] == s[j]:\n t[i] = j + 1\n i += 1\n j += 1\n elif j > 0 and s[j] != s[i]:\n j = t[j-1]\n return t\n \n def find(self, text, pattern):\n ans = []\n t = self.prefixTable(pattern)\n i = j = 0\n while i < len(text):\n if text[i] == pattern[j]:\n i += 1\n j += 1\n \n if j == len(pattern):\n ans.append(i - len(pattern))\n j = t[j-1]\n \n elif i < len(text) and text[i] != pattern[j]:\n if j > 0:\n j = t[j-1]\n else:\n i += 1\n return ans\n \n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if len(needle) == 0:\n return 0\n ans = self.find(haystack, needle)\n return ans[0] if ans else -1\n # for i in range(len(haystack) - len(needle) + 1):\n # if haystack[i: i + len(needle)] == needle:\n # return i\n # return -1\n \n \n # for i in range(len(haystack) - len(needle) + 1):\n # if haystack[i : i + len(needle)] == needle:\n # return i\n # return -1\n"] | {"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 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step | ["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 else:\n number += self.climbStairs(n - 1) + self.climbStairs(n - 2)\n self.dictionary[n] = number\n return number", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n result = [1 for i in range(n+1)]\n for i in range(2, n + 1):\n result[i] = result[i - 1] + result[i - 2]\n return result[n]", "class Solution:\n def climbStairs(self, n):\n T = [1, 1]\n for i in range(2, n+1):\n T[i%2] = T[(i - 2)%2] + T[(i-1)%2]\n return T[n%2]\n \n \n def iterative_climbStairs(self, n):\n T = [-1]*n\n T[0] = 0\n T[1] = 1\n for i in range(2, n+1):\n T[i] = T[i - 2] + T[i - 1]\n return T[n]\n \n \n def recursive_climbStairs(self, T, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if (n in T):\n return T[n]\n if (n < 0):\n return 0\n if (n < 2):\n return 1\n T[n] = self.climbStairs(n - 2) + self.climbStairs(n - 1)\n return T[n]", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n steps = [0, 1, 2]\n if n < 3:\n return steps[n]\n for i in range(3,n+1):\n steps.append(steps[i-1] + steps[i-2])\n return steps[n]", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # f(i) = f(i-1) + f(i-2)\n if n == 0 or n == 1:\n return 1\n f2, f1 = 1, 1\n for i in range(2, n+1):\n f = f1 + f2\n f2, f1 = f1, f\n return f\n \n def climbStairs(self, n):\n F = {0:1, 1:1}\n def f(i):\n if i in F:\n return F[i]\n else:\n F[i] = f(i-1) + f(i-2)\n return F[i]\n return f(n)", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 1:\n return 1\n \n dp = [0]*(n+1)\n dp[0] = 1\n dp[1] = 1\n \n for i in range(2,n+1):\n dp[i] += dp[i-1] +dp[i-2]\n return dp[n]\n", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n < 3:\n return n\n a = [1, 2]\n for i in range(2, n):\n a.append(a[i-1] + a[i-2])\n return a[n-1]", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n<=3:\n return n\n \n v=[1,2,3]\n for i in range(3,n):\n v.append(v[-1]+v[-2])\n return v[-1]", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n a = 1\n b = 2\n if n < 2:\n return 1\n for i in range(n-2):\n a,b = b, a+b\n \n return b", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n #\u9012\u5f52\u8d85\u65f6\u3002\u3002\n # if n == 1:\n # return 1\n # if n == 2:\n # return 2\n # return self.climbStairs(n-1)+self.climbStairs(n-2)\n \n #\u6539\u8fdb\u9012\u5f52\uff0c\u4f7f\u7528cache\n cache = {}\n def f(n):\n if n == 1:\n return 1\n if n == 2:\n return 2\n if n in list(cache.keys()):\n return cache[n]\n cache[n] = f(n-1) + f(n-2)\n return cache[n]\n return f(n)\n \n \n #\u6539\u6210\u5faa\u73af\u3002\u9012\u63a8\u516c\u5f0f\u4e3a\u3002f(n) = f(n-1) + f(n-2)\n \n", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n # n[0] = 1\n # n[1] = 1\n # n[2] = n[0] + n[1]\n # n[3] = n[1] + n[2]\n # n[4] = n[2] + n[3]\n \n if n == 0 or n == 1:\n return 1\n \n ns = [1, 1]\n for i in range(2, n):\n ns[i%2] = sum(ns)\n \n return sum(ns)\n \n", "class Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n <= 0:\n return 0\n if n==1:\n return 1\n if n==2:\n return 2\n a, b=1,2\n for i in range(n)[2:]:\n a,b=b,a+b\n return b\n"] | {"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 adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100
s contains only lower and upper case English letters. | ["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 \n \n", "class Solution:\n def makeGood(self, s: str) -> str:\n i=0\n while i<len(s)-1:\n if abs(ord(s[i])-ord(s[i+1]))==32:\n s=s[:i]+s[i+2:]\n i-=1\n i=max(0,i)\n else:\n i+=1\n return s", "class Solution:\n def makeGood(self, s: str) -> str:\n res = []\n for i in s:\n if not res:\n res.append(i)\n elif res[-1].islower() and res[-1].upper() == i:\n res.pop()\n elif res[-1].isupper() and res[-1].lower() == i:\n res.pop()\n else:\n res.append(i)\n return ''.join(res)", "class Solution:\n def makeGood(self, s: str) -> str:\n if len(s) == 1:\n return s\n \n for i in range(len(s) - 2, -1, -1):\n if s[i].lower() == s[i+1].lower() and s[i] != s[i+1]:\n s = s[:i] + s[i+2:]\n return self.makeGood(s)\n \n \n \n \n return s", "class Solution:\n def makeGood(self, s: str) -> str:\n listx=[('a','A'),('b','B'),('c','C'),('d','D'),('e','E'),('f','F'),('g','G'),('h','H'),('i','I'),('j','J'),('k','K'),('l','L'),('m','M'),('n','N'),('o','O'),('p','P'),('q','Q'),('r','R'),('s','S'),('t','T'),('u','U'),('v','V'),('w','W'),('x','X'),('y','Y'),('z','Z'),('A','a'),('B','b'),('C','c'),('D','d'),('E','e'),('F','f'),('G','g'),('H','h'),('I','i'),('J','j'),('K','k'),('L','l'),('M','m'),('N','n'),('O','o'),('P','p'),('Q','q'),('R','r'),('S','s'),('T','t'),('U','u'),('V','v'),('W','w'),('X','x'),('Y','y'),('Z','z')]\n listy=[s[0]]\n empty=''\n for i in range(1,len(s)):\n if listy:\n a=listy.pop()\n if (a,s[i]) not in listx:\n listy.append(a)\n listy.append(s[i])\n else:\n listy.append(s[i])\n if listy:\n return ''.join(listy)\n else:\n return empty\n \n", "class Solution:\n def makeGood(self, s: str) -> str:\n stack = []\n for i in range(len(s)):\n if (len(stack) == 0):\n stack.append(s[i])\n elif (s[i].isupper() and stack[-1].islower() and (stack[-1].upper() == s[i])):\n stack.pop(-1)\n elif (s[i].islower() and stack[-1].isupper() and (stack[-1].lower() == s[i])):\n stack.pop(-1)\n else:\n stack.append(s[i])\n return ''.join(stack)\n \n \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 largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.
Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Example 2:
Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
Example 3:
Input: s = "leetcode"
Output: "cdelotee"
Example 4:
Input: s = "ggggggg"
Output: "ggggggg"
Example 5:
Input: s = "spo"
Output: "ops"
Constraints:
1 <= s.length <= 500
s contains only lower-case English letters. | ["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 \n for i in suniq:\n if s.count(i) > max_count:\n max_count = s.count(i)\n \n \n chr_count = [0 for i in range(len(suniq))]\n \n \n\n s_sort = ''\n \n for j in range(max_count):\n \n \n for i in range(len(suniq)):\n if chr_count[i] < s.count(suniq[i]):\n s_sort += suniq[i]\n chr_count[i] += 1\n else:\n continue\n \n suniq = suniq[::-1]\n chr_count = chr_count[::-1]\n \n \n return s_sort \n \n", "from collections import OrderedDict\nclass Solution:\n def sortString(self, s: str) -> str:\n \n s1 = OrderedDict()\n \n for i in s:\n \n if i in s1:\n s1[i] += 1\n else:\n s1[i] = 1\n \n \n reverse = 0\n t = []\n s1 = OrderedDict(sorted(s1.items()))\n print(s1)\n while(True):\n p = []\n for key,value in list(s1.items()):\n if value > 0:\n s1[key] = value - 1\n p.append(key)\n \n if p == []:\n break\n if reverse == 1:\n t += p[::-1]\n else:\n t += p\n reverse = 1 - reverse\n print(t)\n return (''.join(t))\n", "class Solution:\n def sortString(self, s: str) -> str:\n output = []\n total = sorted(list(s))\n direction = 1\n while(len(total) > 0):\n if(direction == 1):\n selection = sorted(set(total))\n else:\n selection = sorted(set(total), reverse=True)\n direction *= -1\n output = output + list(selection)\n for char in selection:\n total.remove(char)\n return ''.join(output)\n \n \n \n \n", "\nclass Solution:\n def sortString(self, s: str) -> str:\n s = sorted(s)\n ans = []\n while s:\n for i in sorted(list(set(s))):\n ans.append(s.pop(s.index(i)))\n \n for i in sorted(set(s),reverse=True):\n ans.append(s.pop(s.index(i)))\n \n \n return ''.join(ans)", "\nclass Solution:\n def sortString(self, s: str) -> str:\n s = sorted(s)\n ans = []\n while s:\n for i in sorted(set(s)):\n ans.append(s.pop(s.index(i)))\n \n for i in sorted(set(s),reverse=True):\n ans.append(s.pop(s.index(i)))\n \n \n return ''.join(ans)", "class Solution:\n def sortString(self, s: str) -> str:\n from collections import Counter\n d=Counter(s)\n asc=True\n ans=''\n while d:\n for i in sorted(d) if asc else sorted(d,reverse=True):\n ans+=i\n d[i]-=1\n if d[i]==0:\n del d[i]\n asc^=True\n return ans", "class Solution:\n collections.OrderedDict\n def sortString(self, s: str) -> str:\n list_s = list(s)\n list_s.sort()\n dict_s = {}\n for i in range(len(list_s)):\n if list_s[i] not in dict_s:\n dict_s[list_s[i]] = 1\n else:\n dict_s[list_s[i]] += 1\n result = []\n while dict_s != {}:\n i = 0\n while dict_s != {} and i < len(dict_s):\n result.append(list(dict_s)[i])\n if dict_s[list(dict_s)[i]] - 1 == 0:\n del dict_s[list(dict_s)[i]]\n else:\n dict_s[list(dict_s)[i]] -= 1\n i += 1\n i = len(dict_s) - 1\n while dict_s != {} and i >= 0:\n result.append(list(dict_s)[i])\n if dict_s[list(dict_s)[i]] - 1 == 0:\n del dict_s[list(dict_s)[i]]\n else:\n dict_s[list(dict_s)[i]] -= 1\n i -= 1\n return ''.join(result)\n \n \n", "class Solution:\n def sortString(self, s: str) -> str:\n output = []\n temp = sorted(list(s))\n\n while len(temp)>0:\n output.append(temp[0])\n temp.remove(temp[0])\n for e in temp:\n if e>output[-1]:\n output.append(e)\n temp[temp.index(e)] = ''\n temp = [e for e in temp if e]\n\n if len(temp)==0:\n break\n\n output.append(temp[-1])\n temp.remove(temp[-1])\n for i in range(len(temp)-1,0,-1):\n if temp[i]<output[-1]:\n output.append(temp[i])\n temp[i] = ''\n temp = [e for e in temp if e]\n\n return ''.join(output)", "from collections import Counter\nclass Solution:\n def sortString(self, s: str) -> str:\n result = []\n s = sorted(s)\n counter = Counter(s)\n \n while s:\n for x in sorted(set(s)):\n s.remove(x)\n result.append(x)\n for x in sorted(set(s), reverse=True):\n s.remove(x)\n result.append(x)\n return ('').join(result)", "class Solution:\n def sortString(self, s: str) -> str:\n res = ''\n s = list(s)\n s.sort()\n while s:\n i = 0\n curr = []\n while i < len(s):\n if s[i] not in curr:\n curr.append(s.pop(i))\n else:\n i += 1\n res += ''.join(curr)\n \n j = len(s)-1\n curr = []\n while j >= 0:\n if s[j] not in curr:\n curr.append(s.pop(j))\n j -= 1\n res += ''.join(curr)\n return res", "class Solution:\n def sortString(self, s: str) -> str:\n l=list(s)\n ope=list(s)\n s=''\n while(ope):\n temp=[]\n i=0\n temp2=list(set(ope))\n print('ji')\n while(ope and (ope) and temp2):\n n=min(temp2)\n \n if n not in temp:\n temp.append(n)\n ope.remove(n)\n temp2.remove(n)\n print(temp)\n print((i,len(ope)))\n print(temp2)\n \n \n i+=1\n s+=''.join(temp)\n temp=[]\n i=0\n temp2=list(set(ope))\n while( ope and len(ope) and temp2):\n n=max(temp2)\n if n not in temp:\n temp.append(n)\n ope.remove(n)\n temp2.remove(n)\n i+=1\n s+=''.join(temp)\n \n \n return s\n \n \n \n", "class Solution:\n def sortString(self, s: str) -> str:\n from collections import Counter\n counts, res, asc = Counter(s), [], True\n letters = sorted(set(s))\n while len(res) < len(s):\n for i in range(len(letters)):\n ch = letters[i if asc else ~i]\n if counts[ch] > 0:\n res.append(ch)\n counts[ch] -= 1\n asc = not asc\n return ''.join(res)", "class Solution:\n def sortString(self, s: str) -> str:\n d = {}\n for c in s:\n if c not in d:\n d[c] = 1\n else:\n d[c] += 1\n self.d = d\n self.re = ''\n \n print((self.d))\n while True:\n if self.d == {}:break\n smallest = min(self.d)\n \n if smallest:\n self.re += smallest\n if self.d[smallest] == 1: del self.d[smallest]\n else: self.d[smallest] -= 1\n else:\n break\n \n while True:\n nexts = None\n for key in self.d:\n if key > smallest:\n if nexts is None: nexts = key\n else:\n nexts = min(key, nexts)\n if nexts:\n if self.d[nexts] == 1: del self.d[nexts]\n else: self.d[nexts] -= 1\n self.re += nexts\n else:\n break\n smallest = nexts\n \n if self.d == {}:break\n\n biggest = max(self.d)\n \n if biggest:\n self.re += biggest\n if self.d[biggest] == 1: del self.d[biggest]\n else: self.d[biggest] -= 1\n else:\n break\n \n while True:\n nexts = None\n for key in self.d:\n if key < biggest:\n if nexts is None: nexts = key\n else:\n nexts = max(key, nexts)\n if nexts:\n if self.d[nexts] == 1: del self.d[nexts]\n else: self.d[nexts] -= 1 \n self.re += nexts\n else:\n break\n biggest = nexts\n \n print((self.d))\n return self.re\n \n \n", "class Solution:\n def sortString(self, s: str) -> str:\n new_list = []\n temp_list = list(s)\n\n while len(temp_list) > 0:\n\n if len(temp_list) == 0:\n break\n else: \n slist = sorted(temp_list)\n temp_list = []\n new_list.append(slist.pop(0))\n for i in slist:\n if ord(i) == ord(new_list[-1]):\n temp_list.append(i) \n if ord(i) > ord(new_list[-1]):\n new_list.append(i)\n \n \n if len(temp_list) == 0:\n break\n else: \n slist = sorted(temp_list, reverse = True)\n temp_list = []\n new_list.append(slist.pop(0))\n for i in slist:\n if ord(i) == ord(new_list[-1]):\n temp_list.append(i) \n if ord(i) < ord(new_list[-1]):\n new_list.append(i)\n \n return ''.join(new_list)", "class Solution:\n def sortString(self, s: str) -> str:\n x=sorted(s)\n res=''\n r=0\n while len(x)>0:\n if r==0:\n res+=x[0]\n x.remove(x[0])\n i=0\n while i<len(x):\n if x[i]>res[-1]:\n res+=x[i]\n x.remove(x[i])\n else:\n i+=1\n x=x[::-1]\n r=1\n elif r==1:\n res+=x[0]\n x.remove(x[0])\n i=0\n while i<len(x):\n if x[i]<res[-1]:\n res+=x[i]\n x.remove(x[i])\n else:\n i+=1\n x=x[::-1]\n r=0 \n return res\n \n", "class Solution:\n def sortString(self, s: str) -> str:\n\n ss = sorted(list(dict.fromkeys(s)))\n ssr = ss+ss[::-1]\n dic ={}\n final_s =''\n for i in ss:\n dic[i] = 0\n for i in s:\n dic[i]+=1\n for i in range(len(s)):\n\n for j in ssr:\n if dic[j]>0:\n final_s+=j\n dic[j]-=1\n # for x in ssr:\n # if dic[x]>0:\n # final_s+=x\n # dic[x]-=1\n return final_s\n \n \n \n", "class Solution:\n def sortString(self, s: str) -> str:\n\n ss = sorted(list(dict.fromkeys(s)))\n ssr = ss[::-1]\n dic ={}\n final_s =''\n for i in ss:\n dic[i] = 0\n for i in s:\n dic[i]+=1\n for i in range(len(s)):\n\n for j in ss:\n if dic[j]>0:\n final_s+=j\n dic[j]-=1\n for x in ssr:\n if dic[x]>0:\n final_s+=x\n dic[x]-=1\n return final_s\n \n \n \n", "class Solution:\n def sortString(self, s: str) -> str:\n output = []\n temp = list(s)\n\n while len(temp)>0:\n temp.sort()\n output.append(temp[0])\n temp.remove(temp[0])\n for e in temp:\n if e>output[-1]:\n output.append(e)\n temp[temp.index(e)] = ''\n temp = [e for e in temp if e]\n\n if len(temp)==0:\n break\n temp.reverse()\n output.append(temp[0])\n temp.remove(temp[0])\n for e in temp:\n if e<output[-1]:\n output.append(e)\n temp[temp.index(e)] = ''\n temp = [e for e in temp if e]\n\n print(output)\n\n return ''.join(output)", "class Solution:\n def sortString(self, s: str) -> str:\n output = []\n temp = list(s)\n dump = []\n\n while len(temp)>0:\n temp.sort()\n output.append(temp[0])\n temp.remove(temp[0])\n for e in temp:\n if e>output[-1]:\n output.append(e)\n temp[temp.index(e)] = ''\n temp = [e for e in temp if e]\n\n if len(temp)==0:\n break\n temp.reverse()\n output.append(temp[0])\n temp.remove(temp[0])\n for e in temp:\n if e<output[-1]:\n output.append(e)\n temp[temp.index(e)] = ''\n temp = [e for e in temp if e]\n\n print(output)\n\n return ''.join(output)", "class Solution:\n def sortString(self, s: str) -> str:\n from collections import Counter\n counts = Counter(s)\n characters = sorted(set(s))\n ch_len = len(characters)\n total = 0\n res = ''\n while total < len(s):\n for i in range(ch_len):\n ch = characters[i]\n if counts[ch] > 0:\n res += ch\n total += 1\n counts[ch] -= 1\n for i in range(ch_len)[::-1]:\n ch = characters[i]\n if counts[ch] > 0:\n res += ch\n total += 1\n counts[ch] -= 1\n return res\n \n", "class Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n ans = ''\n while s:\n for c in sorted(set(s)):\n ans += c\n s.remove(c)\n for c in sorted(set(s), reverse = True):\n ans += c\n s.remove(c)\n return ans\n", "class Solution:\n def sortString(self, s: str) -> str:\n from collections import Counter\n counts, res, asc = Counter(s), [], True\n letters = sorted(set(s))\n while len(res) < len(s):\n for i in range(len(letters)):\n ch = letters[i if asc else ~i]\n if counts[ch] > 0:\n res.append(ch)\n counts[ch] -= 1\n asc = not asc\n return ''.join(res)\n", "class Solution:\n def sortString(self, s: str) -> str:\n c = collections.Counter(''.join(sorted(s)))\n a = ''\n while c:\n stack = []\n for i in c.keys():\n if c[i] > 0:\n a = a+i[0]\n c[i] -= 1\n if c[i] > 0:\n stack.append(i)\n while stack:\n j = stack.pop()\n a = a+j[0]\n c[j] -= 1\n c += Counter() # erases all counts of 0\n return a"] | {"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 = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 10^4
text consists of lower case English letters only. | ["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(count_once, count_twice // 2)", "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n ret = []\n for i in 'ban':\n ret.append(text.count(i))\n for i in 'lo':\n ret.append(text.count(i) // 2)\n return min(ret)", "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n d = {'b':0,'a':0,'l':0,'o':0,'n':0}\n for char in text:\n if char in d:\n d[char]+=1\n d['l']//=2\n d['o']//=2\n return min(d.values())\n \n \n \n \n", "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n text = list(text)\n text2=['a', 'b', 'l', 'n', 'o']\n num1=[1,1,2,1,2]\n nums2=[]\n for j in range(len(text2)):\n k=len([number for number in text if number ==text2[j]])\n #print([number for number in text if number ==text2[j]])\n nums2.append(k)\n print(nums2)\n rt=[]\n for j in range(len(nums2)):\n rt.append(nums2[j]/num1[j])\n\n return int(min(rt))\n \n", "from collections import Counter\n\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n word = 'balloon'\n arr = []\n dic = Counter(list(text))\n for c in word:\n arr.append(dic[c]//word.count(c))\n return min(arr)", "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n count_balloon = 0\n \n count_b = 0\n count_a = 0\n count_l = 0\n count_o = 0\n count_n = 0\n \n for char in text: \n if(char == 'b'):\n count_b += 1\n elif(char == 'a'):\n count_a += 1\n elif(char == 'l'):\n count_l += 1\n elif(char == 'o'):\n count_o += 1\n elif(char == 'n'):\n count_n += 1\n\n count_balloon = min(count_b, count_a, count_l // 2, count_o // 2, count_n)\n return count_balloon\n \n", "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n return min(text.count('b'),text.count('a'),text.count('l')//2,text.count('o')//2,text.count('n'))\n"] | {"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 bit positions. For example, the two 1's in "1001" have a distance of 3.
Example 1:
Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
Example 2:
Input: n = 5
Output: 2
Explanation: 5 in binary is "101".
Example 3:
Input: n = 6
Output: 1
Explanation: 6 in binary is "110".
Example 4:
Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.
Example 5:
Input: n = 1
Output: 0
Constraints:
1 <= n <= 109 | ["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 & 1 and currDist != 0:\n currDist+=1\n n >>= 1\n return maxDist", "class Solution:\n def binaryGap(self, n: int) -> int:\n bins = ''\n maxv = 0\n i = 0\n pre = None\n while n > 0:\n if n % 2 == 1:\n if pre is not None:\n maxv = max(maxv,i-pre)\n pre = i\n n //= 2\n i += 1\n \n return maxv", "class Solution:\n def binaryGap(self, n: int) -> int:\n binary_string = bin(n)[2:]\n # The binary string has to begin with a 1, if n is a positive integer.\n\n left, right, current_distance, global_max = 0, 1, 1, 0\n\n print(binary_string)\n while right <= len(binary_string) - 1:\n print(left, right, current_distance, global_max)\n if binary_string[right] == '0':\n right += 1; current_distance += 1\n else:\n global_max = max(global_max, current_distance)\n left = right; right += 1; current_distance = 1\n \n return global_max", "class Solution:\n def binaryGap(self, N: int) -> int:\n bit_list = bin(N)[2:]\n stack = []\n dis = 0\n for b in bit_list:\n if not stack and b == '1':\n stack.append(b)\n elif stack and b == '0':\n stack.append(b)\n elif stack and b == '1':\n dis = max(dis, len(stack))\n stack = ['1']\n return dis\n \n", "class Solution:\n def binaryGap(self, n: int) -> int:\n if n == 0:\n return 0\n \n # Move RSB to first 1\n while n & 1 == 0:\n n = n >> 1\n \n global_max = local_max = 0\n while n > 0:\n # Reset if found another 1\n if n & 1 == 1:\n global_max = max(global_max, local_max)\n local_max = 1\n # Keep counting towards local max\n else:\n local_max += 1\n n = n >> 1\n \n return global_max\n \n \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 this word is capital if it has more than one letter, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note:
The input will be a non-empty word consisting of uppercase and lowercase latin letters. | ["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 return word.istitle()\n else:\n return False", "class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n if word.isupper():\n return True\n if word.islower():\n return True\n if word[0].isupper() and word[1:].islower():\n return True\n \n return False", "class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n for i, w in enumerate(word):\n is_cap = ord(w) < ord('a')\n if i == 0:\n if is_cap:\n first_cap = True\n keep_cap = False\n else:\n first_cap = False\n keep_cap = False\n else:\n if not first_cap and is_cap:\n return False\n if keep_cap and not is_cap:\n return False\n if not keep_cap and i > 1 and is_cap:\n return False\n if i == 1 and is_cap and first_cap:\n keep_cap = True\n return True\n \n", "class Solution:\n def detectCapitalUse(self, word):\n return word[1:]==word[1:].lower() or word==word.upper()", "class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n return word.islower() or word.isupper() or word.istitle()", "class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n return word == word.upper() or word == word.lower() or word == word[0].upper() + word[1::].lower()", "class Solution:\n def detectCapitalUse(self, word):\n \n return word[1:].islower() or word.isupper() or word.islower()\n \n \n \n \"\"\"old\n if word[0].isupper():\n if len(word)==1:return True\n if word[1].isupper():\n for i in range(2,len(word)):\n if word[i].islower():return False\n return True \n for i in range(2,len(word)):\n if word[i].isupper():return False\n return True\n for i in range(1,len(word)):\n if word[i].isupper():return False\n return True\n \"\"\"\n \n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n"] | {"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: The longest harmonious subsequence is [3,2,2,2,3].
Note:
The length of the input array will not exceed 20,000. | ["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 \n return ret\n \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 while first < last and char_list[first] not in vowels:\n first += 1\n while first < last and char_list[last] not in vowels:\n last -= 1\n if first >= last:\n break\n char_list[first], char_list[last] = char_list[last], char_list[first]\n first += 1\n last -=1\n return \"\".join(char_list)", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vow = set(list(\"aeiouAEIOU\"))\n sList = list(s)\n \n sPrt = 0\n ePrt = len(sList)-1\n \n while sPrt < ePrt:\n \n if sList[sPrt] in vow and sList[ePrt] in vow:\n sList[sPrt], sList[ePrt] = sList[ePrt], sList[sPrt]\n sPrt = sPrt +1\n ePrt = ePrt -1\n elif sList[sPrt] in vow:\n ePrt = ePrt -1\n elif sList[ePrt] in vow:\n sPrt = sPrt +1\n else:\n sPrt = sPrt +1\n ePrt = ePrt -1\n \n return \"\".join(sList)", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if not s or len(s) == 1:\n return s\n \n vowels = set('aeiouAEIOU')\n s = list(s)\n left = 0\n right = len(s) - 1\n while left < right:\n while left < right and s[left] not in vowels:\n left += 1\n while left < right and s[right] not in vowels:\n right -= 1\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n return ''.join(s)\n", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n \n if len(s) <= 1:\n return s\n arr = list(s)\n vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n \n left = 0\n right = len(s) - 1\n \n while right > left:\n \n \n while left < len(s) and s[left] not in vowels:\n left += 1\n \n while right > 0 and s[right] not in vowels:\n right -= 1\n \n if right <= left or right == 0 or left == len(s):\n break\n \n arr[left], arr[right] = arr[right], arr[left]\n right -= 1\n left += 1\n \n return ''.join(arr)\n \n \n \n \n \n \n", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vowel = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')\n \n start, end = 0, len(s) - 1\n lists = list(s)\n while start < end:\n if lists[start] in vowel:\n while lists[end] not in vowel:\n end -= 1\n if end < start:\n break\n temp = lists[start]\n lists[start] = lists[end]\n lists[end] = temp\n start += 1\n end -= 1\n else:\n start += 1\n return ''.join(lists)", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n yuanyin=['a','e','i','o','u','A','E','I','O','U']\n s=list(s)\n i=0\n j=len(s)-1\n while i<=j:\n while s[i] not in yuanyin and i<j:\n i+=1\n while s[j] not in yuanyin and i<j:\n j-=1\n temp=s[i]\n s[i]=s[j]\n s[j]=temp\n i+=1\n j-=1\n return ''.join(s)\n", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if not s:\n return s\n vowels=['a','e','i','o','u','A','E','I','O','U']\n left=0\n right=len(s)-1\n res=list(s)\n while left<right:\n while left<right and res[left] not in vowels:\n left+=1\n while right>left and res[right] not in vowels:\n right-=1\n res[left],res[right]=res[right],res[left]\n left+=1\n right-=1\n return ''.join(res)\n \n \n \n \n", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vowels = 'aeiouAEIOU'\n s = list(s)\n l = len(s)\n p1,p2 = 0,l-1\n while p1<p2:\n if s[p1] in vowels and s[p2] in vowels:\n s[p1],s[p2] = s[p2],s[p1]\n p1+=1\n p2-=1\n elif s[p1] not in vowels:\n p1+=1\n elif s[p2] not in vowels:\n p2-=1\n return ''.join(s)\n", "class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if not s:\n return s\n vowels=['a','e','i','o','u','A','E','I','O','U']\n left=0\n right=len(s)-1\n res=[s[0]]*len(s)\n while left<right:\n if s[left] in vowels and s[right] in vowels:\n res[left],res[right]=s[right],s[left]\n left+=1\n right-=1\n else:\n if s[left] not in vowels:\n res[left]=s[left]\n left+=1\n if s[right] not in vowels:\n res[right]=s[right]\n right-=1\n if left==right:\n res[left]=s[left]\n return ''.join(res)\n \n \n \n \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"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7. | ["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.count(x) >= 3 :\n re += s.count(x)-1\n flag =True\n elif s.count(x) == 1:\n flag =True\n if flag == True :\n re += 1\n return re\n \n", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n dict = {}\n for w in s:\n if w not in dict:\n dict[w] = 1\n else:\n dict[w] += 1\n f = 0\n rlen = 0\n for w in dict:\n if not dict[w]%2:\n rlen += dict[w]\n else:\n if not f:\n rlen += 1\n rlen += dict[w] - 1\n f = 1\n return rlen", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n c = {}\n cnt,flag = 0,0\n for i in s:\n c[i] = c.get(i, 0) + 1\n for i in c:\n cnt += (c[i]//2)*2\n if c[i]%2 != 0:\n flag = 1\n return cnt+flag", "class Solution: \n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n tmp = [False] * 58\n res = 0\n for x in s :\n t = ord(x) - 65\n if tmp[t] :\n res += 2\n tmp[t] = not tmp[t]\n if res != len(s) :\n res += 1 \n return res", "class Solution:\n def longestPalindrome(self, s):\n \n l = list(s)\n result = 0\n \n for x in set(s):\n x_count = l.count(x)\n if x_count % 2 == 0:\n result += x_count\n else:\n result += x_count-1\n \n if len(l) > result:\n result += 1\n \n return result", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n base, extra, result = {}, 0, 0\n for letter in s:\n if letter in base:\n base[letter] += 1\n else:\n base[letter] = 1\n for value in base.values():\n if extra == 0 and value % 2 == 1:\n extra += 1\n result += value // 2 * 2\n return result + extra", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n dic = {}\n for ss in s:\n dic[ss] = dic.get(ss, 0) + 1\n \n res = 0\n for _, value in list(dic.items()):\n res += (value//2)*2\n \n \n if res < len(s):\n res += 1\n \n return res\n \n", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n dic ={}\n max_odd = 0\n for i in s :\n if i in dic :\n dic[i] += 1\n else :\n dic[i] = 1\n \n ans = 0\n single = 0\n for c in dic:\n if dic[c] % 2 == 0 :\n ans += dic[c]\n else :\n ans += dic[c] - 1\n single = 1\n \n return ans + single\n \n", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n counter = {}\n longest = 0\n for char in s:\n counter[char] = counter.get(char,0) + 1\n for key,val in counter.items():\n if val%2 == 0:\n longest += val\n else:\n longest += val -1\n if longest < len(s):\n longest += 1\n return longest", "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count_map, has_odd, ans = {}, 0, 0\n \n for c in s:\n try:\n count_map[c] += 1\n except KeyError:\n count_map[c] = 1\n \n for count in list(count_map.values()):\n if ans % 2 != 0 and count % 2 != 0:\n ans += count - 1\n else:\n ans += count\n \n return ans\n"] | {"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 its order.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: String is already palindrome
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 1000
s only consists of letters 'a' and 'b' | ["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 return 2", "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n if not s: return 0\n if s == s[::-1]: return 1\n return 2", "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n \n if s == '':\n return 0\n elif s == s[::-1]:\n return 1\n else:\n return 2", "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n if not s:\n return 0\n if s == s[::-1]:\n return 1\n else:\n return 2\n \n", "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n if not s:\n return 0\n return 1 if s == s[::-1] else 2\n", "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n if not s:\n return 0\n elif s == s[::-1]:\n return 1\n else:\n return 2\n"] | {"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.
Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500
Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000)/1= 2000
Example 3:
Input: salary = [6000,5000,4000,3000,2000,1000]
Output: 3500.00000
Example 4:
Input: salary = [8000,9000,2000,3000,6000,1000]
Output: 4750.00000
Constraints:
3 <= salary.length <= 100
10^3 <= salary[i] <= 10^6
salary[i] is unique.
Answers within 10^-5 of the actual value will be accepted as correct. | ["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(salary) - 2\n for i in salary:\n if i > mx:\n mx = i\n if i < mn:\n mn = i\n print((mn , mx))\n return ( sum(salary) - (mn+mx) )/ n\n \n", "# class Solution:\n# def average(self, salary: List[int]) -> float:\n# maxs = 0\n# mins = 10000000 \n# sums = 0 \n# for s in salary:\n# sums += s\n# maxs = max(maxs, s)\n# mins = min(mins, s)\n# return (sums -maxs -mins) / (len(salary) - 2) # \u7528// \u9519\n \n# ###\u7528python\u5185\u7f6e\u51fd\u6570\u5feb\u4e00\u70b9\n# class Solution:\n# def average(self, salary: List[int]) -> float:\n# maxs = max(salary)\n# mins = min(salary) \n# sums = sum(salary)\n# return (sums -maxs -mins) / (len(salary) - 2) # \u7528// \u9519\n \n#copy other\nclass 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 minSalary = min(salary)\n maxSalary = max(salary)\n total = sum(salary)\n return (total - minSalary - maxSalary) / (len(salary) - 2)", "class Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n salary.pop()\n salary.pop(0)\n return sum(salary)/len(salary)", "class Solution:\n def average(self, salary: List[int]) -> float:\n minSalary = None\n maxSalary = None\n s = 0\n for n in salary:\n s = s + n\n if minSalary is None or n < minSalary:\n minSalary = n\n if maxSalary is None or n > maxSalary:\n maxSalary = n\n return (s - minSalary - maxSalary) * 1.0 / (len(salary) - 2)", "class Solution:\n def average(self, salary: List[int]) -> float:\n return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)", "class Solution:\n def average(self, salary: List[int]) -> float:\n s = salary[:]\n max_ind = 0\n min_ind = 0\n for i in range(1, len(s)):\n if s[max_ind] < s[i]:\n max_ind = i\n elif s[min_ind] > s[i]:\n min_ind = i\n print((max_ind, min_ind))\n if max_ind < min_ind:\n del s[max_ind]\n del s[min_ind - 1]\n else:\n del s[min_ind]\n del s[max_ind - 1]\n return sum(s) / len(s)\n", "class Solution:\n def average(self, arr: List[int]) -> float:\n return (sum(arr)-min(arr)-max(arr))/(len(arr)-2)", "class Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n newSalaryList = salary[1:-1]\n \n numSalaries = len(newSalaryList)\n \n return sum(newSalaryList) / numSalaries"] | {"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:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true | ["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 return False\n return True\n \n \n \n", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n n = [0] * 128\n for c in magazine:\n n[ord(c)] += 1\n for c in ransomNote:\n v = n[ord(c)]\n if v == 0:\n return False\n n[ord(c)] = v - 1\n \n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n return all(ransomNote.count(i)<=magazine.count(i) for i in set(ransomNote))", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n for i in set(ransomNote):\n if i not in set(magazine) or ransomNote.count(i)>magazine.count(i):\n return False\n return True\n", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n for i in set(ransomNote):\n if ransomNote.count(i) > magazine.count(i):\n return False\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n available_letters = dict()\n \n for c in magazine:\n if c in list(available_letters.keys()):\n available_letters[c] += 1\n else:\n available_letters[c] = 1\n \n for c in ransomNote:\n if c not in list(available_letters.keys()):\n return False\n else:\n available_letters[c] -= 1\n if available_letters[c] == 0:\n del available_letters[c]\n \n return True\n", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n for i in set(ransomNote):\n if ransomNote.count(i) > magazine.count(i):\n return False\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n for note in ransomNote:\n if note not in magazine:\n return False\n else:\n INDEX = magazine.index(note)\n magazine = magazine[:INDEX]+magazine[INDEX+1:]\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n a = set(ransomNote)\n b = set(magazine)\n for element in a:\n if ransomNote.count(element) > magazine.count(element):\n return False\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n from collections import Counter\n \n ransom = Counter(ransomNote)\n mag = Counter(magazine)\n \n return all(mag[letter] >= ransom[letter] for letter in ransom)\n", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n \n \n dic1 = collections.Counter(ransomNote)\n dic2 = collections.Counter(magazine)\n \n for key in dic1:\n if key not in dic2 or dic2[key] < dic1[key]:\n return False\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n a = collections.Counter(ransomNote)\n b = collections.Counter(magazine)\n for let in ransomNote:\n if(a[let] > b[let]):\n return False\n \n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n magazine = list(magazine)\n for letter in ransomNote:\n try:\n magazine.remove(letter)\n except ValueError:\n return False\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n rs=list(ransomNote)\n ms=list(magazine)\n for r in rs:\n if r not in ms:\n return False\n else:\n ms.remove(r)\n return True", "class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n r_map = {}\n for char in ransomNote:\n if char in r_map:\n r_map[char] += 1\n else:\n r_map[char] = 1\n m_map = {}\n for char in magazine:\n if char in m_map:\n m_map[char] += 1\n else:\n m_map[char] = 1\n for char, count in r_map.items():\n if char not in m_map:\n return False\n if count > m_map[char]:\n return False\n return True"] | {"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 destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.
Note:
1 <= stones.length <= 30
1 <= stones[i] <= 1000 | ["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 if y != x:\n stones.append(x-y)\n \n", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n ls = len(stones)\n if ls == 1:\n return stones[0]\n elif ls == 0:\n return 0\n stones.sort(reverse=True)\n while len(stones) > 1:\n stone1 = stones.pop(0)\n stone2 = stones.pop(0)\n if not stone1 == stone2:\n stone1 -= stone2\n stones.insert(0, stone1)\n stones.sort(reverse=True)\n try:\n return stones[0]\n except IndexError:\n return 0", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n while len(stones) > 1:\n firstMax,secMax =stones.pop(stones.index(max(stones))),stones.pop(stones.index(max(stones)))\n if firstMax - secMax != 0:\n stones.append(firstMax - secMax)\n if stones:\n return stones[0]\n else:\n return 0", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n \n \n \n while(len(stones) > 1):\n stones.sort(reverse=True)\n stones[0] = stones[0] - stones[1]\n del stones[1]\n \n if(len(stones) == 1):\n return stones[0]\n return 0\n", "from heapq import heappop, heappush, heapify \n\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n for i in range(len(stones)):\n stones[i] *= -1\n \n # min heapify\n heapify(stones)\n while(len(stones) > 1):\n # get the max\n max1 = heappop(stones)\n max2 = heappop(stones)\n if -max1 - (-max2) > 0:\n heappush(stones, -(-max1 - (-max2)))\n # remove the max\n # get the max2\n # remove the max2\n \n \n # add -(-max1 - (-max2)) to the stones\n \n if len(stones) == 1:\n return -stones[0]\n return 0\n", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n # while len(stones) > 1:\n # stones.sort()\n # num = stones.pop() - stones.pop()\n # stones.append(num)\n # return 0 if len(stones) == 0 else stones[0]\n \n heap = [-x for x in stones]\n heapq.heapify(heap)\n while len(heap) > 1 and heap[0] != 0:\n heapq.heappush(heap, heapq.heappop(heap) - heapq.heappop(heap))\n return - heap[0]", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n i = max(stones)\n weights = [0]*(i+1)\n for stone in stones:\n weights[stone] += 1\n current = 0\n while i > 0:\n if weights[i] != 0:\n if current == 0:\n current = i\n weights[i] -= 1\n else:\n current -= i\n weights[i] -= 1\n if current > i:\n i = current\n weights[current] += 1\n current = 0\n else:\n i -=1\n return current", "import queue\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n\n heap = queue.PriorityQueue()\n for stone in stones:\n heap.put(-stone)\n \n while heap.qsize() > 1:\n num1 = heap.get()\n num2 = heap.get()\n \n heap.put(num1-num2)\n \n return -heap.get()", "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n stones = [-s for s in stones]\n heapq.heapify(stones)\n while len(stones) > 1:\n s1 = heapq.heappop(stones)\n s2 = heapq.heappop(stones)\n if s1 != s2:\n s = s1-s2\n heapq.heappush(stones, s)\n \n return -stones.pop() if stones else 0\n", "class Solution:\n def lastStoneWeight(self, st: List[int]) -> int:\n for i in range(len(st)):\n st[i]*=-1\n heapq.heapify(st);\n while(len(st)>1):\n a,b=heapq.heappop(st),heapq.heappop(st);\n a*=-1;b*=-1\n if(b!=a):\n heapq.heappush(st,b-a)\n return -1*st[0] if len(st)==1 else 0"] | {"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 which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1 | ["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 if h == 1:\n return True\n elif h in former:\n return False\n n = h\n former.add(n)", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def next(n):\n res = 0\n while n > 0:\n n, lsd = n // 10, n % 10\n res += lsd * lsd\n return res\n \n seen = set()\n while True:\n seen.add(n)\n n = next(n)\n if n == 1:\n return True\n if n in seen:\n return False", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n memo = set()\n \n while n != 1:\n n = sum([int(digit)**2 for digit in str(n)])\n if n in memo:\n return False\n \n memo.add(n)\n \n return True", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n nums = set()\n while n != 1:\n if n in nums:\n return False\n \n nums.add(n)\n s = str(n)\n new_n = 0\n for c in s:\n new_n += int(c) * int(c) \n n = new_n\n \n return True", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n < 0:\n return False\n if n == 1:\n return True\n \n my_set = set()\n \n while n not in my_set:\n my_set.add(n)\n sq_sum = 0\n while n > 0:\n remain = n%10\n print(('r', remain))\n sq_sum += int(remain * remain)\n n = int(n/10)\n print(sq_sum)\n if sq_sum == 1:\n return True\n else:\n n = sq_sum\n \n \n return False\n \n", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n record={}\n add=0\n while add!=1:\n add=0\n for s in str(n):\n add+=int(s)**2\n n=add\n if add in list(record.keys()):\n return False\n else:\n record[add]=1\n \n return True\n", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n seen = {}\n while True:\n if str(n) in seen:\n return n == 1\n seen[str(n)] = True\n newN = 0\n while n > 0:\n n, mod = divmod(n, 10)\n newN += mod ** 2\n n = newN\n return False", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n seen = set()\n while n not in seen:\n seen.add(n)\n n = sum([int(d) ** 2 for d in str(n)])\n return n == 1", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n slow, fast = n, n\n while True:\n \tslow = self.getSquareSum(slow)\n \tfast = self.getSquareSum(fast)\n \tfast = self.getSquareSum(fast)\n \tif slow == fast:\n \t\tbreak;\n if slow == 1:\n \treturn True\n return False\n \n def getSquareSum(self, n):\n \treturn sum([int(i)**2 for i in str(n)]);", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n sol = set()\n while n not in sol:\n sol.add(n)\n n = sum([int(i) **2 for i in str(n)])\n \n \n return n == 1\n \n \n \n \n", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n ans = set()\n while n != 1:\n n = sum([int(i) ** 2 for i in str(n)])\n if n in ans:\n return False\n else:\n ans.add(n)\n print(ans)\n return True\n", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def isHappyHelper(n):\n squaresum = 0\n while n:\n n, remainder = divmod(n, 10)\n squaresum += remainder**2\n if squaresum == 1:\n return True\n elif squaresum in seenumbers:\n return False\n else:\n seenumbers.add(squaresum)\n return isHappyHelper(squaresum)\n \n if n <= 0:\n return False\n seenumbers = set()\n seenumbers.add(n)\n return isHappyHelper(n)\n", "class Solution(object):\n def isHappy(self, n):\n aset = set()\n while n != 1 and n not in aset:\n aset.add(n)\n sums = 0\n while n:\n digit = n % 10\n sums += digit * digit\n n = n // 10\n n = sums\n return n == 1", "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n count = {}\n \n while True:\n new_n = 0\n \n while n > 0:\n new_n = new_n + (n % 10)**2\n n = n // 10\n \n n = new_n\n \n if n == 1:\n return True\n \n if n in count:\n return False\n else:\n count[n] = 1"] | {"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\n ans += chr(64+p)\n n -= p\n a += 1\n \n return ans[::-1]", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n return \"\" if n == 0 else self.convertToTitle(int((n-1)/26)) + chr((n-1)%26+ord('A'))", "class Solution:\n def convertToTitle(self, num):\n res = []\n \n while num > 0:\n res.append(chr(ord('A') + (num - 1) % 26))\n num = (num - 1) // 26\n res.reverse()\n return \"\".join(res)\n \n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n alph='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n c=1\n clm=''\n while n>0:\n if (n%26)>0:\n clm=alph[(n%26)-1]+clm\n n=(n-(n%26))//26\n elif (n%26)==0:\n clm=alph[25]+clm\n n=(n-26)//26\n return clm", "class Solution:\n def convertToTitle(self, n):\n res = \"\"\n while n != 0:\n tmp = (n-1)%26\n c = chr(ord(\"A\") + tmp)\n res = c + res\n n = (n-1)//26\n return res\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n \n if n <= 26:\n return chr(n + 64)\n \n out = ''\n r = n\n while r >= 1:\n out += chr((r-1) % 26 + 65)\n r = (r - 1) // 26\n \n return out[::-1]", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n result = ''\n while n:\n n -= 1\n result = letters[n % 26] + result\n n //= 26\n \n return result", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n ret = []\n while n > 0:\n n -= 1\n tmp = n % 26\n n = int(n/26)\n ret.append(chr(ord('A') + tmp))\n return ''.join(reversed(ret))", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n dict_alpha = {0:'Z',1:'A', 2:'B', 3:'C', 4:'D', 5:'E', 6:'F', 7:'G', 8:'H', 9:'I', 10:'J', 11:'K', 12:'L', 13:'M', 14:'N', 15:'O', 16:'P', 17:'Q', 18:'R', 19:'S', 20:'T', 21:'U', 22:'V', 23:'W', 24:'X', 25:'Y'}\n output = []\n while n > 0: \n output.append(dict_alpha[n%26])\n n = (n-1) // 26 \n output.reverse()\n return(''.join(output))", "class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n if n == 0: \n return \"\"\n return self.convertToTitle( (n-1) // 26 ) + chr(ord('A') + (n-1) % 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 in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.
Example 3:
Input: startTime = [4], endTime = [4], queryTime = 5
Output: 0
Example 4:
Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
Output: 0
Example 5:
Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
Output: 5
Constraints:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000 | ["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, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n return sum([1 if startTime[i] <= queryTime and endTime[i] >= queryTime else 0 for i in range(len(startTime))])", "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n startTime = [i - queryTime for i in startTime]\n endTime = [i - queryTime for i in endTime]\n \n count = 0\n \n for i, j in zip(startTime, endTime):\n if (i <= 0) & (j >= 0):\n count += 1\n \n return count", "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n count = 0\n \n for start, end in zip(startTime, endTime):\n if queryTime >= start and queryTime <= end:\n count += 1\n \n return count\n", "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n count = 0\n for idx, x in enumerate(startTime):\n if (x <= queryTime <= endTime[idx]):\n count += 1\n return count", "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n count = 0\n \n for i, j in zip(startTime, endTime):\n if (i <= queryTime) & (j >= queryTime):\n count += 1\n \n return count", "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n count = 0\n for i in range(len(startTime)):\n if queryTime in list(range(startTime[i],endTime[i]+1)):\n count += 1\n return count"] | {"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 = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.
Follow up:
Can you solve it in O(N) time and O(1) space? | ["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 = self.getChar(S2, i2)\n if c1 != c2:\n return False\n return True\n \n \n def getChar(self, s, i):\n char = ''\n count = 0\n while i >= 0 and not char:\n if s[i] == '#':\n count += 1\n elif count == 0:\n char = s[i]\n else:\n count -= 1\n i -= 1\n return char, i\n\n", "class Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n def test(s):\n stack = []\n for l in s:\n if l == '#':\n if len(stack) != 0:\n stack.pop()\n else:\n stack.append(l)\n return ''.join(stack)\n \n return test(S) == test(T)", "class Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n i, j = len(S) - 1, len(T) - 1\n \n \n backS = backT = 0 \n \n while True:\n while i >= 0 and (backS or S[i] == '#'):\n backS += 1 if S[i] == '#' else -1\n i -= 1\n while j >= 0 and (backT or T[j] == '#'):\n backT += 1 if T[j] == '#' else -1\n j -= 1\n if not (i >= 0 and j >= 0 and S[i] == T[j]):\n return i == j == -1\n i, j = i - 1, j - 1", "class Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n i = len(S) - 1\n j = len(T) - 1\n \n skip_S = 0\n skip_T = 0\n \n while i >=0 or j >= 0:\n while i >=0 and (S[i] == '#' or skip_S > 0):\n if S[i] == '#':\n skip_S += 1\n else:\n skip_S -= 1\n i -= 1\n \n while j >=0 and (T[j] == '#' or skip_T > 0):\n if T[j] == '#':\n skip_T += 1\n else:\n skip_T -= 1\n j -= 1\n \n if i < 0 and j < 0:\n return True\n elif i >= 0 and j >= 0:\n if S[i] == T[j]:\n i -= 1\n j -= 1\n else:\n return False\n elif i >=0 or j >=0:\n return False\n return True", "class Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n \n s = []\n \n for i in S:\n if i == '#':\n if s:\n s.pop()\n \n else:\n s.append(i)\n \n t = []\n \n for i in T:\n if i == '#':\n if t:\n t.pop()\n \n else:\n t.append(i)\n \n \n if s == t:\n return True\n \n return False", "class Solution:\n \n\n\n def backspaceCompare(self, S: str, T: str) -> bool:\n \n def helper(S):\n r = ''\n erase = 0\n for s in S[-1::-1]:\n if s == '#':\n erase+=1\n elif s !='#' and erase == 0:\n r=s+r\n elif s !='#' and erase >=1:\n #r=s+r\n erase-=1\n \n \n return r\n \n return helper(S) == helper(T)\n \n \n"] | {"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 pivot indexes, you should return the left-most pivot index.
Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Note:
The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000]. | ["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 left += num\n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if(len(nums) == 0 ):\n return -1\n leftSum = sum(nums) \n rightSum = 0 \n \n for i in range(len(nums)):\n leftSum = leftSum - nums[i]\n if(rightSum == leftSum):\n return i\n rightSum = rightSum + nums[i]\n \n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ret = sum(nums)\n left = 0\n for k, v in enumerate(nums):\n if left * 2 + v == ret:\n return k\n left += v\n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left_sum = 0\n right_sum = sum(nums)\n for index in range(0, len(nums)):\n right_sum -= nums[index]\n if left_sum == right_sum:\n return index\n left_sum += nums[index]\n return -1\n \n", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = sum(nums)\n sum_num = n\n for i in range(len(nums)):\n n-=nums[i]\n if (sum_num-nums[i])/2 == n:\n return i\n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n tot = sum(nums)\n n = tot\n for i in range(0,len(nums)):\n n = n - nums[i]\n if (tot - nums[i])/2 == n:\n return i\n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n #nums = [-1,-1,-1,1,1,1]\n \n \n if len(nums) == 0:\n return -1\n \n \n if len(nums) == 1:\n return nums[0]\n \n \n left = 0\n right = 0\n \n for i in range(1,len(nums)):\n right += nums[i]\n \n \n if left == right:\n return 0\n \n \n for i in range(1,len(nums)):\n left += nums[i-1]\n right -= nums[i]\n \n #print(\"l=\" + str(left))\n #print(\"r=\" + str(right))\n \n \n if left == right:\n return i\n \n \n \n \n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums == []:\n return -1\n sum = 0\n for i in range(len(nums)):\n sum += nums[i]\n if nums[0] == sum:\n return 0\n left_sum = 0\n for i in range(len(nums)-1):\n left_sum += nums[i]\n if left_sum*2 == sum - nums[i+1]:\n return i+1\n if nums[len(nums)-1] == sum:\n return len(nums)-1\n return -1", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l = len(nums)\n if l < 3:\n return -1\n \n s = [0] * l\n s[0] = nums[0]\n for i in range(1, l):\n s[i] = s[i-1]+ nums[i]\n \n d=[0]* l\n d[l-1] = nums[l-1]\n for j in range(l-2,-1,-1):\n d[j] = d[j+1] + nums[j]\n \n for i in range(0, l):\n if(s[i] == d[i]):\n return i\n \n return -1 ", "class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return -1\n \n left = [0]\n for num in nums:\n left.append(left[-1] + num)\n right = [0]\n for i in range(len(nums)-1, -1, -1):\n right.append(right[-1] + nums[i])\n \n length = len(nums)\n for i in range(len(left)-1):\n if left[i] == right[length-i-1]:\n return i\n return -1"] | {"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", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Example 4:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R' | ["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 retVal += 1\n lCount = rCount = 0\n return retVal\n", "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n l_cnt = r_cnt = 0\n output = 0\n for i in range(len(s)):\n if s[i] == 'R':\n r_cnt += 1\n else:\n l_cnt += 1\n if l_cnt == r_cnt:\n output += 1\n return output\n", "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n r = 0\n l = 0\n result = 0\n for st in s:\n if st == 'R':\n r += 1\n else:\n l += 1\n if r > 0 and l > 0:\n if r == l:\n result += 1\n r, l = 0,0\n return result", "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n count1 = 0\n count2 = 0\n counter = 0\n for i in s:\n if i == 'R':\n \n count1 +=1\n else:\n \n count2 +=1\n if count1 == count2:\n \n counter +=1\n return counter", "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n n,c=0,0\n for v in s:\n if v=='R':\n n+=1\n else:\n n-=1\n if(n==0):\n c+=1\n return c"] | {"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'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff" | ["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 res.insert(0,nums[num%16])\n num=num//16\n n+=1\n s=\"\"\n for i in res:\n s+=i\n return s\n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num < 0:\n num = 2 ** 32 + num\n return hex(num)[2:]", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n '''\n s = []\n hexChar= ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']\n if num == 0:\n return '0'\n while num:\n s.append(hexChar[num % 16])\n num = num // 16\n return \"\".join(s[::-1])\n hex(int())\n hex(num & 0b)\n '''\n return '%x' % (num & 0xffffffff)\n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n ans = []\n dic = {10:\"a\", 11:\"b\", 12:\"c\", 13:\"d\", 14:\"e\", 15:\"f\"}\n if num == 0:\n return \"0\"\n if num < 0:\n num = num + 2**32\n \n while num > 0:\n digit = num % 16\n num //= 16\n if digit > 9 and digit < 16:\n digit = dic[digit]\n else:\n digit = str(digit)\n ans.append(digit)\n return \"\".join(ans[::-1])\n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num<0: num = 2**32 -1 - ~num\n if num ==0: return '0'\n s = \"\"\n dic = {10:\"a\", 11:\"b\", 12:\"c\", 13:\"d\", 14:\"e\", 15:\"f\"}\n for i in range(8,-1,-1):\n if int(num/(16**i)) > 0:\n if int(num/(16**i))<10: s = s + str(int(num/(16**i)))\n else:\n s = s + dic[int(num/(16**i))]\n num = num - int(num / (16 ** i))*(16**i)\n else:\n if len(s)>0: s = s+ '0'\n return s\n \n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num == 0:\n return \"0\"\n check = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']\n save = []\n num = (num + 4294967296) % 4294967296\n while num > 0:\n save.append(check[num % 16])\n num //= 16\n return \"\".join(save)[::-1]", "class Solution:\n def toHex(self, num):\n def toHexUnsigned(num):\n num_hex = []\n while num // 16 > 0:\n digit = num % 16\n if digit >= 10:\n num_hex.append(chr(digit-10+ord('a')))\n else:\n num_hex.append(str(digit))\n num = num // 16\n \n if num >= 10:\n num_hex.append(chr(num-10+ord('a')))\n elif num > 0:\n num_hex.append(str(num))\n \n return \"\".join(num_hex[::-1])\n \n if num == 0:\n return \"0\"\n if num < 0:\n return toHexUnsigned(2**32+num)\n else:\n return toHexUnsigned(num)\n \n", "class Solution(object):\n def toHex(self, num):\n if num == 0: return '0'\n if num < 0: num = num + 2**32 # convert negative to positive\n hexa = '0123456789abcdef' # based on 16\n r = ''\n while num:\n r = hexa[num%16] + r\n num = num // 16\n return r\n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num == 0:\n return '0'\n if num < 0:\n num = num + 2**32\n mapping = '0123456789abcdef'\n output = ''\n while num > 0:\n print(num)\n remainder = num % 16\n output = mapping[remainder] + output\n num = math.floor(num / 16)\n return output\n", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num==0: return '0'\n mp = '0123456789abcdef' # like a map\n ans = ''\n for i in range(8):\n n = num %16 # or n=num & 15, this means num & 1111b\n c = mp[n] # get the hex char \n ans=c+ans\n num = num >> 4 #num\u7684\u4e8c\u8fdb\u5236\u7f16\u7801\u53f3\u79fb4\u4f4d\n return ans.lstrip('0') #strip leading zeroes", "class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num == 0:\n return '0'\n \n hexKey = '0123456789abcdef'\n ans = ''\n \n for _ in range(8):\n ans = hexKey[num & 15] + ans\n num >>= 4\n \n return ans.lstrip('0')"] | {"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 solution using the divide and conquer approach, which is more subtle. | ["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_sum = sum(nums[i:j])\n # if temp_sum >= max_sum:\n # i_keep = i\n # j_keep = j\n # max_sum = temp_sum\n # elif i == j-1:\n # i += 1\n # j += 1\n # j += 1\n # return max_sum\n \n # brute force\n # max_sum = nums[0]\n # for i in range(len(nums)):\n # for j in range(i,len(nums)+1):\n # temp_sum = sum(nums[i:j])\n # if temp_sum > max_sum and i != j:\n # max_sum = temp_sum\n # return max_sum\n \n # outer loop only\n max_sum = csum = nums[0]\n for num in nums[1:]:\n if num >= csum + num:\n csum = num\n else:\n csum += num\n \n if csum > max_sum:\n max_sum = csum\n \n return max_sum\n \n \n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return None\n cur_sum = 0\n max_sum = nums[0]\n for n in nums:\n if cur_sum < 0:\n cur_sum = n\n else:\n cur_sum += n\n if cur_sum > max_sum:\n max_sum = cur_sum\n return max_sum", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n current = 0\n maxsum = -9**99\n \n for i in range(len(nums)):\n if current < 0: current = 0\n current += nums[i]\n maxsum = max(maxsum, current)\n return maxsum", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n current, the_max = [nums[0]]*2\n for num in nums[1:]:\n current = max(num, current + num)\n the_max = max(current, the_max)\n return the_max", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n res = curr = nums[0] \n for i in range(1, len(nums)):\n curr = max((curr + nums[i], nums[i]))\n res = max((res, curr))\n return res\n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, curr = nums[0], nums[0]\n i = 1\n while i < len(nums) :\n curr = max(nums[i], curr+nums[i]) \n result = max(curr, result)\n i += 1 \n return result", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maxSum = maxGlobalSum = nums[0]\n \n for i in range(1, len(nums)):\n if nums[i] > nums[i] + maxSum:\n maxSum = nums[i]\n else:\n maxSum += nums[i]\n \t\t\n if maxSum > maxGlobalSum:\n maxGlobalSum = maxSum\n \n return maxGlobalSum\n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return None\n \n result = nums[0]\n lastMax = nums[0]\n \n for i in range(1, len(nums)):\n lastMax = lastMax + nums[i] if lastMax + nums[i] >= nums[i] else nums[i]\n result = lastMax if lastMax > result else result\n \n return result\n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n else:\n res = 0\n count = 0\n for i in range(len(nums)):\n count += nums[i]\n if count < 0:\n count = 0\n else:\n res = max(res,count)\n if res == 0:\n return max(nums)\n return res", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if all(n < 0 for n in nums):\n return max(nums)\n i = 0\n a = 0\n maxsum = 0\n while i < len(nums):\n b = c = 0\n while i < len(nums) and nums[i] <= 0:\n b += nums[i]\n i += 1\n while i < len(nums) and nums[i] >= 0:\n c += nums[i]\n i += 1\n a = max(a + b + c, c)\n maxsum = max(maxsum, a)\n return maxsum", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n \n curSum = maxSum = nums[0]\n \n for num in nums[1:]:\n curSum = max(num, curSum + num)\n maxSum = max(maxSum, curSum)\n \n return maxSum\n \n \n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # [-2,1,-3,-5]\n curSum = maxSum = nums[0]\n for num in nums[1:]:\n curSum = max(num, curSum + num) # start a new array or use added up array num[1]=1 or num[0]+num[1]=-1\n maxSum = max(maxSum, curSum) # update the max prior = 1 or cursum 1-3-5\n \n return maxSum\n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n best = 0\n total = 0\n for n in nums:\n if total+n<0:\n total=0\n else:\n total+=n\n print(total)\n \n \n best=max(total,best)\n if max(nums)<0:\n return max(nums)\n return best\n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_sum = nums[0]\n sum_list = [0] * len(nums)\n sum_list[0] = max_sum\n for i in range(1, len(nums)):\n sum_list[i] = max(nums[i], sum_list[i-1] + nums[i])\n max_sum = max(max_sum, sum_list[i])\n return max_sum\n \n", "class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n sumlist = [0] * (len(nums) + 1)\n sumlist[0] = 0\n sumMin = 0\n globalMax = nums[0]\n for i in range(1, len(nums) + 1):\n sumlist[i] = sumlist[i - 1] + nums[i - 1]\n print(sumlist[i])\n globalMax = max(sumlist[i] - sumMin, globalMax)\n sumMin = min(sumMin, sumlist[i])\n \n return globalMax", "class Solution:\n \n \n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n def dac (X):\n if len(X) == 1:\n return X[0], X[0], X[0], X[0] # l, r, m, s\n \n n = len(X)\n nby2 = n // 2\n A = X[:nby2]\n B = X[nby2:]\n l1, r1, m1, s1 = dac(A)\n l2, r2, m2, s2 = dac(B)\n l = max(l1, s1 + l2)\n r = max(r2, s2 + r1)\n m = max(m1, m2, r1 + l2)\n s = s1 + s2\n return l, r, m, s\n \n return dac(nums)[2]\n \n"] | {"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 return False\n else:\n hasOne = True\n \n n = n >> 1\n \n return hasOne", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n # so let's take a look at what it means to be a power of two\n # 2^2 = 4 = 0100 | Now note when we subtract one | 2^2 - 1 = 3 = 0011 \n # 2^3 = 8 = 1000 | Now note when we subtract one | 2^3 - 1 = 7 = 0111\n # Now note if we do n AND n-1, we should always get 0 | 1000 & 0111 = 0000 = 0\n return n>0 and not (n & n-1)\n # This holds true for all powers of 2. However note if we used 0 & anything else, it would show to be a power of 2.\n # To fix this we can add another clause v & (earlier clause) or we can simply check if value is greater than 0.\n \n \n", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n == 0:\n return False\n if n < 0:\n n **= -1\n \n pow_ = True\n while n and pow_: \n if n == 1:\n return True\n pow_ = not(n % 2)\n n //= 2\n return pow_\n \n \n", "class Solution:\n def isPowerOfTwo(self, n):\n if n <= 0: return False\n if n == 1: return True\n while n > 1:\n if n & 1: return False\n n >>= 1\n else: return True\n", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n return True if n & (n-1) == 0 and n != 0 else False\n", "class Solution:\n import math\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n<1:\n return False\n b = str(bin(n))\n b = b.replace('0b','')\n b = b.replace('0','')\n \n return len(b)==1", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n # if n == 0:\n # return False\n # while n % 2 == 0:\n # n = n // 2\n \n # if n == 1:\n # return True\n # return False\n \n return n > 0 and 1073741824 % n == 0\n", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n return n > 0 and n & (n - 1) == 0", "class Solution:\n def isPowerOfTwo(self, n):\n return n > 0 == 2**32 % n\n", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return n > 0 and not (n & (n - 1))", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return n != 0 and not n & (n - 1)", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n if n < 0:\n return False\n \n if bin(n).replace('0b','').count('1') == 1:\n return True\n return False", "class Solution:\n def isPowerOfTwo(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return n>0 and (not n&(n-1))"] | {"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 \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n res = 0\n for i in s:\n res = res*26 + ord(i) - ord('A')+1\n return res", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n res = 0\n for i in s:\n res *= 26\n res += ord(i) - ord(\"A\") + 1\n return res \n \n \n \n \n", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = 0\n for char in s:\n result *= 26\n result += ord(char) - ord('A') + 1\n return result", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return 0 if len(s) == 0 else ord(s[-1]) - ord('A') + 1 + 26 * self.titleToNumber(s[:len(s)-1])", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if s == \"\":\n return 0\n return self.titleToNumber(s[:-1])*26 + ord(s[-1]) - ord('A') + 1", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n s = s[::-1]\n sum = 0\n for exp, char in enumerate(s):\n sum += (ord(char) - 65 + 1) * (26 ** exp)\n return sum\n \n", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n s = [ord(c)-64 for c in s]\n result = 0\n x = len(s) - 1\n for i in range(0, len(s)):\n result += (s[x - i] * (26**i))\n return result", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n val = ord('A')\n length = len(s)\n sum = 0\n for i in range(length):\n sum = sum + (ord(s[i])-val+1)* 26**(length-1-i)\n return sum", "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \n \n \"\"\"\n s = s[::-1]\n res = 0\n for exp, c in enumerate(s):\n res += (ord(c)-65 + 1) * (26 ** exp)\n return res"] | {"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]
Output: false
Example 2:
Input: [3,5,5]
Output: false
Example 3:
Input: [0,3,2,1]
Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000 | ["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 return False\n if n < curr:\n is_up = False\n curr = n\n if n > curr:\n if is_up:\n curr = n\n else:\n return False\n return not is_up\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n isIncreasing = True\n i = 1\n n = len(A)\n if n < 3:\n return False\n if A[1] <= A[0]:\n return False\n while i < n:\n if isIncreasing and A[i-1] < A[i]:\n i += 1\n continue\n elif A[i] < A[i-1]:\n isIncreasing = False\n i += 1\n continue\n else:\n return False\n if A[-1] >= A[-2]:\n return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n arr = A\n if len(arr) < 3:\n return False\n if arr[0] > arr[1]:\n return False\n if arr[-1] > arr[-2]:\n return False\n \n peek = None\n for i in range(1, len(arr)-1):\n if arr[i] > arr[i+1]:\n peek = i\n if peek and arr[i] < arr[i+1]:\n return False\n if arr[i] == arr[i+1] or arr[i] == arr[i-1]:\n return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n dec = 0\n n = len(A)\n if n < 3:\n return False\n else:\n for i in range(n):\n if i!= 0 and A[i] == A[i-1]:\n return False\n elif i == 0 and A[i] > A[i+1]:\n return False\n elif dec == 1 and A[i] > A[i-1]:\n return False\n elif i != 0 and dec == 0 and A[i] < A[i-1]:\n dec = 1\n elif i == (n - 1) and dec == 0:\n return False\n return True\n \n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool: \n N = len(A)\n if N < 3:\n return False\n i = 0\n while i < N -1:\n if(A[i]< A[i + 1]):\n i+=1\n print(i)\n else:\n break\n if (i==0 or i==N-1):\n print('***')\n return False \n while (i<N-1):\n if (A[i] > A[i+1]):\n i += 1\n print(i)\n else:\n break\n if(i==N-1):\n return True\n else:\n print('1111')\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n length = len(A)\n if length < 3: return False\n \n prev = A[0]\n peak = -1\n \n for i in range (1, length):\n print(A[i])\n if A[i] > prev:\n if peak != -1:\n return False\n elif A[i] == prev:\n return False\n else:\n if i == 1: \n return False\n peak = A[i]\n \n prev = A[i]\n \n print(peak)\n return True if peak != -1 else False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool: \n N = len(A)\n if N < 3:\n return False\n i = 0\n while i < N -1:\n if(A[i]< A[i + 1]):\n i+=1\n print(i)\n else:\n break\n if (i==0 or i==N-1):\n return False \n while (i<N-1):\n if (A[i] > A[i+1]):\n i += 1\n print(i)\n else:\n break\n if(i==N-1):\n return True\n else:\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool: \n N = len(A)\n if N < 3:\n return False\n i = 0\n while i < N -1:\n if A[i] < A[i + 1]:\n i += 1\n print(i)\n else:\n break\n if i == 0 or i == N - 1:\n print('***')\n return False \n while i < N - 1:\n if A[i] > A[i + 1]:\n i += 1\n print(i)\n else:\n break\n if(i==N-1):\n return True\n else:\n print('1111')\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n \n start = 0\n finish = len(A) \n \n \n \n print((len(A)))\n \n for i in range(0, len(A)-1):\n print(('i', i))\n \n \n if A[i] == A[i + 1] :\n\n return False\n \n elif A[i] > A[i+1]: \n start = i\n print(('else1', start))\n break\n\n \n \n for j in range(0, len(A)-1):\n print(('j', j)) \n \n \n if A[len(A) - 1 - j] == A[len(A) - 2 - j] :\n \n return False\n \n \n elif A[len(A) - 1 - j] > A[len(A) - 2 - j]:\n print(('break2' , len(A) - 1 - j, len(A) - 2 - j, A[len(A) - 1 - j], A[len(A) - 2 - j] ))\n finish = len(A) - 1 - j\n break\n \n \n \n \n \n print(('s, f', start, finish)) \n return (start == finish and start > 0 and finish < len(A) )\n \n\n", "class Solution:\n \n def __init__(self):\n self.f = True\n \n def impl(self, arr, i, incr):\n self.f = incr\n if (i + 1 >= len(arr)):\n return True\n\n if (arr[i + 1] > arr[i] and not incr):\n return False\n\n elif (arr[i + 1] < arr[i] and incr):\n incr = False\n\n elif(arr[i + 1] == arr[i]):\n return False\n\n return self.impl(arr, i + 1, incr)\n\n def validMountainArray(self, A) -> bool:\n if (A == None or len(A) <= 2):\n return False\n if(A[1]<A[0]):\n return False\n self.f = True\n result = self.impl(A, 0, True)\n if(self.f):\n return False\n return result\n \n \n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if not A or len(A)< 3:\n return False\n \n l, r = 0, len(A) -1\n while l<r:\n if A[l] < A[l+1] and A[r-1] > A[r]:\n l += 1\n r -= 1\n elif A[l] < A[l+1]:\n l += 1\n elif A[r-1] > A[r]:\n r -= 1\n else:\n return False\n \n print(l, r)\n \n if l == r and l !=0 and r!= len(A)-1:\n return True\n else:\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n i=1\n N=len(A)\n if N<3:\n return False\n while(i<N and A[i]>A[i-1]):\n i +=1\n if(i==1 or i==N):\n return False\n while(i<N and A[i]<A[i-1]):\n i +=1\n return i==N ", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n \n N = len(A)\n i = 0\n\n # walk up\n while i+1 < N and A[i] < A[i+1]:\n i += 1\n\n # peak can't be first or last\n if i == 0 or i == N-1:\n return False\n\n # walk down\n while i+1 < N and A[i] > A[i+1]:\n i += 1\n\n return i == N-1\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n i = 0\n \n #walk up\n while i+1 < len(A) and A[i] < A[i+1]:\n i += 1\n \n #peak can't be first or last\n if i == 0 or i == len(A)-1:\n return False\n \n while i+1 < len(A) and A[i] > A[i+1]:\n i += 1\n \n return i == len(A) - 1\n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n t=0\n c1,c2 =0,0\n for i in range(1,len(A)-1):\n if A[i] == A[i+1]:\n return False\n break\n elif A[i-1] < A[i] < A[i+1] or A[i-1] > A[i] > A[i+1] or A[i-1] < A[i] > A[i+1]:\n t +=1\n if A[i-1] < A[i] < A[i+1]:\n c1+=1\n if A[i-1] > A[i] > A[i+1]:\n c2+=1\n if t ==len(A)-2 and c1< len(A)-2 and c2< len(A)-2:\n return True\n else:\n return False\n \n", "#19\nclass Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n nprev = A[0]\n for i in range(1,len(A)):\n if A[i] <= nprev:\n nprev = A[i-1]\n start = i \n break\n nprev = A[i]\n if i == len(A)-1:\n return False\n \n for i in range(start,len(A)):\n if A[i] >= nprev:\n return False\n nprev = A[i]\n if start == 1 and i == len(A)- 1:\n return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n \n maxIndex = A.index(max(A))\n \n if (maxIndex == len(A)-1) or (maxIndex == 0):\n return False\n \n for i in range(maxIndex):\n if A[i] >= A[i+1]:\n return False\n \n for i in range(maxIndex, len(A)-1):\n if A[i] <= A[i+1]:\n return False\n \n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n increasing=True\n prev = -1\n if len(A) < 3: return False\n for idx,i in enumerate(A):\n print(prev, i , increasing)\n if i == prev: return False\n if increasing:\n if i<prev:\n increasing = False\n if idx==1: return False\n else:\n if i>prev:\n return False\n prev = i\n if increasing==True: return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n i = 0\n while i + 1 < len(A) and A[i + 1] > A[i]:\n i += 1\n if i == 0 or i == len(A) - 1:\n return False\n \n while i + 1 < len(A) and A[i + 1] < A[i]:\n i += 1\n return i == len(A) - 1", "class Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n i = 0\n l = len(arr)\n while i+1 < l and arr[i] < arr[i+1]:\n i += 1\n\n if i == 0 or i == l-1:\n return False\n\n while i+1 < l and arr[i] > arr[i+1]:\n i += 1\n\n return i == l-1", "class Solution(object):\n def validMountainArray(self, A):\n N = len(A)\n i = 0\n\n # walk up\n while i+1 < N and A[i] < A[i+1]:\n i += 1\n\n # peak can't be first or last\n if i == 0 or i == N-1:\n return False\n\n # walk down\n while i+1 < N and A[i] > A[i+1]:\n i += 1\n\n return i == N-1\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n i = 0\n N = len(A)\n while i < N and i+1<N and A[i] < A[i+1]:\n i+=1\n if i ==0 or i ==N-1:\n return False\n while i<N and i+1<N and A[i] > A[i+1]:\n i+=1\n if i==N-1:\n return True\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n # find max\n # everything to the left should be strictly decreasing \n # everything to the right should be decreasing \n m = (0,0)\n for i in range(0, len(A)):\n if A[i] > m[1]:\n m = (i, A[i])\n \n if m[0] == 0 or m[0] == len(A)-1:\n return False\n for i in range(0, m[0]-1):\n if A[i] >= A[i+1]:\n return False\n for i in range(m[0], len(A)-1):\n if A[i] <= A[i+1]:\n return False\n return True", "class Solution:\n def walkUp(self, A: List[int]) -> int:\n for i, step in enumerate(A[:-1]):\n if A[i] >= A[i+1]:\n return i\n return len(A)\n \n def walkDown(self, A: List[int], top: int) -> bool:\n for i, step in enumerate(A[top:-1], start=top):\n if A[i] <= A[i+1]:\n return False\n return True\n \n def validMountainArray(self, A: List[int]) -> bool:\n top = self.walkUp(A)\n if top == 0 or top == len(A):\n return False\n return self.walkDown(A, top)\n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n switch = 0\n if A[0] > A[1]:\n return False\n for i in range(2, len(A)):\n if A[i] == A[i - 1]:\n return False\n if switch == 0 and A[i] < A[i - 1]:\n switch = 1\n elif switch == 1 and A[i] > A[i - 1]:\n return False\n if switch == 0:\n return False\n return True\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n\n N = len(A)-1\n reached = False\n for i in range(N):\n if A[i] == A[i+1]:\n return False\n \n if not reached:\n if A[i] > A[i+1]:\n if i == 0:\n return False\n reached = True\n else:\n if A[i] < A[i+1]:\n return False\n return reached", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if(len(A) >= 3):\n peak = max(A)\n if(A.count(peak) == 1):\n peakInd = A.index(peak)\n incArr = A[:peakInd]\n decArr = A[peakInd+1:]\n if(len(incArr) > 0 and len(decArr) > 0):\n for i in range(1,len(incArr)): \n if(incArr[i]<= incArr[i-1]):\n return False\n for d in range(0,len(decArr)-1):\n if(decArr[d]<= decArr[d+1]):\n return False \n return True\n else:\n return False\n else:\n return False\n else:\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n strict_inc = False\n strict_dec = False\n if len(A) > 2:\n for i in range(1,len(A)):\n if A[i] > A[i-1]:\n if strict_dec:\n return False\n strict_inc = True\n \n elif A[i] < A[i-1]:\n strict_dec = True\n else:\n return False\n if strict_inc and strict_dec:\n return True\n else:\n return False\n else:\n return False\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n \n if len(A) in [0,1,2] :\n return False\n max_ele = max(A)\n if A.count(max_ele) > 1 :\n return False\n \n index = A.index(max_ele)\n \n if index == len(A) - 1 or index == 0:\n return False\n \n for i in range(0,index) :\n print(('values',A[i],A[i+1]))\n print(('index',i,i+1))\n if not(A[i] < A[i+1]) :\n print('trig1')\n return False\n \n for i in range(len(A)-1,index+1,-1) :\n print('hi')\n if not(A[i] < A[i-1]) :\n print('trig2')\n return False\n return True\n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n i, j = 0, len(A) - 1\n while i < j:\n if A[i] < A[i + 1]:\n i += 1\n if A[j] < A[j - 1]:\n j -= 1\n elif i + 1 >= len(A) or A[i] >= A[i + 1]:\n break\n return i == j and 0 < i < len(A) - 1", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n \n if len(A) < 3:\n return False\n \n diffs = [A[i+1] - A[i] for i in range(len(A)-1)]\n \n if 0 in diffs or diffs[0] < 0:\n return False\n \n peak = False\n for i in range(len(diffs)-1):\n if diffs[i+1]/abs(diffs[i+1]) != diffs[i]/abs(diffs[i]):\n if peak == False:\n peak = True\n else:\n return False\n return peak #catches the case where no peak\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3:\n return False\n \n for i in range(len(A)-1):\n if A[i] >= A[i+1]:\n break\n for j in range(-1, -len(A), -1):\n if A[j] >= A[j-1]:\n break\n return i == len(A) + j", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n n = len(A)\n if n < 3:\n return False\n changes = 0\n is_increasing = False\n is_decreasing = False\n for i in range(0, n-1):\n if changes == 0: \n if A[i] > A[i+1]:\n changes += 1\n is_decreasing = True\n elif A[i] == A[i+1]:\n changes += 1\n else:\n is_increasing = True\n elif changes == 1:\n if A[i] <= A[i+1]:\n changes += 1\n else:\n is_decreasing = True\n else:\n return False\n return changes < 2 and is_decreasing and is_increasing\n \n \n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n arr=A\n i=1\n while i<len(arr):\n if arr[i-1]<arr[i]:\n i+=1\n else:\n break\n if i==1 or i==len(arr):\n return False\n while i<len(arr):\n if arr[i-1]>arr[i]:\n i+=1\n else:\n return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) < 3: return False\n up = True\n for i in range(1, len(A)):\n if A[i] == A[i-1]:\n # flat \n return False\n if up:\n # going up\n if A[i] < A[i-1]:\n # going down\n if i == 1:\n # starting down is not valid\n return False\n up = False\n else:\n # going down\n if A[i] > A[i-1]:\n # going back up after down is not mountain\n return False\n return not up", "class Solution(object):\n def validMountainArray(self, A):\n N = len(A)\n i = 0\n\n # walk up\n while i+1 < N and A[i] < A[i+1]:\n i += 1\n\n # peak can't be first or last\n if i == 0 or i == N-1:\n return False\n\n # walk down\n while i+1 < N and A[i] > A[i+1]:\n i += 1\n\n return i == N-1", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n \n if len(A) < 3:\n return False\n \n if A[0] > A[1]:\n return False\n \n decreasing = False\n last = A.pop(0)\n \n while A:\n \n new = A.pop(0)\n print((new, last, decreasing))\n if new == last:\n return False\n \n if new > last and decreasing:\n print('early')\n return False\n \n if new < last and not decreasing:\n decreasing = True\n \n last = new\n \n return decreasing\n \n \n \n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n n = len(A)\n if n < 3: return False\n i = 0\n \n while i < n-1 and A[i] < A[i+1]:\n i += 1\n \n if i == 0 or i == n-1:\n # peak at beginning or end\n return False\n \n while i < n-1 and A[i] > A[i+1]:\n i += 1\n \n if i != n-1:\n return False\n return True", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n passedPeak = False\n \n if len(A) <= 2 or A[0] > A[1]: return False\n \n for i in range(len(A)-1):\n if A[i] == A[i+1]: return False\n\n if passedPeak == True and A[i] < A[i+1]: return False\n \n if passedPeak == False and A[i] > A[i+1]:\n passedPeak = True\n\n if passedPeak: return True\n else: return False\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n inflection = None\n if len(A) > 3:\n for i in range(0,len(A)- 1):\n if inflection is not None:\n if A[i] < A[i+1]:\n return False\n else:\n if A[i] > A[i+1]:\n inflection = i\n \n print(inflection,A[0:inflection],A[inflection:])\n \n if inflection is not None:\n if len(A[0:inflection]) and len(A[inflection:]):\n if len(set(A[0:inflection]))+len(set(A[inflection:])) == len(A):\n return True\n else:\n return False\n else:\n return False\n print(set(A[0:inflection]),len(A[0:inflection]),set(A[inflection:]),len(A[inflection:]))\n return False\n else:\n return False\n elif len(A) == 3:\n if A[0] < A[1] and A[1] > A[2]:\n return True\n else:\n return False\n else:\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n \n N = len(A)-1\n i = 0\n\n # walk up\n while i < N and A[i] < A[i+1]:\n i += 1\n\n # peak can't be first or last\n if i == 0 or i == N:\n return False\n\n # walk down\n while i < N and A[i] > A[i+1]:\n i += 1\n\n return i == N\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if(len(A)<3):\n return False\n elif(A.index(max(A))==0 or A.index(max(A))==(len(A)-1)):\n return False\n else:\n for i in range(A.index(max(A))):\n if(A[i]>=A[i+1]):\n return False\n for i in range(A.index(max(A)),len(A)-1):\n if(A[i]<=A[i+1]):\n return False\n return True\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n climb = True\n cs = 0\n fs = 0\n for i in range(1, len(A)):\n if climb == True:\n if A[i] > A[i-1]:\n cs += 1\n continue\n elif A[i] == A[i-1]:\n return False\n else:\n climb = False\n if climb == False:\n if A[i] < A[i-1]:\n fs += 1\n continue\n else:\n return False\n if cs > 0 and fs > 0:\n return True\n return False", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if(len(A)<3):\n return False\n i = 1\n while(i<len(A) and A[i]>A[i-1]):\n i+=1\n if(i==1 or i==len(A)):\n return False\n \n while(i<len(A) and A[i]<A[i-1]):\n i+=1\n return i==len(A)", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A) == 0 or len(A) == 1:\n return False\n \n idx = 0\n \n while (idx < len(A) - 1 and A[idx] < A[idx+1]):\n idx += 1\n if idx == 0 or idx == len(A) - 1:\n return False\n while (idx < len(A) - 1 and A[idx] > A[idx+1]):\n idx += 1\n \n print((idx, len(A)))\n return idx == len(A) - 1\n", "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if not A or len(A)<=2:\n return False\n increase = -1 \n for i in range(1, len(A)):\n if A[i] > A[i-1] and increase == -1:\n increase = 1\n if A[i] > A[i-1] and increase == 1:\n continue\n elif A[i] < A[i-1] and increase == 1:\n increase = 0\n elif A[i] < A[i-1] and increase == 0:\n continue\n else:\n return False\n if increase != 0:\n return False\n return True"] | {"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, they lose the game.
Return True if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
1 <= N <= 1000 | ["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 return False \n else:\n return True \n \n", "class Solution:\n memo = {}\n def divisorGame(self, N: int) -> bool:\n return self.move(N)\n def move(self, N):\n if N in self.memo:\n return self.memo[N]\n if N == 2:\n return True\n for f in self.factors(N):\n if self.move(N-f) == False:\n self.memo[N] = True\n return True\n self.memo[N] = False\n return False\n def factors(self,n):\n a = []\n for x in range(1,n):\n if n % x == 0:\n a.append(x)\n return a\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n memo = set()\n def check(factor, player):\n if factor==1:\n return player!='A'\n if factor in memo:\n return False\n player = 'A' if player=='B' else 'B'\n \n for i in range(1, 1 + (factor//2)):\n if factor % i==0:\n memo.add(factor)\n if check(factor-i, player):\n return True\n return check(N, 'A')\n\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n memo = [None]*(N+1)\n ans = self.canWin(N, memo)\n return ans\n \n def canWin(self, N, memo) :\n if N<=1 :\n return False\n if memo[N] is not None :\n return memo[N]\n for i in range(1, N//2 + 1) :\n if N%i == 0 :\n if not self.canWin(N-i, memo) :\n memo[N] = True\n return True\n memo[N] = False\n return False\n \n \n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp=[False for i in range(N+1)]\n for i in range(N+1):\n for x in range(1,i//2+1):\n if i%x==0 and (not dp[i-x]):\n dp[i]=True\n break\n return dp[N] \n \n", "import math\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n m = [0 for x in range(N+1)]\n m[1] = 0\n for x in range(2, N+1):\n temp = []\n i = 1\n while i < math.sqrt(x):\n if x%i == 0:\n if x/i == i:\n temp.append(i)\n else:\n temp.append(i)\n if x/i != x:\n temp.append(int(x/i))\n i += 1\n \n for y in temp:\n print(('x-y', x-y))\n if m[x-y] == 0:\n m[x] = 1\n \n return True if m[N]==1 else False\n", "class Solution:\n def divisorGame(self, n: int) -> bool:\n return self.helper(n, {})\n \n def helper(self, n, memo):\n if n == 1:\n return False\n elif n in memo:\n return memo[n]\n else:\n for f in self.factors(n): \n if self.helper(n-f, memo) == False:\n memo[n] = True\n return True\n memo[n] = False\n return False\n \n def factors(self, n):\n l = []\n i = 1\n while i**2 <= n:\n if n % i == 0:\n l.append(i)\n i += 1\n for num in l:\n if num**2< n and num > 1:\n l.append(int(n/num))\n \n return l", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False for i in range(N+1)]\n for i in range(N+1):\n for j in range(1, i//2+1):\n if i % j == 0 and (not dp[i - j]):\n dp[i] = True\n break\n return dp[N]", "\n\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n return recurse_game(N, 0)\n\n \ndef find_factors(n):\n factors = []\n for i in range(1,n):\n if n%i==0:\n factors.append(i)\n return factors\n\n\nlookup = {}\n\ndef recurse_game(N, P):\n if (N,P) in lookup:\n return lookup[(N,P)]\n \n if N<=1 and P==0:\n lookup[(N,P)] = False\n return False\n elif N<=1 and P==1:\n lookup[(N,P)] = True\n return True\n \n next_P = 0 if P == 1 else 1\n \n results = []\n for factor in find_factors(N):\n results.append(recurse_game(N-factor,next_P))\n \n # print(N,P,results)\n \n if P == 0:\n if True in results:\n lookup[(N,P)] = True\n return True\n else:\n lookup[(N,P)] = False\n return False\n \n if P == 1:\n if False in results:\n lookup[(N,P)] = False\n return False\n else:\n lookup[(N,P)] = True\n return True\n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n return N % 2 == 0", "class Solution:\n def divisorGame(self, N: int) -> bool:\n game = [False for i in range(N+1)]\n \n for i in range(2,N+1):\n for j in range(1,i):\n if i%j == 0 and game[i-j] == False:\n game[i] = True\n break\n \n return game[N]", "class Solution:\n def divisorGame(self, N: int) -> bool:\n if N <= 1:\n return False\n dp = [False] * (N + 1)\n for i in range(2, N + 1):\n for j in range(1, i // 2 + 1):\n if i % j == 0:\n nextN = i - j\n if dp[nextN] == False:\n dp[i] = True\n \n return dp[N]", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False for _ in range(N+1)]\n \n for i in range(N+1):\n for j in range(1, i//2+1):\n # dp[i-j] make sure Bob fails at step i-j\n if i % j == 0 and dp[i-j] == False:\n dp[i] = True\n \n return dp[-1]", "def doS(N,arr):\n if (N==1):\n return False\n \n if not(arr[N] == None):\n return arr[N]\n \n for i in range(1,N):\n if(N%i==0):\n if not doS(N-i,arr):\n arr[i]=True\n # print(N-i,arr) \n return True\n \n arr[N]=False\n return False\n \n\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n \n arr = [None]*(N+1)\n print(arr)\n return doS(N,arr) \n \n \n \n \n \n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n table = dict()\n res = self.helper(N, 0, table)\n return res\n \n \n def helper(self, N:int, numRds: int, ht: dict) -> bool:\n soln = False\n \n # Bob wins base case\n if N == 1 and numRds % 2 == 0: return False \n \n # Alice wins base case\n if N == 1 and numRds % 2 != 0: return True\n \n # Check to see if the current N values has been processed\n if ht.get(N, None) != None: return ht[N]\n ht[N] = False\n # Obtain list of factors\n fact = findFactors(N)\n \n # If not in the table process N against all of its factors\n for num in fact:\n ht[N] = ht[N] or self.helper(N - num, numRds + 1, ht)\n \n return ht[N]\n \n \n \ndef findFactors(num: int) -> list:\n res = []\n loPtr, hiPtr = 1, num\n while hiPtr > loPtr:\n if num % loPtr == 0: \n res.append(loPtr)\n if num // loPtr != num: res.append(num // loPtr)\n hiPtr = num // loPtr\n loPtr += 1\n return res", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False] * (N + 1)\n for i in range(N + 1):\n for j in range(1, i//2 + 1):\n if i%j == 0 and not dp[i - j]:\n dp[i] = True\n break\n return dp[-1]\n", "class Solution:\n @lru_cache(maxsize=None)\n def divisorGame(self, N: int) -> bool:\n if N == 2:\n return True\n \n options = []\n \n for x in range(1, N // 2):\n if N % x == 0:\n options.append(N - x)\n \n return any(map(\n lambda x: not self.divisorGame(x),\n options,\n ))", "class Solution:\n def __init__(self):\n self.memo = {}\n def findfactors(self, N):\n n = N//2\n fs = []\n for i in range(2, n+1):\n if N%i==0:\n fs.append(i)\n return fs+[1]\n \n def div(self, N):\n if N in self.memo:\n return self.memo[N]\n fs = self.findfactors(N)\n if N==1:\n self.memo[N] = 0\n return 0\n else:\n nf = len(fs)\n vals = [0]*nf\n for i in range(nf):\n vals[i] = self.div(N-fs[i])\n self.memo[N] = 1+max(vals)\n return self.memo[N]\n \n def divisorGame(self, N: int) -> bool:\n ans = self.div(N)\n if ans%2==0:\n return False\n else:\n return True\n \n", "class Solution:\n \n #this function will return all the possible nums after one move\n \n \n def divisorGame(self, N: int) -> bool:\n \n \n return N & 1 == 0", "class Solution:\n\n @lru_cache(None)\n def divisorGame(self, N: int) -> bool:\n if N == 0:\n return False\n if N == 1:\n return False\n if N == 2:\n return True\n \n @lru_cache(None)\n def divs(N):\n out = []\n for i in range(1, (N//2) + 1):\n if N % i == 0:\n out.append(i)\n return out\n \n moves = divs(N)\n \n for move in moves:\n if not self.divisorGame(N-move):\n return True\n \n return False\n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n turns = [{2:1}, {2:0}]\n \n def play(turn, N):\n if N in turns[turn]:\n return turns[turn][N]\n \n if turn:\n win = all(play(0, N-x) for x in range(1, N) if N % x == 0)\n else:\n win = any(play(1, N-x) for x in range(1, N) if N % x == 0)\n \n return turns[turn].setdefault(N, win)\n \n return play(0, N)", "from collections import defaultdict as dd\n\nclass Solution:\n def __init__(self):\n self.d = dd()\n \n def divisorGame(self, n: int) -> bool:\n return self.__will_win(n)\n \n def __will_win(self, n: int):\n \n for i in range(1, n):\n if n % i != 0:\n continue\n \n if n - i in self.d:\n wins = self.d[n - i]\n else:\n wins = self.__will_win(n - i)\n self.d[n - i] = wins\n \n if not wins: \n # this player choses this i as the next one will lose\n return True\n \n return False\n\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n if N == 1:\n return False\n elif N == 2:\n return True\n \n dp = [False for _ in range(N+1)]\n dp[2] = True\n \n for a in range(3, N+1):\n for b in range(1, a):\n if a%b == 0 and dp[a-b] == False:\n dp[a] = True\n break\n \n return dp[-1]", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False]*(N+1)\n for i in range(2,N+1):\n j = 1\n while j<i:\n if i%j==0 and dp[i-j]==False:\n dp[i] = True\n break\n j+=1 \n return dp[-1]\n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n \n if N <= 3:\n return (N % 2) == 0\n \n dp = [False for _ in range(N+1)]\n dp[2] = True\n \n for i in range(3, N+1):\n for j in range(1, i):\n if i % j == 0 and dp[i-j] == False:\n dp[i] = True\n break\n \n return dp[-1]\n \n \n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n if N == 1:\n return False\n elif N == 2:\n return True\n \n dp = [False]*(N+1)\n dp[1] = True\n dp[2] = True\n \n for i in range(3, N+1):\n for j in range(1, i):\n if i%2 == 0:\n dp[i] = True\n break\n print(dp)\n return dp[-1]", "class Solution:\n @lru_cache(None)\n def divisorGame(self, N: int) -> bool:\n if N == 1:\n return False\n return any(not self.divisorGame(N-x) if N % x == 0 else False for x in range(1, N))", "class Solution:\n def divisorGame(self, N: int) -> bool:\n \n self.visited = collections.defaultdict(bool)\n \n def alice_wins(N, alice = True):\n \n if N == 1:\n return True if not alice else False\n \n if N in self.visited:\n return self.visited[N]\n \n for i in range(1,N):\n if not N%i:\n if alice:\n self.visited[N] = alice_wins(N-i,alice=False)\n else:\n self.visited[N] = alice_wins(N-i)\n \n return self.visited[N]\n \n return alice_wins(N)\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n if N % 2 == 0:\n return True\n else:\n return False", "class Solution:\n def divisorGame(self, N: int) -> bool:\n if N<2:\n return False\n dp=[False]*(N+1)\n dp[2]=True\n \n for i in range(2,N+1):\n for x in range(1,i):\n if i%x==0 and not dp[i-x]:\n dp[i]=True\n return dp[-1]\n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n table = dict()\n res = self.helper(N, 0, table)\n return res\n \n \n def helper(self, N:int, numRds: int, ht: dict) -> bool:\n soln = False\n \n # Bob wins base case\n if N == 1 and numRds % 2 == 0: return False \n \n # Alice wins base case\n if N == 1 and numRds % 2 != 0: return True\n \n # Check to see if the current N values has been processed\n if ht.get(N, None) != None: \n a = 5\n return ht[N]\n \n # Obtain list of factors\n fact = findFactors(N)\n \n # If not in the table process N against all of its factors\n ht[N] = False # Base case to ensure no false positives\n for num in fact:\n ht[N] = ht[N] or self.helper(N - num, numRds + 1, ht)\n \n return ht[N]\n \n \n \ndef findFactors(num: int) -> list:\n res = []\n for val in range(1, num):\n if num % val == 0: res.append(val) \n return res", "class Solution:\n def divisorGame(self, N: int) -> bool:\n # dp solution\n d = {}\n def dp(v):\n if v not in d:\n d[v] = False\n for w in range(1, v):\n if v % w == 0:\n d[v] = d[v] or not dp(v-w)\n return d[v]\n out = dp(N)\n return out", "class Solution:\n def divisorGame(self, N: int) -> bool:\n res=[False]*(N+1)\n for i in range(2,N+1):\n if i%2 == 0 and res[int(i/2)] == False:\n res[i] = True\n continue\n for j in range(1,int(math.sqrt(i))):\n if i %j == 0:\n if res[i-j] == False or (j!=1 and res[i-int(i/j)] == False):\n res[i] = True\n break\n return res[N]\n \n \n \n\n \n \n \n \n \n", "class Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False, False]\n for x in range(2, N+1):\n dp.append(any([not dp[x-i] for i in range(1, int(math.sqrt(x))+1) if x % i == 0]))\n return dp[-1]", "class Solution:\n def divisorGame(self, N: int) -> bool:\n return win_game(N)\n \nfrom functools import lru_cache\n@lru_cache(maxsize=None)\ndef win_game(N):\n return any(not win_game(N-x) for x in range(1,N) if N % x == 0)", "class Solution:\n def divisorGame(self, N: int) -> bool:\n \n def divisors(N):\n if N == 1:\n return [1]\n \n res = []\n for n in range(1, int(N**0.5)+1):\n if N % n == 0:\n res.append(n)\n return res\n \n # Initial conditions\n table = {\n 1 : False,\n 2 : True,\n 3 : False\n }\n \n def compute(i):\n if i in table:\n return table[i]\n \n divs = divisors(i)\n next_nums = [i-d for d in divs]\n \n for n in next_nums:\n status = compute(n)\n \n if status == False:\n table[i] = True\n return True\n table[i] = False\n return False\n \n \n# for n in range(3, N+1):\n# divs = divisors(n)\n \n# for d in divs:\n# next_num = n - d\n# if table[next_num] == False:\n# # We want the next number to be a losing number\n# table[n] = True\n# break\n# if n not in table:\n# # If all next numbers are winning, then this is a losing number\n# table[n] = False\n\n return compute(N)"] | {"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
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100 | ["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 sum_ += mat[r][c2]\n return sum_\n", "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n leng = len(mat[0])\n ans = 0\n check = [[0 for _ in range(len(mat[0]))] for _ in range(len(mat))]\n for i in range(leng):\n ans+=mat[i][i]\n check[i][i] = 1\n \n for i in range(leng):\n if check[i][leng-1] != 1:\n ans+=mat[i][leng-1]\n leng-=1\n \n return ans\n", "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n leng = len(mat[0])\n ans = 0\n seen = set()\n for i in range(leng):\n ans+=mat[i][i]\n seen.add((i,i))\n \n ctr = len(mat)-1\n for i in range(leng):\n if (i,leng-1) not in seen:\n ans+=mat[i][leng-1]\n leng-=1\n \n return ans\n", "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n ans = 0\n n = len(mat[0])\n for i in range(n):\n ans = ans + mat[i][i] + mat[i][n - i - 1]\n if n % 2 != 0:\n ans = ans - mat[n//2][n//2]\n return ans\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 that if nums is special, the value for x is unique.
Example 1:
Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
Example 2:
Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.
Example 3:
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.
Example 4:
Input: nums = [3,6,7,7,0]
Output: -1
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000 | ["# 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# right = mid \n# return -1 if left < len(nums) and left == nums[left] else left\nclass Solution:\n def specialArray(self, a: List[int]) -> int:\n n, i = len(a), 0\n a.sort(reverse=True) \n l, r = 0, n\n while l < r:\n m = l + (r-l) // 2\n if m < a[m]:\n l = m + 1\n else:\n r = m\n return -1 if l < n and l == a[l] else l\n", "from bisect import bisect_left\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n nums.sort()\n l = len(nums)\n maxi = nums[-1]\n \n for i in range(maxi+1):\n if l - bisect_left(nums,i) == i:\n return i\n \n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for i in range(0, len(nums)+1):\n if sum([n >= i for n in nums]) == i:\n return i\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n res = -1\n \n \n nums.sort()\n \n for i in range(0, len(nums)):\n temp = 0\n for j in range(0, len(nums)):\n if nums[j] >= i+1 and nums[j] != 0:\n temp += 1\n \n if i+1 == temp: \n res = i+1 if i+1 > res else res\n \n return res\n", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n # n --> length of given array\n n = len(nums)\n \n # temporary array with all elements 0\n temp = [0 for i in range(n)]\n \n # if all elements are 0 then given array is not special\n if nums==temp:\n return -1\n \n # check for each number from 0 to 1000 that for ith number there are exactly i numbers greater than or equal to i.\n for x in range(1001):\n cnt = 0\n for i in nums:\n if i>=x:\n cnt+=1\n if cnt==x:\n return x\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n x = 0\n res = 0\n maxn = max(nums)\n # minn = min(nums)\n for i in range(maxn+1):\n res = 0\n for y in nums:\n if y >= i:\n res += 1\n if res == i:\n return i\n return -1\n", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for x in range(0, 1001):\n cnt = 0\n for e in nums:\n if e >= x:\n cnt += 1\n if cnt == x:\n return x\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n for x in range(-5, 1002):\n cnt = 0\n for y in nums:\n if y >= x:\n cnt += 1\n if cnt == x:\n return x\n \n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for i in range(1001):\n if sum(1 for a in nums if a >= i) == i:\n return i\n return -1\n", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for i in range(1, 1001):\n geq = 0\n for n in nums:\n geq += n >= i\n if geq == i:\n return i\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n low, high = 0, len(nums)\n while low <= high:\n mid = (low + high) // 2\n cnt = 0\n for i in nums:\n if i >= mid: cnt += 1\n if cnt == mid:\n return mid\n elif cnt > mid: low = mid + 1\n else: high = mid - 1\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n freq = collections.Counter()\n i, cnt = 1, 0\n for num in nums:\n freq[num] += 1\n if num >= i:\n cnt += 1\n if cnt == i:\n cnt -= freq[i]\n i += 1\n return -1 if cnt + freq[i-1] != i - 1 else i - 1\n", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n cache=set()\n for x in range(len(nums),0,-1):\n cnt=0\n for i in range(len(nums)):\n if nums[i] in cache:\n cnt+=1\n elif nums[i]>=x:\n cnt+=1\n cache.add(nums[i])\n if cnt==x:\n return x\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for x in range(len(nums), -1, -1):\n c = 0\n for n in nums:\n if n >= x:\n c += 1\n if c == x:\n return x\n \n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n len_num = len(nums)\n for x in range(1, len_num+1):\n elem_greater = 0\n for num in nums:\n elem_greater += num >= x\n if x == elem_greater:\n return x\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n for i in range(min(len(nums), max(nums)) + 1):\n if i == len([x for x in nums if x >= i]):\n return i\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(0, nums[-1] + 1):\n if i == len([n for n in nums if n >= i]):\n return i\n return -1", "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n x = None\n for i in range(1, len(nums) + 1):\n count = 0\n for n in nums:\n if n >= i:\n count += 1\n if count == i:\n x = i\n break\n return x if x is not None else -1"] | {"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 squares, never on filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.
Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".
You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.
Example 1:
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"
Example 2:
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "
Example 3:
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"
Example 4:
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X "
" O "
" "
Constraints:
1 <= moves.length <= 9
moves[i].length == 2
0 <= moves[i][j] <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe. | ["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: [[0, 1], [1, 1], [2, 1]],\n 3: [[0, 2], [1, 2], [2, 2]],\n 4: [[0, 0], [0, 1], [0, 2]],\n 5: [[1, 0], [1, 1], [1, 2]],\n 6: [[2, 0], [2, 1], [2, 2]],\n 7: [[0, 2], [1, 1], [2, 0]]\n }\n\n # count player one and two correct moves\n for possible_win in list(possible_wins.values()):\n count_a = 0\n for move in player_a:\n if move in possible_win:\n count_a += 1\n if count_a == 3:\n return 'A'\n\n count_b = 0\n for move in player_b:\n if move in possible_win:\n count_b += 1\n if count_b == 3:\n return 'B'\n\n return 'Draw' if len(player_a) + len(player_b) == 9 else 'Pending'\n"] | {"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 the double of M = 5,that is, 10 = 2 * 5.
Example 2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
Example 3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
Constraints:
2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3 | ["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 Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n lookup = dict()\n \n for val in arr: \n if val*2 in lookup:\n return True\n elif val /2 in lookup:\n return True\n else:\n lookup[val] = 1\n \n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr2=list([x*2 for x in arr])\n zeros=arr.count(0)\n \n if zeros >=2: return True\n \n \n print(arr2)\n for a in arr2:\n if a in arr: \n if a==0 and zeros == 1: continue\n return True\n \n return False\n \n \n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n tracker = set()\n for n in arr:\n if (n%2==0 and (n/2) in tracker) or n*2 in tracker:\n return True\n tracker.add(n)\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n # seen = set()\n # for e in arr:\n # if 2*e in seen or (e % 2 == 0 and e//2 in seen):\n # return True\n # seen.add(e)\n # return False\n \n for i in range(0, len(arr)):\n for j in range(i+1, len(arr)):\n if arr[i] == 2*arr[j] or arr[j] == 2*arr[i]:\n return True\n return False\n \n # for e in arr:\n # if 2*e in arr:\n # return True\n # return False\n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr.sort()\n for k in range(len(arr)-1):\n if 2*arr[k] in arr[k+1:] or 2*arr[k] in arr[:k]:\n return True\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n i=0\n i=len(arr)\n for j in range(0,i):\n for k in range(0,i):\n if(arr[j]>0 and arr[k]>0 and arr[j]>arr[k]):\n if(arr[j]==arr[k]*2):\n return True\n elif(arr[j]<0 and arr[k]<0 and arr[j]<arr[k]):\n if(arr[k]*2==arr[j]):\n return True \n if(arr[0]==0 and arr[1]==0):\n return True \n else:\n return False\n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n i=0\n i=len(arr)\n for j in range(0,i):\n for k in range(0,i):\n if(arr[j]>0 and arr[k]>0 and arr[j]>arr[k]):\n if(arr[j]==arr[k]*2):\n return True\n elif(arr[j]<0 and arr[k]<0 and arr[j]<arr[k]):\n if(arr[k]*2==arr[j]):\n return True \n if(arr[j]==0 and arr[k]==0):\n return True\n else:\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n \n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n if ((arr[j] == (arr[i]*2)) | (float(arr[j]) == (arr[i]/2))):\n return True\n return False\n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n if len(arr) == 0 or len(arr) == 1:\n return False\n else:\n for i in range(len(arr) - 1):\n for j in range(i + 1, len(arr)):\n if arr[i] == 2 * arr[j] or arr[j] == 2 * arr[i]:\n return True\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr.sort()\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n if (arr[i]!=0 and arr[j]/arr[i]==2):\n return True\n if(arr[i]==0 and arr[j]==0):\n return True\n if(arr[i]<0 and arr[j]<0 and arr[i]/arr[j]==2 ):\n return True\n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n seen = set()\n for e in arr:\n if 2*e in seen or (e % 2 == 0 and e//2 in seen):\n return True\n seen.add(e)\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr.sort()\n print(arr)\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[j] == 0 and arr[i] == 0:\n return True\n if arr[j] != 0 and arr[i] == 0:\n continue\n if arr[j] < 0 and arr[i] < 0:\n if arr[i] / arr[j] == 2:\n return True\n if arr[j] > 0 and arr[i] > 0:\n if arr[j] / arr[i] == 2:\n return True\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n for num in arr:\n if num == 0:\n if arr.count(0) > 1:\n return True\n else:\n if arr.count(num * 2) != 0:\n return True \n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n h_table = set()\n for num in arr:\n if num*2 in h_table or num/2 in h_table:\n return True\n h_table.add(num)\n return False\n \n \n \n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n doubledList = []\n l = len(arr)\n for num in arr:\n doubledList.append(num*2)\n for i in range(l):\n if doubledList[i] in arr and arr.index(doubledList[i]) != i:\n return True\n return False\n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n cache = set()\n for i, value in enumerate(arr):\n if 2*value in cache or (value%2 == 0 and value/2 in cache):\n return True\n cache.add(value)\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n \n if(len(arr) < 2):\n return False\n \n for n in range(len(arr)):\n m = 2*arr[n]\n for k in range(len(arr)):\n if(arr[k] == m and k!=n):\n return True\n \n return False\n \n \n", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n if arr[0] == 0 and arr[1] == 0:\n return True\n dictionary = {}\n for number in arr:\n dictionary[2 * number] = True\n\n for number in arr:\n if number in dictionary and number != 0:\n return True\n return False", "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n for i in range(len(arr)):\n for j in range(len(arr)):\n if i != j and (arr[i]*2 == arr[j] or arr[i] == arr[j]*2):\n print(i)\n print(j)\n return True\n return False\n"] | {"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 dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Constraints:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9 | ["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 set1[i]+=1\n elif ri in set1.keys():\n sum1+=set1[ri]\n set1[ri]+=1\n else:\n set1[i]=1\n return sum1", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n lst = [tuple(sorted(d)) for d in dominoes]\n dct = dict((x,lst.count(x)) for x in set(lst))\n\n y = sum(list([(x*(x-1)/2) for x in list(dct.values())]))\n return int(y)\n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n lst = [tuple(sorted(d)) for d in dominoes]\n counts = [lst.count(x) for x in set(lst)]\n # return int(sum(map(lambda x: (x*(x-1)/2), counts)))\n return int(sum([x*(x-1)/2 for x in counts]))\n \n \n \n \n x = [1,2,3]\n y = map(lambda a: a+2, x)\n print(list(y))", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n c = collections.Counter()\n for i in dominoes:\n c[tuple(sorted(i))] += 1\n \n return sum(math.comb(i, 2) for i in c.values()) ", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n count = 0\n# for i in range(len(dominoes)-1):\n# for j in range(i+1,len(dominoes)):\n# if (dominoes[i][0]==dominoes[j][0] and dominoes[i][1]==dominoes[j][1] ) or (dominoes[i][0]==dominoes[j][1] and dominoes[i][1]==dominoes[j][0] ):\n# count+=1\n \n# return count\n \n mydict = {}\n for dom in dominoes:\n if ''.join(str(dom)) in mydict:\n mydict[''.join(str(dom))] += 1\n elif ''.join(str(dom[::-1])) in mydict:\n mydict[''.join(str(dom[::-1]))] += 1\n else:\n mydict[''.join(str(dom))] = 1\n for val in list(mydict.values()):\n if val > 1:\n count += val*(val-1)//2\n\n return count\n\n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n for i in range(len(dominoes)):\n dominoes[i] = tuple(sorted(dominoes[i]))\n \n ans = 0\n \n for i in set(dominoes):\n d = dominoes.count(i)\n if d > 1:\n ans += d*(d-1) // 2\n return ans", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n for i in range(len(dominoes)):\n dominoes[i] = tuple(sorted(dominoes[i]))\n ans = 0\n for i in set(dominoes):\n t = dominoes.count(i)\n ans += t*(t-1)//2\n return ans", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n # d=dict()\n # res=0\n # for i,j in dominoes:\n # if(str([i,j]) in d):\n # d[str([i,j])]+=1\n # res+=d[str([i,j])]\n # elif(str([j,i]) in d):\n # d[str([j,i])]+=1\n # res+=d[str([j,i])]\n # else:\n # d[str([i,j])]=0\n # return res\n d={}\n res=0\n for i in dominoes:\n i=sorted(i)\n if(str(i) not in d):\n d[str(i)]=0\n d[str(i)]+=1\n if(d[str(i)]>1):\n res+=d[str(i)]-1\n print(d)\n return res", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n return sum(d * (d - 1) // 2 for d in Counter(tuple(sorted(domino)) for domino in dominoes).values())", "from collections import defaultdict\n\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n # ans = 0\n # dominoes = sorted([sorted(i) for i in dominoes])\n # # print(dominoes)\n # prev = dominoes.pop()\n # cnt = 0\n # tot = 0\n # while dominoes:\n # curr = dominoes.pop()\n # # print('curr ', curr)\n # if curr == prev:\n # cnt += 1\n # tot += cnt\n # else:\n # ans += tot\n # tot, cnt = 0, 0\n # prev = curr\n # return ans + tot\n \n \n # step 1: count the dominoes\n d = {}\n for domi in dominoes:\n p = tuple(sorted(domi))\n if p in d:\n d[p] += 1\n else:\n d[p] = 1\n # step 2: caculate the pairs. for each pair, number of pairs = n*(n-1)//2\n c = 0\n for n in list(d.values()):\n s = n*(n-1)//2\n c += s\n return c\n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n s=[]\n for i in range(len(dominoes)):\n \n dominoes[i]=sorted(dominoes[i])\n if dominoes[i] not in s:\n s.append(dominoes[i])\n re=0\n def fac(n):\n if n==0:\n return 1\n if n<3:\n return n\n return n*fac(n-1)\n for r in s:\n c=dominoes.count(r)\n re+=int(fac(c)/(fac(c-2)*2))\n \n print(dominoes,s,re)\n return re", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n dominoes_dict = {}\n for i in [frozenset(domino) for domino in dominoes]:\n if i not in dominoes_dict:\n dominoes_dict[i] = 1\n else:\n dominoes_dict[i] += 1 \n \n return sum([int((n*(n-1))/2) for n in list(dominoes_dict.values()) if n > 1])\n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n dominoes_dict = {}\n for i in dominoes:\n j = frozenset(i)\n if j not in dominoes_dict:\n dominoes_dict[j] = 1\n else:\n dominoes_dict[j] += 1 \n \n return sum([int((n*(n-1))/2) for n in list(dominoes_dict.values()) if n > 1])\n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n dicts = defaultdict(int)\n ans = 0\n\n for domi in dominoes:\n dicts[tuple(sorted(domi))] += 1\n \n for n in dicts.values():\n ans += n * (n - 1) // 2\n \n return ans", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n collection = defaultdict(int)\n count = 0\n for i in dominoes:\n pair = frozenset(i)\n count+=collection[pair]\n collection[pair]+=1\n \n \n return count", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n from collections import defaultdict\n counter = defaultdict(int)\n for domino in dominoes:\n counter[tuple(sorted(domino))] +=1\n return sum([v*(v-1)//2 for v in counter.values()])", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n # step 1: count the dominoes\n d = {}\n for dom in dominoes:\n p = tuple(sorted(dom))\n if p in d:\n d[p] += 1\n else:\n d[p] = 1\n # step calculate it \n c = 0\n for n in d.values():\n s = n*(n-1)//2\n c += s\n return c ", "from math import comb\nclass Solution:\n #def convert(self,list) -> int: \n # res = int(\\\"\\\".join(map(str, list))) \n # return res \n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n hashtable = {}\n for d in dominoes:\n new = tuple(sorted(d))\n if(new not in list(hashtable.keys())):\n hashtable[new] = 1\n else:\n hashtable[new] += 1\n counter = 0\n print(hashtable)\n for k,v in list(hashtable.items()):\n if v >= 2:\n counter += (comb(v,2))\n \n \n return counter\n \n", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n d = {}\n for domi in dominoes:\n p = tuple(sorted(domi))\n if p in d:\n d[p] += 1\n else:\n d[p] = 1\n c = 0\n for n in d.values():\n s = n*(n-1)//2\n c += s\n return c", "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n# # Ot(n^2) where n = len(dominoes)\n# # Os(1)\n# count, n = 0, len(dominoes)\n# for i in range(n - 1):\n# for k in range(i + 1, n):\n# count += dominoes[i] == dominoes[k] or dominoes[i] == list(reversed(dominoes[k]))\n \n# return count\n \n# # Ot(n) where n = len(dominoes)\n# # Os(n)\n \n# count_dict = {}\n# total_count = 0\n# for d1, d2 in dominoes:\n# if (d1, d2) in count_dict:\n# count_dict[(d1, d2)] += 1\n# total_count += count_dict[(d1, d2)] - 1\n# elif (d2, d1) in count_dict:\n# count_dict[(d2, d1)] += 1\n# total_count += count_dict[(d2, d1)] - 1\n# else:\n# count_dict[(d1, d2)] = 1\n \n# return total_count\n\n\n # Ot(n) where n = len(dominoes)\n # Os(n)\n \n count_dict = {}\n total_count = 0\n for d in dominoes:\n d = tuple(sorted(d))\n if d in count_dict:\n total_count += count_dict[tuple(d)]\n count_dict[d] += 1\n else:\n count_dict[d] = 1\n\n return total_count\n \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 the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 400 | ["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 dp[i] = max(dp[i-2] + nums[i], dp[i-1])\n return max(dp)", "class Solution:\n def rob(self, nums: List[int]) -> int:\n # if len(nums) <= 2: return max(nums+[0])\n now, last = 0, 0\n \n for i in nums:\n last, now = now, max(now, last + i)\n \n return now", "class Solution:\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n if n == 1:\n return nums[0]\n \n max_to_i = [None] * n\n max_to_i[0] = nums[0]\n max_to_i[1] = max(nums[0], nums[1])\n \n for i in range(2, n):\n max_to_i[i] = max(nums[i] + max_to_i[i-2], max_to_i[i-1])\n \n # max_to_i has len n, and contains max with the subarray [0:i].\n # Total result is just max_to_i[n-1]\n \n return max_to_i[-1]", "class Solution:\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n if(n==0):\n return 0\n if(n<=2):\n return max(nums)\n else:\n dp = [0 for i in nums]\n dp[0] = nums[0]\n dp[1] = nums[1]\n \n for i in range(2,n):\n dp[i] = max(dp[i-1],max(dp[j]+nums[i] for j in range(i-1)))\n return max(dp)\n", "class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n if len(nums) <= 2:\n return max(nums)\n \n dp = [0] * len(nums)\n dp[0] = nums[0]\n dp[1] = max(dp[0], nums[1])\n \n for i in range(2, len(nums)):\n dp[i] = max(nums[i] + dp[i-2], dp[i-1])\n return dp[-1]", "class Solution:\n def rob(self, nums: List[int]) -> int:\n n=len(nums)\n if n==0:\n return 0\n if n==1:\n return nums[0]\n dp=[0]*(n+1)\n dp[0]=0\n dp[1]=nums[0]\n a=1\n while a<n:\n dp[a+1]=max(dp[a-1]+nums[a],dp[a])\n a+=1\n return dp[n]\n", "class Solution:\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n l1 = [0]*n\n if n==0:\n return 0\n elif n==1:\n return nums[0]\n elif n==2:\n return max(nums[0],nums[1])\n \n l1[0],l1[1]=nums[0],max(nums[0],nums[1])\n \n for i in range(2,n):\n l1[i] = max(l1[i-1],nums[i]+l1[i-2])\n \n return max(l1)\n", "class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n if len(nums) == 1:\n return nums[0]\n \n robbed = [nums[0]]\n maxMoney = robbed[0]\n #print(nums)\n for i in range(1, len(nums)):\n cur = nums[i]\n for j in range(len(robbed) - 1):\n cur = max(nums[i] + robbed[j], cur)\n robbed.append(cur)\n if cur > maxMoney:\n maxMoney = cur\n #print(robbed)\n return maxMoney\n \n", "class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n \n dp = [0]\n dp.append(nums[0])\n\n for i in range(2,len(nums)+1):\n dp.append(max(dp[i-1],dp[i-2]+nums[i-1]))\n\n return dp[len(dp)-1]", "class Solution:\n def rob(self, nums: List[int]) -> int:\n prevMax=0\n currMax=0\n \n for num in nums:\n temp=currMax\n currMax=max(prevMax+num, currMax)\n prevMax=temp\n \n return currMax ", "class Solution:\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n size = len(nums)\n max_sums = nums.copy()\n for i, num in enumerate(nums):\n for j in range(0, i - 1):\n if 0 <= j < size:\n max_sums[i] = max(max_sums[i], num + max_sums[j])\n return max(max_sums)", "class Solution:\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n \n dp = [0] * len(nums)\n dp[0] = nums[0]\n dp[1] = nums[1]\n res = max(dp)\n for i in range(2, len(dp)):\n for j in range(i-1):\n dp[i] = max(dp[i], dp[j] + nums[i])\n res = max(res, dp[i])\n\n return res"] | {"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).
You need to return whether the student could be rewarded according to his attendance record.
Example 1:
Input: "PPALLP"
Output: True
Example 2:
Input: "PPALLL"
Output: False | ["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,0)] == \"L\":\n return False\n return True\n", "class Solution:\n def checkRecord(self, s):\n twoL = 0\n twoA = 0\n i = 0\n while i < len(s):\n if s[i] == 'A':\n twoA += 1\n if twoA > 1:\n return False\n twoL = 0\n elif s[i] == 'L':\n twoL += 1\n if twoL > 2:\n return False\n else:\n twoL = 0\n i += 1\n return True", "class Solution:\n def checkRecord(self, s):\n if not s:\n return\n c=0\n if s==\"AA\":\n return False\n for i in range(len(s)-2):\n if s[i]==\"L\":\n if s[i]==s[i+1] and s[i]==s[i+2]:\n return False\n if s[i]==\"A\":\n c+=1\n if c==2:\n return False\n \n return True", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return s.count('A')<=1 and s.count('LLL')==0\n \n \n \n \n", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n aCount=0\n clCount=0\n for r in s:\n if r=='A':\n aCount+=1\n if aCount >1:\n return False\n if r=='L':\n clCount+=1\n if clCount>2:\n return False\n else:\n clCount=0\n return True", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return(s.count(\"A\") < 2 and \"LLL\" not in s)", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n from collections import Counter\n val=Counter(s)\n idx=[]\n for i in range(len(s)):\n if s[i]==\"L\":\n idx.append(i)\n for j in range(len(idx)-2):\n if idx[j+2]-idx[j]==2:\n return False\n \n if val[\"A\"]>1:\n return False\n return True", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n return s.count('A') <= 1 and s.count('LLL') == 0\n", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n charA = charL = 0\n for c in s:\n if c == 'A':\n charA += 1 \n if charA > 1: return False\n charL = 0\n elif c == 'L':\n charL += 1\n if charL > 2: return False\n else: \n charL = 0\n \n \n return True\n \n \n", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return s.count(\"A\") < 2 and \"LLL\" not in s", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return s.count('A')<2 and s.count('LLL')==0", "class Solution:\n def checkRecord(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n mydir = {}\n for record in s:\n mydir[record] = mydir.get(record,0)+1\n return mydir.get('A',0) <= 1 and s.count('LLL') == 0\n"] | {"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 characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
Example 3:
Input: s = "j?qg??b"
Output: "jaqgacb"
Example 4:
Input: s = "??yw?ipkj?"
Output: "acywaipkja"
Constraints:
1 <= s.length <= 100
s contains only lower case English letters and '?'. | ["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 if string[i-1] != chr(j) and string[i+1] != chr(j):\n string[i] = chr(j)\n break\n \n ret = ''.join(string[1:-1])\n return ret\n", "class Solution:\n # def modifyString(self, s: str) -> str:\n # if s == \\\"?\\\":\n # return \\\"a\\\"\n # for i in range(len(s)):\n # if s[i] == '?':\n # if i == 0:\n # print(\\\"right\\\")\n # for j in range(97,123):\n # if chr(j) != s[1]:\n # print(\\\"right\\\")\n # s = s.replace('?', chr(j), 1)\n # print(s)\n # break\n # elif i == len(s)-1:\n # for j in range(97,123):\n # if chr(j) != s[i-1]:\n # s = s.replace('?', chr(j), 1)\n # break\n # else:\n # for j in range(97,123):\n # if chr(j) != s[i-1] and chr(j) != s[i+1]:\n # s = s.replace('?', chr(j), 1)\n # break\n # return s\n def modifyString(self, s: str) -> str:\n letters = ['a', 'b', 'c']\n for i in range(len(s)):\n if s[i] == '?':\n for l in letters:\n if (i == 0 or s[i-1] != l) and (i == len(s) - 1 or s[i+1] != l):\n s = s.replace('?', l, 1)\n break\n \n return s\n \n \n", "class Solution:\n def modifyString(self, s: str) -> str:\n r = ''\n \n if s[0] == '?':\n r += 'b' if (len(s) > 1 and s[1] == 'a') else 'a'\n else:\n r += s[0]\n \n for i in range(1, len(s) - 1):\n if s[i] == '?':\n if r[i - 1] != 'a' and s[i + 1] != 'a':\n r += 'a'\n elif r[i - 1] != 'b' and s[i + 1] != 'b':\n r += 'b'\n else:\n r += 'c'\n else:\n r += s[i]\n \n if len(s) > 1:\n if s[len(s) - 1] == '?':\n r += 'b' if r[len(s) - 2] == 'a' else 'a'\n else:\n r += s[len(s) - 1]\n \n return r\n \n", "class Solution:\n def modifyString(self, s: str) -> str:\n chars=list(map(chr, list(range(97, 123))))\n s=list(s)\n for i in range(0,len(s)):\n for x in chars:\n if(s[i]=='?'):\n if(i==len(s)-1):\n if(s[i-1]!=x):\n s[i]=x\n elif(s[i-1]!=x and s[i+1]!=x):\n s[i]=x\n return ''.join(s)\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
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned. | ["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\n low = 0\n high = x\n \n while low < high:\n mid = (high+low)/2\n if abs(mid**2-x) < 1e-6:\n return int(mid)\n elif mid**2 > x: \n high = mid\n else:\n low = mid", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n return int(x**(1/2))", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n a = x**0.5\n \n return math.floor(a)", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n return int((x ** (1/2)))", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n return int((x ** (1/2)))", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x==1 or x==0:\n return x\n left,right=1,x\n while 1:\n mid=left+(right-left)//2\n if mid>x//mid:\n right=mid-1\n else:\n if mid+1>x//(mid+1):\n return mid\n left=mid+1\n \n return int(n)\n", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x==1 or x==0:\n return x\n left,right=1,x\n while 1:\n mid=left+(right-left)//2\n if mid>x//mid:\n right=mid-1\n else:\n if mid+1>x//(mid+1):\n return mid\n left=mid+1\n \n return int(n)\n", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x==1 or x==0:\n return x\n left,right=0,x\n mid=(right+left)/2\n while abs(mid*mid-x)>0.01:\n if mid>x/mid:\n right=mid\n else:\n left=mid\n mid=(right+left)/2\n \n return int(mid)\n", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x==1 or x==0:\n return x\n left,right=0,x\n mid=(right+left)/2\n while abs(mid*mid-x)>0.01:\n if mid>x/mid:\n right=mid\n else:\n left=mid\n mid=(right+left)/2\n \n return int(mid)\n", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n hi = x // 2\n lo = 0\n if x == 1:\n return 1\n while True:\n if hi == lo:\n return hi\n if hi - lo == 1:\n if hi * hi > x:\n return lo\n return hi\n test = (hi + lo) // 2\n sq = test * test\n if sq == x:\n return test\n if sq > x:\n hi = test - 1\n else:\n lo = test\n \n", "class Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x<=1:\n return x\n up=x\n down=0\n while True:\n n=(up+down)//2\n if n**2==x:\n return n\n elif n**2<x:\n if (n+1)**2>x:\n return n\n else:\n down=n\n else:\n if (n-1)**2<x:\n return n-1\n else:\n up=n\n"] | {"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 is ["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"]. (Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]]).
Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.
Return the minimum possible value of D.length.
Example 1:
Input: A = ["cba","daf","ghi"]
Output: 1
Explanation:
After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order.
If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.
Example 2:
Input: A = ["a","b"]
Output: 0
Explanation: D = {}
Example 3:
Input: A = ["zyx","wvu","tsr"]
Output: 3
Explanation: D = {0, 1, 2}
Constraints:
1 <= A.length <= 100
1 <= A[i].length <= 1000 | ["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 \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n if (len(A) <= 1):\n return 0\n elif len(A[1]) == 1:\n return 0\n D = []\n for i in range(0, len(A[0])):\n col = [a[i] for a in A]\n col_sort = sorted(col)\n if col != col_sort:\n D.append(i)\n return len(D)\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n n = len(A[0])\n res = 0\n for i in range(n):\n col = [a[i] for a in A]\n if col != sorted(col):\n res += 1\n return res", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n result=0\n M=len(A[0])\n for i in range(M):\n col=[row[i] for row in A]\n if col!=sorted(col):\n result+=1\n return result\n \n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ans = 0\n for i,word in enumerate(zip(*A)):\n for j in range(len(word)-1):\n if word[j] > word[j+1]:\n ans += 1\n break\n \n return ans", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n delete_size = 0\n cols = zip(*A)\n for col in cols:\n for a, b in zip(col, col[1:]):\n if a > b:\n delete_size += 1\n break\n return delete_size", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n D = 0\n for col in zip(*A):\n p = chr(0)\n for c in col:\n if c < p:\n D += 1\n break\n p = c\n return D", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n return sum(any(i > j for i, j in zip(t, t[1:])) for t in zip(*A))", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n length = len(A[0])\n noofstr = len(A)\n #print(length, noofstr)\n \n for i in range(length):\n increasing = True\n for j in range(1,noofstr):\n if A[j][i] < A[j-1][i]:\n increasing = False\n break\n if increasing:\n count += 1\n return (length - count)", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n total_deletes = 0\n for j in range(len(A[0])):\n for i in range(1, len(A)):\n if A[i-1][j] > A[i][j]:\n total_deletes += 1\n break\n \n return total_deletes\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n return sum([list(i) != sorted(i) for i in zip(*A)])", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n res = []\n rows = len(A)\n cols = len(A[0])\n for c in range (cols):\n for r in range (rows-1):\n if A[r][c] > A[r+1][c]:\n res.append(-1)\n break\n \n return res.count(-1)", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n rows = len(A)\n cols = len(A[0])\n for c in range (cols):\n for r in range (rows-1):\n if A[r][c] > A[r+1][c]:\n count += 1\n break\n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n return sum(not all(c <= d for c, d in zip(col, col[1:])) for col in zip(*A))\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n length = len(A[0])\n noofstr = len(A)\n print(length, noofstr)\n \n for i in range(length):\n increasing = True\n for j in range(1,noofstr):\n if A[j][i] < A[j-1][i]:\n increasing = False\n break\n if increasing:\n count += 1\n return (length - count)", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n n = len(A[0])\n del_indices = []\n for j in range(n):\n for i in range(len(A) - 1):\n if A[i][j] > A[i + 1][j]:\n del_indices.append(j)\n break\n continue\n return len(del_indices)\n \n \n", "class Solution(object):\n def minDeletionSize(self, A):\n ans = 0\n for col in zip(*A):\n if any(col[i] > col[i+1] for i in range(len(col) - 1)):\n ans += 1\n return ans", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ans=0\n for col in zip(*A):\n if any(col[i]>col[i+1] for i in range(len(col)-1)):\n ans+=1\n return ans", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n res = 0\n for i in range(len(A[0])):\n for j in range(1,len(A)):\n if A[j][i] < A[j-1][i]:\n res+=1\n break\n \n \n return res", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n c_l = len(A[0])\n A_l = len(A)\n count = 0\n for i in range(c_l):\n string = [col[i] for col in A]\n # print(string)\n for j in range(1, A_l):\n if string[j] < string[j-1]:\n count += 1\n break\n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n for col in zip(*A):\n if list(col) != sorted(col):\n count += 1\n return count\n \n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n c = 0\n for i in range(len(A[0])):\n for j in range(len(A)-1):\n if A[j][i] > A[j+1][i]:\n c += 1\n break\n return c ", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n rows = len(A)\n cols = len(A[0])\n out = []\n for i in range(cols):\n temp = []\n for j in range(rows):\n temp.append(A[j][i])\n out.append(temp)\n count = 0\n for i in out:\n if i != sorted(i):\n count+=1\n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n columns = [''] * len(A[0]) \n for string in A:\n for i, char in enumerate(string):\n columns[i]+=char\n count = 0\n for word in columns:\n if word != ''.join(sorted(word)):\n count += 1\n return count\n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n l = list(A[0])\n \n for i in A:\n for j in range(len(i)):\n if l[j] == 'A':\n continue\n if i[j] < l[j]:\n l[j] = 'A'\n else:\n l[j] = i[j]\n # print(l)\n # print(l)\n return l.count('A')", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n indiciesToRemove = []\n columns = len(A[0])\n rows = len(A)\n for col in range(0, columns):\n previous = chr(0)\n for row in range(0, rows):\n if A[row][col] < previous:\n indiciesToRemove.append(col)\n break\n previous = A[row][col]\n \n \n return len(indiciesToRemove)\n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n return sum([x[i] for x in A] != sorted([x[i] for x in A]) for i in range(len(A[0]))) ", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n set_dim = 0\n for column in range(len(A[0])):\n for row in range(len(A) - 1):\n if A[row][column] > A[row + 1][column]:\n set_dim += 1\n break\n \n return set_dim\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n \n count = 0\n for c in range(len(A[0])):\n for i in range(len(A)-1):\n if ord(A[i][c]) > ord(A[i+1][c]):\n count += 1\n break\n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n # check ascending order = comparison O(1)\n \n do_not_remove_idx = []\n for idx in range(len(A[0])):\n tmp = [a[idx] for a in A]\n \n if any(x > y for x, y in zip(tmp, tmp[1:])):\n do_not_remove_idx.append(idx)\n \n return len(do_not_remove_idx)", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m = len(A)\n n = len(A[0])\n res = 0\n for j in range(n):\n for i in range(m - 1):\n if A[i][j] > A[i + 1][j]:\n res += 1\n break\n return res", "class Solution:\n def minDeletionSize(self, A):\n return sum(list(col) != sorted(col) for col in zip(*A))", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n t = 0\n i = 0\n while i < len(A[0]):\n j = 0\n last = chr(0)\n while j < len(A):\n if A[j][i] >= last:\n last = A[j][i]\n else:\n t += 1\n break\n j += 1\n i += 1\n return t", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n \n count = 0\n\n for i in range(len(A[0])):\n if not self.isSorted(list([x[i] for x in A])):\n count+=1\n\n return count\n \n \n \n def isSorted(self,list_char):\n for i in range(1,len(list_char)):\n if list_char[i-1]>list_char[i]:\n return False\n \n return True\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n result = 0\n for i in range(len(A[0])):\n last = A[0][i]\n for j in range(1, len(A)):\n if ord(last) > ord(A[j][i]):\n result += 1\n break\n last = A[j][i]\n \n return result\n \n", "class Solution:\n def minDeletionSize(self, A):\n word_len = len(A[0])\n count = 0\n\n for j in range(word_len):\n for i in range(1, len(A)):\n if A[i][j] < A[i-1][j]:\n count+=1\n break\n return count", "# brute force\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n res = 0\n for j in range(len(A[0])):\n for i in range(len(A) - 1):\n if ord(A[i][j]) > ord(A[i + 1][j]):\n res += 1\n break\n return res", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n if len(A) == 0:\n return 0\n n = len(A[0])\n cnt = 0\n for i in range(n):\n is_sorted = True\n for j in range(len(A) - 1):\n if A[j][i] > A[j + 1][i]:\n is_sorted = False\n break\n if not is_sorted:\n cnt += 1\n return cnt", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n if not A:\n return 0\n count=0\n prev=''\n for i in range(0,len(A[0])):\n for j in range(1,len(A)):\n if ord(A[j-1][i])>ord(A[j][i]):\n count+=1\n break\n return count\n \n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ans = 0\n for col in zip(*A):\n if any(col[i] > col[i+1] for i in range(len(col) - 1)):\n ans += 1\n return ans", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count=0\n for i in zip(*A):\n if ''.join(i)!=''.join(sorted(list(map(''.join,i)))):\n count+=1\n return count", "class Solution:\n # check all non-decreasing order exists and find all peaks\n def findAllPeaks(self, A:List[str]) -> set():\n if (len(A[0]) <= 1):\n return set()\n \n column_number = len(A[0])\n row_number = len(A)\n \n pre_letter_to_int = [-1 for i in range(column_number)]\n result = set()\n for c in range(column_number):\n for r in range(row_number):\n if ord(A[r][c]) < pre_letter_to_int[c]:\n # find a peak, pre_letter_to_int\n result.add(c)\n break\n else:\n pre_letter_to_int[c] = ord(A[r][c])\n return result\n \n \n \n \n def minDeletionSize(self, A: List[str]) -> int:\n return len(self.findAllPeaks(A))\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n size = len(A[0])\n setd = set([i for i in range(size)])\n for i in range(len(A) - 1) :\n if not setd :\n return size\n setn = set()\n for digit in setd:\n if A[i][digit] > A[i+1][digit] :\n setn.add(digit)\n setd -= setn\n \n return size - len(setd)", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n N = len(A[0])\n # print(A[0])\n count = 0\n for i in range(N):\n temp = []\n for j in range(len(A)):\n temp.append(A[j][i])\n \n # print(temp)\n # print(sorted(temp))\n if temp != sorted(temp):\n count += 1\n \n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n return sum(any(A[j][i] < A[j - 1][i] for j in range(1, len(A))) for i in range(len(A[0])))", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n for i in range(len(A)):\n self.convertCharsToIntArray(i,A)\n counts = 0\n for i in range(len(A[0])):\n checker = False\n for j in range(1,len(A)):\n if A[j-1][i] > A[j][i]:\n checker = True\n if checker:\n counts += 1\n return counts \n \n def convertCharsToIntArray(self,i,A):\n chars = A[i]\n array = []\n for char in chars:\n array.append(ord(char))\n A[i] = array\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n col = 0\n while col < len(A[0]):\n row = 0\n while row < len(A)-1:\n if ord(A[row][col] ) > ord(A[row+1][col]):\n count += 1\n break\n row += 1\n col += 1\n return count\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n for i in range(len(A)):\n self.convertCharsToIntArray(i,A)\n \n counts = 0\n for i in range(len(A[0])):\n checker = False\n for j in range(1,len(A)):\n if A[j-1][i] > A[j][i]:\n checker = True\n if checker:\n counts += 1\n return counts \n \n def convertCharsToIntArray(self,i,A):\n chars = A[i]\n array = []\n for char in chars:\n array.append(ord(char))\n A[i] = array\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ans = []\n j = 0\n for i in range(len(A[0])):\n temp = []\n for k in range(len(A)):\n temp.append(A[k][j])\n ans.append(temp)\n j += 1\n count = 0\n for i in ans:\n temp = i[:]\n temp.sort()\n if temp != i:\n count += 1\n return count", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n count = 0\n for i in range(0, len(A[0])):\n maximum = A[0][i]\n inDecreasingOrder = True\n j = 1\n while j < len(A):\n val = A[j][i]\n if val < maximum:\n inDecreasingOrder = False\n break\n maximum = val\n j += 1\n if inDecreasingOrder:\n count += 1\n return len(A[0])-count\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n ans = 0\n for col in zip(*A):\n if any(col[i] > col[i+1] for i in range(len(col) - 1)): # Delete decreasing ones\n ans += 1\n return ans\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n \n ans = 0\n for i in zip(*A):\n if list(i) != sorted(i):\n ans += 1\n return ans\n", "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n prev = A[0]\n indices = {i for i in range(len(prev))}\n remove = set()\n for a in A[1:]:\n remove.clear()\n for i in indices:\n if prev[i] > a[i]:\n remove.add(i)\n indices -= remove\n prev = a\n # if len(indices) == 0: break\n return len(prev) - len(indices)\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 :rtype: int\n \"\"\"\n result = 0\n while num >= 10:\n num, rem = divmod(num,10)\n num+= rem\n return num\n", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num == 0:return 0\n return (num-1)%9+1", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if(num<10):\n return num\n else:\n return self.addDigits(num%10 + self.addDigits(num//10))\n", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num < 10:\n return num\n \n curr_num = num\n total = 0\n \n while True:\n while curr_num > 0:\n digit = curr_num % 10\n total += digit\n curr_num = curr_num//10\n \n if total < 10:\n return total\n else:\n curr_num = total\n total = 0\n", "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 :rtype: int\n \"\"\"\n \n while num // 10 > 0:\n rlt = 0\n while num > 0:\n rlt += num % 10\n num //= 10\n num = rlt\n \n return num", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n while len(str(num)) > 1:\n newNum = 0\n while num > 0:\n newNum += num % 10\n num = num // 10\n num = newNum\n return num", "class Solution: \n \n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num < 10:\n return num\n else:\n return self.addDigits(sum([int(x) for x in str(num)]))", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n while True:\n if num<10:\n return num\n else:\n num=sum([int(i) for i in str(num)])", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n return 9 if num != 0 and num % 9 == 0 else num % 9", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n return num if num < 10 else num%9 if num%9!=0 else 9", "class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num == 0: return 0\n mod = num % 9\n return mod if mod != 0 else 9"] | {"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 the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:
Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters. | ["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 # Use pair of sorted even substring and odd substring as unique key\n \n for idx, s in enumerate(A):\n signature.add( ''.join( sorted( s[::2] ) ) + ''.join( sorted( s[1::2] ) ) )\n \n return len( signature )\n", "from collections import Counter\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n count = Counter()\n for s in A:\n seven = ''\n sodd = ''\n for i in range(len(s)):\n if i % 2 == 0:\n seven += s[i]\n else:\n sodd += s[i]\n count[''.join(sorted(seven)), ''.join(sorted(sodd))] += 1\n # print(count.keys())\n return len(count)\n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n for i in range(len(A)):\n A[i]=sorted(list(A[i][::2]))+sorted(list(A[i][1::2]))\n A.sort()\n n=0\n while len(A)>0:\n A=A[A.count(A[0]):]\n n+=1\n return n", "from collections import Counter\n\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n lst = []\n for word in A:\n evens = []\n odds = []\n for i, l in enumerate(word):\n if i % 2 == 0:\n evens.append(l)\n else:\n odds.append(l)\n lst.append((sorted(evens), sorted(odds)))\n s = []\n for word in lst:\n if word not in s:\n s.append(word)\n return len(s)", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n groups = []\n for s in A:\n info = len(s), Counter(s[::2]), Counter(s[1::2])\n if info not in groups:\n groups.append(info)\n return len(groups)\n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(''.join(sorted(a[::2])) + ''.join(sorted(a[1::2])) for a in A))\n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n groups = []\n \n def match(string):\n \n odds, evens = {}, {}\n \n for i in range(0, len(string), 2):\n evens[string[i]] = evens.get(string[i], 0) + 1\n \n for i in range(1, len(string), 2):\n odds[string[i]] = odds.get(string[i], 0) + 1\n \n for g in groups: \n if g[0] == odds and g[1] == evens:\n return True, odds, evens\n \n return False, odds, evens\n \n \n for s in A:\n \n matched, odds, evens = match(s)\n \n if not matched:\n groups.append((odds, evens))\n \n return len(groups)\n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n group = list()\n \n count = 0\n for el in A:\n i = 0\n counter = {0: dict(), 1: dict()}\n for ch in el:\n if ch not in counter[i]:\n counter[i][ch] = 1\n else:\n counter[i][ch] += 1\n i = 1 - i\n if counter not in group:\n group.append(counter)\n count += 1\n \n return count\n \n \n \n \n \n", "class Solution:\n \n def numSpecialEquivGroups(self, A: List[str]) -> int:\n lst = [string2IndRes(string) for string in A]\n \n u_lst = unique(lst)\n \n return len(u_lst)\n \n \n\ndef string2IndRes(string):\n \n res = []\n \n for i,c in enumerate(string):\n res.append((c,i%2))\n \n return Counter(res)\n\n\ndef unique(list1): \n \n # intilize a null list \n unique_list = [] \n \n # traverse for all elements \n for x in list1: \n # check if exists in unique_list or not \n if x not in unique_list: \n unique_list.append(x) \n \n return unique_list\n \n", "from collections import defaultdict \n\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n groups = []\n for word in A:\n result = {0: defaultdict(int), 1: defaultdict(int)}\n for i, char in enumerate(word):\n result[i % 2][char] += 1\n if result not in groups:\n groups.append(result)\n return len(groups)\n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n # set1 = set()\n even_set = []\n odd_set = []\n for i in A:\n even = []\n odd = []\n for j in range(len(i)):\n if j %2 == 0:\n even.append(i[j])\n else:\n odd.append(i[j])\n even.sort()\n odd.sort()\n if even in even_set:\n k = []\n for p,values in enumerate(even_set):\n if even == values:\n k += [p]\n flag = 0\n for p in k:\n if odd_set[p] == odd:\n flag = 1 \n break\n if flag == 0:\n even_set.append(even) \n odd_set.append(odd)\n else:\n even_set.append(even) \n odd_set.append(odd)\n \n return len(even_set)\n \n \n \n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n set1 = set()\n even_set = []\n odd_set = []\n for i in A:\n even = []\n odd = []\n for j in range(len(i)):\n if j %2 == 0:\n even.append(i[j])\n else:\n odd.append(i[j])\n even.sort()\n odd.sort()\n \n if even in even_set:\n k = []\n for p,values in enumerate(even_set):\n if even == values:\n k += [p]\n flag = 0\n for p in k:\n if odd_set[p] == odd:\n flag = 1 \n if flag == 0:\n even_set.append(even) \n odd_set.append(odd)\n else:\n even_set.append(even) \n odd_set.append(odd)\n \n print((even_set,odd_set))\n return len(even_set)\n \n \n \n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n group = []\n \n for el in A:\n i = 0\n # counter = {0: dict(), 1: dict()}\n counter = [dict(), dict()]\n for ch in el:\n if ch not in counter[i]:\n counter[i][ch] = 1\n else:\n counter[i][ch] += 1\n i = 1 - i\n if counter not in group:\n group.append(counter)\n \n return len(group)\n \n \n \n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n haveList = list()\n ans = 0\n for i in range(len(A)):\n odd = dict()\n even = dict()\n for y,v in enumerate(A[i]):\n if y % 2 == 0:\n odd[v] = odd.get(v,0)+1\n else:\n even[v] = even.get(v,0)+1\n if [odd,even] not in haveList:\n haveList.append([odd,even])\n return len(haveList)", "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]));", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n haveList = list()\n ans = 0\n for i in A:\n odd = dict()\n even = dict()\n for s in i[0::2]:\n odd[s] = odd.get(s,0)+1\n for s2 in i[1::2]:\n even[s2] = even.get(s2,0)+1\n if [odd,even] not in haveList:\n haveList.append([odd,even])\n length = len(haveList)\n return length", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n odds = []\n evens = []\n n = len(A[0])\n for s in A:\n de = {}\n do = {}\n for i in range(n):\n if i%2:\n if s[i] in de:\n de[s[i]] += 1\n else:\n de[s[i]] = 1\n else:\n if s[i] in do:\n do[s[i]] += 1\n else:\n do[s[i]] = 1\n odds.append(do)\n evens.append(de)\n \n total = []\n i = 0\n while i < len(odds):\n j = i + 1\n while j < len(odds):\n if odds[i] == odds[j] and evens[i] == evens[j]:\n odds.pop(j)\n evens.pop(j)\n else:\n j += 1\n i += 1\n return len(odds)", "from collections import Counter\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n n = len(A)\n groups = 0\n taken = [0]*n\n even_counters = list(map(Counter, [z[::2] for z in A]))\n odd_counters = list(map(Counter, [z[1::2] for z in A]))\n for i in range(n):\n if taken[i]==0:\n oci = odd_counters[i]\n eci = even_counters[i]\n for j in range(i+1, n):\n if taken[j]==1:\n continue\n ocj = odd_counters[j]\n ecj = even_counters[j]\n if oci==ocj and eci==ecj:\n taken[j] = 1\n groups += 1\n return groups\n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res, count, ct = 0, [], collections.Counter\n \n for s in A:\n even = collections.defaultdict(int)\n odd = collections.defaultdict(int)\n isEven = True\n for c in s:\n if isEven:\n even[c] += 1\n else:\n odd[c] += 1\n isEven = not isEven\n count.append((even, odd))\n \n i = 0\n while i < len(count):\n j = i + 1\n while j < len(count):\n if count[i][0] == count[j][0] and count[i][1] == count[j][1]:\n count.pop(j)\n j -= 1\n j += 1\n res += 1\n count.pop(i)\n \n return res", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res, count, ct = 0, [], collections.Counter\n \n for s in A:\n even = collections.defaultdict(int)\n odd = collections.defaultdict(int)\n isEven = True\n for c in s:\n if isEven:\n even[c] += 1\n else:\n odd[c] += 1\n isEven = not isEven\n count.append((even, odd)) \n\n while count:\n i, count2 = 1, []\n for i in range(1, len(count)):\n if count[0][0] != count[i][0] or count[0][1] != count[i][1]:\n count2.append(count[i])\n res += 1\n count = count2\n \n return res", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n if len(A) == 1:\n return 1\n \n def areSpecialEquiv(x: str, y: str) -> bool:\n dic_x = {}\n dic_y = {}\n for c in x:\n if c not in y:\n return False\n\n for i in range(len(x)):\n found = 0\n for j in range(len(y)):\n if x[i] == y[j] and i % 2 == j % 2:\n found = 1\n if not found:\n return False\n \n for l in x:\n if l in dic_x:\n dic_x[l] += 1\n else:\n dic_x[l] = 1\n \n for l in y:\n if l in dic_y:\n dic_y[l] += 1\n else:\n dic_y[l] = 1\n \n for l in dic_x:\n if dic_x[l] != dic_y[l]:\n return False\n \n return True\n \n stack = A[:]\n arr = []\n \n while stack:\n arr2 = []\n curr = stack.pop(0)\n count = 1\n \n for w in stack:\n if areSpecialEquiv(curr,w):\n count += 1\n arr2.append(w)\n arr.append(count)\n\n for i in arr2:\n stack.remove(i)\n \n return len(arr)", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n s = set()\n for a in A:\n s.add(''.join(sorted(a[::2])) + ''.join(sorted(a[1::2])))\n return len(s)\n \n \n# dic = Counter()\n \n# def idx(x):\n# ans = \\\"\\\"\n# for k in sorted(x):\n# ans += k + str(x[k])\n# return ans\n \n# for a in A:\n# odd = Counter(a[1::2])\n# even = Counter(a[::2])\n# dic[idx(odd), idx(even)] += 1\n \n# return len(dic)\n \n \n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n counter_list = set()\n \n for i in A:\n \n even = []\n odd = []\n \n for index, item in enumerate(i):\n if index % 2 == 0:\n even.append(item)\n else:\n odd.append(item)\n \n normalised = ''.join(sorted(even) + sorted(odd))\n counter_list.add(normalised)\n \n return len(counter_list)\n\n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n l = len(A)\n counter = {}\n for i in range(l):\n odd = []\n even = []\n for j in range(len(A[i])):\n if j % 2 == 0:\n even.append(A[i][j])\n else:\n odd.append(A[i][j])\n even.sort()\n odd.sort()\n counter[(str(even), str(odd))] = counter.get((str(even), str(odd)), 0) + 1\n \n return len(counter)\n \n \n \n \n", "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n d = set()\n for w in A:\n even = ''.join(sorted(w[0::2]))\n odd = ''.join(sorted(w[1::2]))\n d.add((even, odd))\n return len(d)\n"] | {"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 def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n s_dict = {}\n for letter in s:\n if letter not in s_dict:\n s_dict[letter] = 1\n else:\n s_dict[letter] += 1\n \n t_dict = {}\n for letter in t:\n if letter not in t_dict:\n t_dict[letter] = 1\n else:\n t_dict[letter] += 1\n \n result = ''\n for letter in t:\n if letter not in s_dict:\n result = letter\n elif t_dict[letter] > s_dict[letter]:\n result = letter\n return result\n \n \n", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n ss = sorted(s)\n st = sorted(t)\n i = 0 \n j = 0\n while i <= len(ss) - 1:\n if ss[i] == st[j]:\n i += 1\n j += 1\n else: return st[j]\n return st[j]", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n return [i for i in t if i not in s or s.count(i)!=t.count(i)][0]\n # one more letter not more than one letter and rtype=return type --string\n", "class Solution:\n def findTheDifference(self, s, t):\n for i in t:\n if not i in s or t.count(i) != s.count(i):\n return i\n", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n for i in set(t):\n if i not in set(s) or t.count(i)>s.count(i):\n return i", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n s_map = {}\n for char in s:\n if char in s_map:\n s_map[char] += 1\n else:\n s_map[char] = 1\n t_map = {}\n for char in t:\n if char in t_map:\n t_map[char] += 1\n else:\n t_map[char] = 1\n for char in t_map:\n if (char not in s_map) or (t_map[char] > s_map[char]):\n return char", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n a = list(s)\n b = list(t)\n for c in s:\n a.remove(c)\n b.remove(c)\n return b[0]", "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n S = [i for i in s]\n T = [i for i in t]\n for i in S:\n T.remove(i)\n return T[0]\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 (down). The output should be true or false representing whether the robot makes a circle.
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false | ["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 moves: str\n :rtype: bool\n \"\"\"\n if not moves:\n return True\n if len(moves) % 2 == 1:\n return False\n \n up, left = 0, 0\n for move in moves:\n if move == 'U':\n up += 1\n if move == 'D':\n up -= 1\n if move == 'L':\n left += 1\n if move == 'R':\n left -= 1\n return up == 0 and left == 0\n \n", "class Solution:\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n pos = [0,0]\n for i in moves:\n if i == 'U':\n pos[0] = pos[0] + 1\n elif i == 'D':\n pos[0] = pos[0] - 1\n elif i == 'L':\n pos[1] = pos[1] - 1\n elif i == 'R':\n pos[1] = pos[1] + 1\n return [0,0] == pos", "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')))\n", "class Solution:\n def judgeCircle(self, moves):\n l, r, u, d = list(map(moves.count, 'LRUD'))\n return l == r and u == d\n", "class Solution:\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n \n # moves = list(moves)\n # u = moves.count('U')\n # d = moves.count('D')\n # l = moves.count('L')\n # r = moves.count('R')\n # if u == d and l == r:\n # return True\n # else:\n # return False\n # return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')\n u, d, l, r = map(moves.count, 'UDLR')\n return u==d and l==r", "class Solution:\n def judgeCircle(self, moves):\n m_list = list(moves)\n return m_list.count('U') == m_list.count('D') and m_list.count('R') == m_list.count('L')\n", "class Solution:\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n x = 0\n y = 0\n for move in moves:\n #print(move)\n if move == 'L':\n x -= 1\n elif move == 'R':\n x += 1\n elif move == 'U':\n x += 1\n elif move == 'D':\n x -= 1\n \n if x == 0 and y == 0:\n return True\n else:\n return False"] | {"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 cost needed to move all the chips to the same position.
Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.
Example 2:
Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at poistion 3 to position 2. Each move has cost = 1. The total cost = 2.
Example 3:
Input: position = [1,1000000000]
Output: 1
Constraints:
1 <= position.length <= 100
1 <= position[i] <= 10^9 | ["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]\n else:\n b+=d[i]\n return min(a,b)", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n oddc = evenc = 0\n for i in position:\n if i%2 == 0:\n evenc+=1\n else:\n oddc+=1\n return oddc if oddc <= evenc else evenc\n \n", "from collections import Counter\n\nclass Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n count_e = count_o = 0\n for pos in position:\n if pos % 2 == 0:\n count_e += 1\n else:\n count_o += 1\n \n return min(count_e, count_o) \n", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n position.sort()\n mn = float('inf')\n def getTo(index,p):\n res = 0\n for i in range(len(position)):\n res += abs(p - position[i])%2\n return res\n for i in range(len(position)):\n mn = min(mn, getTo(i,position[i]))\n return mn", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n l = [0,0]\n for i in range(len(position)):\n if position[i]%2 == 0:\n l[0] += 1\n else:\n l[1] += 1\n return min(l[0],l[1])", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n even = 0\n odd = 0\n for i in position:\n if i%2 == 0:\n even += 1\n else:\n odd += 1\n return min(even, odd)", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n odd = 0\n even = 0\n for pos in position:\n odd = odd + 1 if pos % 2 else odd\n even = even + 1 if not pos % 2 else even\n \n return min(odd, even)\n", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n \n \n record = {}\n for i in range(len(position)):\n if(position[i] not in record):\n record[position[i]] = 1\n else:\n record[position[i]] += 1\n max_freq = 0\n odd_freq = 0\n even_freq = 0\n odd_max_freq = 0\n even_max_freq = 0\n odd_rec = 0\n even_rec = 0\n for i in record:\n if (i%2 != 0):\n odd_freq += record[i]\n if(record[i]>=odd_max_freq):\n odd_max_freq = record[i]\n odd_rec = i\n else:\n even_freq += record[i]\n if(record[i]>=even_max_freq):\n even_max_freq = record[i]\n even_rec = i\n #ax_freq = max(odd_freq, even_freq)\n if (odd_freq > even_freq):\n rec = odd_rec\n else:\n rec = even_rec\n\n\n\n cost = 0\n for i in position:\n if(((rec-i)% 2 ==0) or ((i - rec) % 2 == 0)):\n continue\n elif (rec == i):\n continue\n else:\n cost += 1\n return cost", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n odd = len([p for p in position if p%2])\n return min(odd, len(position)-odd)\n \n", "class Solution:\n def minCostToMoveChips(self, p: List[int]) -> int:\n even=0\n odd=0\n for i in p:\n if(i%2==0):\n even+=1\n else:\n odd+=1\n return min(even,odd)\n", "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n position.sort()\n flag = 0\n record = {}\n for i in range(len(position)):\n if(position[i] not in record):\n record[position[i]] = 1\n else:\n record[position[i]] += 1\n max_freq = 0\n odd_freq = 0\n even_freq = 0\n odd_max_freq = 0\n even_max_freq = 0\n odd_rec = 0\n even_rec = 0\n for i in record:\n if (i%2 != 0):\n odd_freq += record[i]\n if(record[i]>=odd_max_freq):\n odd_max_freq = record[i]\n odd_rec = i\n else:\n even_freq += record[i]\n if(record[i]>=even_max_freq):\n even_max_freq = record[i]\n even_rec = i\n #ax_freq = max(odd_freq, even_freq)\n if (odd_freq > even_freq):\n rec = odd_rec\n else:\n rec = even_rec\n\n\n\n cost = 0\n for i in position:\n if(((rec-i)% 2 ==0) or ((i - rec) % 2 == 0)):\n continue\n elif (rec == i):\n continue\n else:\n cost += 1\n return cost"] | {"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(3, 4).
Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000]. | ["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, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size. | ["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 pos < len(flowerbed):\n if n == 0:\n print(n)\n return True\n else:\n if pos+1 < len(flowerbed):\n if flowerbed[pos] == 0 and flowerbed[pos+1] == 0:\n print(pos)\n n-=1\n pos+=2\n elif flowerbed[pos] == 1:\n pos += 2\n else:\n pos +=3\n else:\n if flowerbed[pos] == 0:\n n-=1\n pos+=2\n if n == 0:\n return True\n else:\n return False\n else:\n return False", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n \n possible = 0\n repeated = 1\n \n for f in flowerbed:\n if f:\n if repeated:\n possible += (repeated - 1) // 2\n repeated = 0\n else:\n repeated += 1\n \n if repeated:\n possible += repeated // 2\n \n return (possible >= n)", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n cnt = 0\n for i in range(len(flowerbed)):\n if flowerbed[i] == 0:\n if (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerbed)-1 or flowerbed[i+1] == 0):\n flowerbed[i] = 1\n cnt += 1\n return cnt >= n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n cnt = 0\n for i, f in enumerate(flowerbed):\n if f == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerbed)-1 or flowerbed[i+1] == 0):\n cnt += 1\n flowerbed[i] = 1\n return cnt >= n\n \n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n if n == 0:\n return True\n L = len(flowerbed)\n if n > (L + 1) // 2:\n return False\n if L == 1:\n return flowerbed[0] == 0\n \n cnt, i = 0, 0\n while i < L:\n if flowerbed[i] == 1:\n i += 2\n elif i < L-1 and flowerbed[i+1] == 1:\n i += 3\n elif i == L-1:\n cnt += int(flowerbed[i-1] == 0)\n i += 1\n elif i == 0 or flowerbed[i-1] == 0:\n cnt += 1\n i += 2\n return cnt >= n", "class Solution:\n def canPlaceFlowers(self, nums, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n count = 0\n nums = [0] + nums +[0]\n for i in range(1,len(nums)-1):\n if nums[i] == 0:\n if nums[i+1] == 0 and nums[i-1] == 0:\n count += 1\n nums[i] =1\n if count >= n:\n return True\n else:\n return False", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n lenFb = len(flowerbed)\n for i in range(lenFb):\n if i == 0:\n if flowerbed[i] == 0:\n if i == lenFb -1:\n flowerbed[i] = 1\n n -= 1\n elif flowerbed[i+1] == 0:\n flowerbed[i] = 1\n n -= 1\n elif i == lenFb - 1:\n if flowerbed[i] == 0:\n if flowerbed[i-1] == 0:\n flowerbed[i] = 1\n n -= 1\n else:\n if flowerbed[i-1] == 0 and flowerbed[i+1] == 0 and flowerbed[i] == 0:\n flowerbed[i] = 1\n n -= 1\n return not (n>0)\n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n lenFb = len(flowerbed)\n for i in range(lenFb):\n if i == 0:\n if flowerbed[i] == 0:\n if i == lenFb -1:\n flowerbed[i] = 1\n n -= 1\n elif flowerbed[i+1] == 0:\n flowerbed[i] = 1\n n -= 1\n elif i == lenFb - 1:\n if flowerbed[i] == 0:\n if flowerbed[i-1] == 0:\n flowerbed[i] = 1\n n -= 1\n else:\n if flowerbed[i-1] == 0 and flowerbed[i+1] == 0 and flowerbed[i] == 0:\n flowerbed[i] = 1\n n -= 1\n return (n<=0)\n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n canPlant=0\n if len(flowerbed)==1:\n if flowerbed[0]==0:\n canPlant +=1\n flowerbed[0]=1\n else:\n for i in range(len(flowerbed)):\n if flowerbed[i]==0:\n if i ==0:\n if flowerbed[i+1]==0:\n flowerbed[i]=1\n canPlant+=1\n elif i == len(flowerbed)-1:\n if flowerbed[i-1]==0:\n flowerbed[i]=1\n canPlant+=1\n else:\n if flowerbed[i+1]==0 and flowerbed[i-1]==0:\n flowerbed[i]=1\n canPlant+=1 \n if canPlant >=n:\n return True\n else:\n return False\n \n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n count, pos = 0, 0\n while pos < len(flowerbed):\n if (pos - 1 < 0 or not flowerbed[pos-1]) and \\\n (not flowerbed[pos]) and \\\n (pos + 1 > len(flowerbed) - 1 or not flowerbed[pos+1]):\n print(pos)\n count+=1\n pos+=2\n else:\n pos+=1\n return count >= n", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n result = False\n if n == 0:\n return True\n if flowerbed:\n if len(flowerbed) == 1:\n if flowerbed[0] == 0:\n flowerbed[0] = 1\n n -= 1\n return n == 0\n for i in range(len(flowerbed)):\n left, right = False, False\n if flowerbed[i] == 0 and n != 0:\n if i == 0 and len(flowerbed) >= 2:\n if flowerbed[i] == 0 and flowerbed[i + 1] == 0:\n flowerbed[i] = 1\n n -= 1\n else:\n left = i - 1 >= 0 and flowerbed[i - 1] == 0 \n \n if i == len(flowerbed) - 1 and len(flowerbed) >= 2:\n if flowerbed[i] == 0 and flowerbed[i - 1] == 0:\n flowerbed[i] =1 \n n -= 1\n else:\n right = i + 1 < len(flowerbed) and flowerbed[i + 1] == 0\n \n if left and right:\n flowerbed[i] = 1\n n -= 1\n result = (n == 0)\n return result", "class Solution:\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n if n==0:\n return True\n temp=0\n m=0\n if flowerbed[0]==0:\n temp=1\n for i,plot in enumerate(flowerbed):\n if plot==0:\n temp+=1\n if(i==len(flowerbed)-1):\n temp+=1\n if plot==1 or i==len(flowerbed)-1:\n m+=int((temp-1)/2)\n temp=0\n if m>=n:\n return True\n return False\n"] | {"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.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000 | ["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 return False\n return True", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n c = Counter(arr)\n freq = list(c.values())\n return len(freq) == len(set(freq))\n \n \n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n l=list(set(arr))\n for i in range(len(l)):\n l[i]=arr.count(l[i])\n if len(l)==len(set(l)):\n return True\n else:\n return False\n \n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n occur = {}\n check = set()\n for num in arr:\n if num not in occur:\n occur[num] = arr.count(num)\n for num in occur.values():\n check.add(num)\n if len(occur) == len(check):\n return True\n return False", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n res = False\n occ=[]\n n=0\n for i in range(0,len(arr)):\n if arr[i] in arr[0:i]:\n pass\n else: \n n = arr.count(arr[i])\n occ.append(n)\n\n\n c=0\n\n for j in range(0,len(occ)):\n for k in range(j+1,len(occ)):\n if occ[j]==occ[k]:\n c=1\n res=False\n break\n else:\n c=0\n res=True\n\n if c==1:\n break\n \n return res\n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n count = {}\n for a in arr:\n if a not in count:\n count[a] = 1\n else:\n count[a] += 1\n occ = []\n for c in list(count.values()):\n if c not in occ:\n occ.append(c)\n else:\n return False\n return True\n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n count = Counter(arr)\n s = set()\n \n for k,v in list(count.items()):\n if v in s:\n return False\n else:\n s.add(v)\n return True\n \n \n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n from collections import Counter\n count_dict = dict(Counter(arr))\n count_occurrences = [j for i,j in list(count_dict.items())]\n return len(set(arr)) == len(set(count_occurrences))\n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n occd = {}\n for n in arr:\n if n in occd:\n occd[n] += 1\n else:\n occd[n] = 1\n \n s = set()\n for k, v in occd.items():\n if v in s:\n return False\n s.add(v)\n \n return True", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n counter = {}\n\n for i in arr:\n counter[i] = counter.get(i, 0) + 1\n\n return len(counter.values()) == len(set(list(counter.values())))", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n \n dct = {}\n \n for num in arr:\n if num in dct:\n dct[num]+=1\n else:\n dct[num] = 1\n \n return len(list(dct.values())) == len(set(dct.values()))\n \n \n \n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n rec = [arr.count(elem) for elem in set(arr)]\n return len(rec) == len(set(rec))\n", "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n unique = set(arr)\n sol = []\n for i in unique:\n sol.append(arr.count(i))\n print(sol)\n for i in sol:\n if sol.count(i) > 1:\n return False\n return True"] | {"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", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Example 4:
Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""
Constraints:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1 and str2 consist of English uppercase letters. | ["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 = contender\n ans = None\n while len(contender) <= len(str1) and len(contender) <= len(str2):\n t1 = str1.replace(contender, '')\n t2 = str2.replace(contender, '')\n if len(t1) == len(t2) == 0:\n ans = contender\n contender += orig\n return ans if ans else ''", "class Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n m, n = len(str1), len(str2)\n candidate, curr = '', ''\n \n for i in range(min(m, n)):\n if str1[i] != str2[i]:\n break\n else:\n curr += str1[i]\n if m % len(curr) == 0 and n % len(curr) == 0:\n if str1 == curr * (m // len(curr)) and str2 == curr * (n // len(curr)):\n candidate = curr\n \n return candidate\n", "class Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n def diviser(n):\n if n == 4:\n return [1,2]\n Result = [1]\n for i in range(2,n//2):\n if n%i == 0:\n Result.extend([int(i),int(n/i)])\n return Result\n \n def str_diviser(str3):\n Result = ['',str3]\n Result1 = diviser(len(str3))\n if len(Result1) > 0:\n for i in Result1:\n div=str3[:i]\n for j in range(i,len(str3),i):\n if str3[j:(j+i)] != div:\n break\n if j == len(str3)-i:\n Result.append(div)\n return Result\n a=str_diviser(str1)\n b=str_diviser(str2)\n if len(a)>len(b):\n a,b = b,a\n Cur = ''\n for i in a:\n if i in b and len(i)>len(Cur):\n Cur = i\n return Cur\n"] | {"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].
Constraints:
0 <= low <= high <= 10^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)-(low-low//2)+low%2\n", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n return ((high + 1)>>1) - (low>>1)", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n c = 0\n if low < 0 or high > 10**9:\n return\n else:\n if (low%2 != 0 and high%2 !=0):\n return int((high-low)/2)+1\n elif ((low%2 == 0 and high%2 != 0) or (low%2 != 0 and high%2 == 0)):\n return int((high-low)/2)+1\n else:\n return int((high-low)/2)\n", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n c = 0\n if low < 0 or high > 10**9:\n return\n else:\n if (low%2 == 0 and high%2 ==0):\n return int((high-low)/2)\n else:\n return int((high-low)/2)+1 \n", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n \n ## O(1) With Math\n odd_lowerbound, odd_upperbound = -1, -1\n \n # compute smallest odd number in range\n if low % 2 == 1:\n odd_lowerbound = low\n else:\n odd_lowerbound = low + 1\n \n # compute largest odd number in range\n if high % 2 == 1:\n odd_upperbound = high\n else:\n odd_upperbound = high - 1\n \n \n # compute the number of odd numbers in range\n return (odd_upperbound - odd_lowerbound) // 2 + 1\n \n", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n return (high + 1) // 2 - (low //2)", "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n return (high - low + 1) // 2 + (high % 2 and low % 2);\n", "class Solution:\n def countOdds(self, lo, hi):\n return (hi+1)//2 - lo//2"] | {"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 obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 10^6 | ["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) -> int:\n bnum = bin(num)\n return len(bnum) + bnum.count('1') - 3", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n return len(bin(num)) + bin(num).count('1') - 3", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n \n steps = 0\n while(num>0):\n # print(num)\n if num%2 == 0:\n num = num/2\n steps+=1\n else:\n num = num-1\n steps+=1\n return steps", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n count=0\n while num>0:\n if num&1:\n count+=1\n num=num>>1\n count+=1\n \n return count-1 if count > 0 else count", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n count = 0\n \n while num!=0:\n if num%2 == 0:\n num /= 2\n count += 1\n else:\n num -= 1\n count += 1\n return count", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n count = 0\n \n while num!=0:\n if num%2 == 0:\n num = num/2\n else:\n num -= 1\n count += 1\n return count", "class Solution:\n def numberOfSteps (self, num):\n steps = 0 # We need to keep track of how many steps this takes.\n while num > 0: # Remember, we're taking steps until num is 0.\n if num % 2 == 0: # Modulus operator tells us num is *even*.\n num = num // 2 # So we divide num by 2.\n else: # Otherwise, num must be *odd*.\n num = num - 1 # So we subtract 1 from num.\n steps = steps + 1 # We *always* increment steps by 1.\n return steps # And at the end, the answer is in steps so we return it.\n", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n \n steps = 0\n \n while num > 0:\n if num%2 == 0:\n num = num//2\n steps += 1\n else:\n num -=1\n steps +=1\n return steps\n", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n if num==0:return 0\n ans=0\n while num!=0:\n if num&1==0:\n num=num>>1\n ans+=1\n else:\n if num==1:\n return ans+1\n num=num>>1\n ans+=2\n return ans\n", "class Solution:\n def numberOfSteps (self, num: int) -> int:\n cnt = 0\n while num:\n if num & 1: num -= 1\n else: num >>= 1\n cnt += 1\n return cnt"] | {"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 substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) | ["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 = (s + s)[1:-1]\n return s in ss\n", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n double_s = s + s\n return s in double_s[1:len(double_s)-1]", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return any(s[:i] * (len(s) // i) == s for i in range(1, len(s) // 2 + 1) if len(s) % i == 0)", "class Solution:\n def repeatedSubstringPattern(self, s):\n size = len(s)\n for x in range(1, size // 2 + 1):\n if size % x:\n continue\n if s[:x] * (size // x) == s:\n return True\n return False", "class Solution:\n def repeatedSubstringPattern(self, s):\n size = len(s)\n for x in range(1, size // 2 + 1):\n if size % x:\n continue\n if s[:x] * (size // x) == s:\n return True\n return False", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n n = len(s) # find len\n for i in range(n//2,0,-1): # loop from end to start\n if n%i ==0: # if n is sub_len integer tiems\n repeat = s[0:i]\n if repeat*(n//i) ==s: #if repeat*several_times == s\n return True\n return False\n \n", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s)<1:\n return True\n if len(s)==1:\n return False\n for lenofsub in range(1,len(s)):\n if (len(s)%lenofsub==0):\n substring=[s[0:lenofsub]]*(len(s)//lenofsub)\n if ''.join(substring)==s:\n return True\n return False\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 = (s + s)[1:-1]\n return s in ss \n", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n ss = (s + s)[1:-1]\n return ss.find(s) != -1", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return s in (2 * s)[1:-1]\n", "class Solution:\n def repeatedSubstringPattern(self, s):\n size = len(s)\n for x in range(1, size // 2 + 1):\n if size % x:\n continue\n if s[:x] * (size // x) == s:\n return True\n return False", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n size = len(s)\n for i in range(1, size//2 + 1):\n if size % i:\n continue\n if s[:i] * (size//i) == s:\n return True\n return False", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n return s in (s+s)[1:-1]", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s_len = len(s)\n for i in range(1,(s_len)//2+1):\n if s[i] == s[0]:\n s_sub = s[:i]\n s_new = s_sub * (s_len // i)\n if s_new == s:\n return True\n return False", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n ss = (s*2)[1:-1]\n return s in ss", "class Solution:\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n length = len(s)\n \n base = 1\n while base <= length // 2:\n if length % base == 0:\n if s[:base]*(length//base) == s:\n return True\n base += 1\n \n return False"] | {"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 (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5 | ["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 number < 10000:\n return True\n elif number < 100000:\n return False\n return True\n\n return sum([1 for num in nums if has_even_digits(num)])\n", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return len([i for (i) in nums if len(str(i))%2==0 ])\n", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return sum([1 if(len(str(num))%2 == 0) else 0 for num in nums])", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n count = 0\n for i in nums:\n if len(str(i)) % 2==0:\n count += 1\n return count\n \n", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n even_cnt = 0\n for num in nums :\n if (len(str(num)) % 2 == 0) : even_cnt += 1\n \n return even_cnt", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n ec = 0\n digit = 0\n for value in nums:\n digit = len(str(value))\n if digit % 2 == 0:\n ec += 1 \n return ec", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n count = 0\n track = 0\n for num in nums:\n count = 0\n if len(str(num)) % 2 ==0:\n track += 1\n return track", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n count = 0\n string_map = map(str, nums)\n for i in string_map:\n if len(i) % 2 == 0:\n count+=1\n return count", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n nums.sort()\n # pt = [ 10 ** m for m in range(6)]\n ans = 0\n for i in nums:\n if (i >= 10 and i < 100) or (i >= 1000 and i < 10000) or (i >= 100000 and i < 1000000):\n ans += 1\n return ans", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n count = 0\n for n in nums:\n if len(str(n)) % 2 == 0:\n count += 1\n return count", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n result = 0\n for num in nums:\n count = 0 \n while num:\n num = num//10\n count +=1\n if count%2 == 0:\n result+=1\n \n \n return result\n", "class Solution:\n def digits(self,num):\n count=0\n while num:\n num=num//10\n count+=1\n if count%2==0:\n return True\n else:\n return False\n \n def findNumbers(self, nums: List[int]) -> int:\n c=0\n for i in nums:\n if Solution().digits(i):\n c+=1\n return c\n \n", "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n count = 0\n for num in nums:\n if len(str(num)) % 2 == 0:\n count += 1\n return count"] | {"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:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0. | ["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):\n if prices[i] - minprice > res:\n res = prices[i] - minprice\n if prices[i]<minprice:\n minprice = prices[i]\n \n return res\n \n \n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n hold = float(\"inf\")\n result = 0\n \n for p in prices:\n if p>hold:\n result=max(result,p-hold)\n hold = min(hold, p)\n return result\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n mincur,maxcur=prices[0],0\n for index in range(len(prices)):\n mincur=min(prices[index],mincur)\n maxcur=max(prices[index]-mincur,maxcur)\n return maxcur\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) < 2:\n return 0\n max_profit = 0\n min_before = prices[0]\n for i in prices:\n min_before = min(i,min_before)\n max_profit = max(max_profit,i-min_before)\n \n return max_profit", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n profit = 0\n buy = prices[0] if prices else None\n for price in prices:\n buy = min(buy, price)\n profit = max(profit, price - buy)\n return profit\n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n hold = float(\"inf\")\n result = 0\n \n for p in prices:\n if p>hold:\n result=max(result,p-hold)\n else:\n hold = p\n return result\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n curr_min = float('inf')\n max_profit = 0\n \n for price in prices:\n curr_min = min(curr_min, price)\n profit = price - curr_min \n max_profit = max(max_profit, profit)\n \n return max_profit", "class Solution:\n def maxProfit1(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n mincur,maxcur=prices[0],0\n for index in range(len(prices)):\n mincur=min(prices[index],mincur)\n maxcur=max(prices[index]-mincur,maxcur)\n return maxcur\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices)<2:\n return 0\n maxcur,maxpro=0,0\n for index in range(1,len(prices)):\n maxcur+=(prices[index]-prices[index-1])\n maxcur=max(0,maxcur)\n maxpro=max(maxpro,maxcur)\n return maxpro\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n profit = 0\n for i in range(len(prices)-1):\n for j in range(i+1,len(prices),1):\n if prices[i] >= prices[j]:\n break\n else:\n profit = max(profit, prices[j]-prices[i])\n return profit", "class Solution:\n def maxProfit(self, prices):\n max_profit = 0\n local_max = 0\n for i in range(1,len(prices)):\n if(local_max+prices[i]-prices[i-1]>0):\n local_max += prices[i]-prices[i-1]\n if(local_max>max_profit):\n max_profit = local_max\n else:\n local_max = 0\n return max_profit\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n n = len(prices)\n \n return self.count_profit(prices,0,n -1)\n \n \n \n def count_profit(self,prices,left,right):\n if left >= right:\n return 0\n if right - left == 1:\n profit = prices[right] - prices[left]\n if profit < 0:\n profit = 0\n return profit\n mid = (left + right) // 2\n pro_left = self.count_profit(prices,left,mid)\n pro_right = self.count_profit(prices,mid+1,right)\n pro_mid = 0\n i = min(prices[left:mid + 1])\n j = max(prices[mid+1:right + 1])\n pro_mid = j -i\n profit = max(pro_left,pro_mid,pro_right)\n if profit < 0:\n profit = 0\n return profit\n \n \n \n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # find the valley first, them sale at peak\n if not prices: return 0\n min_price = prices[0]\n max_profit = 0\n for i in prices:\n if i < min_price:\n min_price = i\n elif max_profit < i - min_price:\n max_profit = i - min_price\n return max_profit", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices: return 0\n min_val = prices[0]\n profit = 0\n for i in range(1, len(prices)):\n if profit < prices[i] - min_val:\n profit = prices[i] - min_val\n if prices[i] < min_val:\n min_val = prices[i]\n \n return profit"] | {"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 "^" corresponds to bitwise XOR operator.
Example 2:
Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
Example 3:
Input: n = 1, start = 7
Output: 7
Example 4:
Input: n = 10, start = 5
Output: 2
Constraints:
1 <= n <= 1000
0 <= start <= 1000
n == nums.length | ["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(self, n: int, start: int) -> int:\n nums = [0]*n\n res= 0\n for i in range(n):\n nums[i] = start + 2*i\n res = res ^ nums[i]\n return res\n", "import functools\n\n\nclass Solution:\n \n \n def gen_array(self, n, s):\n for x in range(n):\n yield s + x * 2\n \n \n def xorOperation(self, n: int, start: int) -> int: \n return functools.reduce(lambda a, b: a^b, self.gen_array(n, start))", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n \n array = [start+2*i for i in range(n)]\n res = start\n for i in range (1,len(array)):\n res ^=array[i]\n \n return res\n", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n xor=0\n for i in range(n):\n xor^=start+(2*i)\n return xor\n", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n \n a = start\n \n for i in range(1,n):\n \n a = a^(start+2*i)\n \n return a\n \n", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n res = 0\n for i in range(n):\n res ^= start + 2 * i\n return res", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n res = start\n for i in range(1,n):\n res ^= i*2+start\n return res", "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n nums = []\n for i in range(n):\n nums.append(start + (2 * i))\n result = 0\n for n in nums:\n result = result ^ n\n return result\n"] | {"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 in "abcd" results in "cbad".
Example 1:
Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
Example 2:
Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
Example 3:
Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:
Input: A = "", B = "aa"
Output: false
Constraints:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist of lowercase letters. | ["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 enumerate(A):\n if a!=B[i]:\n diffs.append(i)\n if len(diffs) == 2:\n i,j = diffs\n return A[i]==B[j] and A[j]==B[i]\n \n return False", "class Solution:\n def buddyStrings(self, A, B):\n if len(A) != len(B) or set(A) != set(B): return False \n if A == B:\n return len(A) - len(set(A)) >= 1\n else: \n indices = []\n counter = 0\n for i in range(len(A)):\n if A[i] != B[i]:\n counter += 1\n indices.append(i) \n if counter > 2:\n return False \n return A[indices[0]] == B[indices[1]] and A[indices[1]] == B[indices[0]]", "class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n if len(A) != len(B):\n return False\n cand = []\n for i in range(len(A)):\n if A[i] != B[i]:\n cand.append(i)\n if len(cand) > 2:\n return False\n if len(cand) == 1:\n return False\n if len(cand) == 2:\n i, j = cand\n if A[i] == B[j] and B[i] == A[j]:\n return True\n else:\n return False\n if len(cand) == 0:\n if len(set(list(A))) < len(A):\n return True\n else:\n return False\n \n", "class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n if len(A) != len(B):\n return False\n if A == B:\n seen = set()\n for a in A:\n if a in seen:\n return True\n seen.add(a)\n return False\n else:\n pairs = []\n for a, b in zip(A, B):\n if a != b:\n pairs.append((a, b))\n if len(pairs) > 2:\n return False\n return len(pairs) == 2 and pairs[0] == pairs[1][::-1]", "class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n if len(A) != len(B):\n return False\n \n if A == B and len(set(A)) < len(A):\n return True\n \n diffs = [(a, b) for a, b in zip(A, B) if a!= b]\n \n return len(diffs) == 2 and diffs[0] == diffs[1][::-1]", "class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n \n if A == B and len(set(A)) < len(B): return True\n \n if len(A) != len(B): return False\n \n diff_A = []\n diff_B = []\n \n for i in range(len(A)):\n if A[i] != B[i]:\n diff_A.append(A[i])\n diff_B.append(B[i])\n \n return len(diff_A) == len(diff_B) == 2 and diff_A[::-1] == diff_B", "class Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n count_A = {}\n doubled = False\n for i,a in enumerate(A):\n if a not in count_A:\n count_A[a] = set()\n else:\n doubled = True\n count_A[a].add(i)\n off = 0\n for i,b in enumerate(B):\n if b not in count_A:\n return False\n else:\n if i in count_A[b]:\n count_A[b].remove(i)\n if not count_A[b]:\n del count_A[b]\n else:\n off += 1\n if off > 2:\n return False\n return doubled or off == 2"] | {"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 named x (This folder is guaranteed to always exist).
You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.
The file system starts in the main folder, then the operations in logs are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
Example 1:
Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.
Example 2:
Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3
Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0
Constraints:
1 <= logs.length <= 103
2 <= logs[i].length <= 10
logs[i] contains lowercase English letters, digits, '.', and '/'.
logs[i] follows the format described in the statement.
Folder names consist of lowercase English letters and digits. | ["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", "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n result = 0\n for log in logs:\n if log[:-1] == '..':\n result = max(0, result - 1)\n elif log[:-1] == '.':\n pass\n else:\n result += 1\n return result\n", "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = []\n for line in logs:\n if line == '../':\n if stack:\n stack.pop()\n elif line == './':\n pass\n else:\n stack.append(line)\n return len(stack)\n", "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n depth = 0\n for i in logs:\n if i =='../':\n depth = max(0, depth-1)\n elif i !='./':\n depth += 1\n return depth\n", "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n c = 0\n i = 0\n while i<len(logs):\n if logs[i] == '../':\n if c != 0:\n c -= 1\n elif logs[i] == './':\n pass\n else:\n c += 1\n i += 1\n return c", "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n s = []\n c = 0\n i = 0\n while i<len(logs):\n if logs[i] == '../':\n if c != 0:\n c -= 1\n elif logs[i] == './':\n i += 1\n continue\n else:\n c += 1\n i += 1\n return c"] | {"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 three numbers in the input won't exceed the range of 32-bit signed integer. | ["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 maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\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 maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n h, m, l = -float('inf'), -float('inf'), -float('inf')\n lowest, second_lowest = float('inf'), float('inf')\n \n for num in nums:\n if num > h:\n l = m\n m = h\n h= num\n elif num > m:\n l = m\n m = num\n elif num > l:\n l = num\n \n if num < lowest:\n second_lowest = lowest\n lowest = num\n elif num < second_lowest:\n second_lowest = num\n \n return max(h*m*l, h*lowest*second_lowest)", "class Solution:\n def maximumProduct1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n #Easy way to do it: sort them, take top 3 product\n #But have to think about negative numbers, lowest\n #2 could be 2 giant negatives.. * biggest positive\n #which could still be biggest product\n \n nums.sort()\n top = nums[~0] * nums[~1] * nums[~2]\n bottom = nums[0] * nums[1] * nums[~0]\n return max(top, bottom)\n #Time O(nlogn) due to sorting\n #Space O(1)\n \n \n def maximumProduct(self, nums):\n #Other approach is keep track of min1/2\n #and max1/2/3 while we iterate through the array\n min1 = min2 = float('inf')\n max1 = max2 = max3 = -float('inf')\n \n for n in nums:\n if n <= min1:\n min1, min2 = n, min1\n elif n <= min2:\n min2 = n\n \n if n >= max1:\n max1, max2, max3 = n, max1, max2\n elif n >= max2:\n max2, max3 = n, max2\n elif n >= max3:\n max3 = n\n \n return max(min1*min2*max1, max1*max2*max3)\n", "class Solution:\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max1,max2,max3,min1,min2 = float('-Inf'),float('-Inf'),float('-Inf'),float('Inf'),float('Inf')\n for num in nums:\n if num >= max1:\n max3,max2,max1 = max2,max1,num\n elif num >= max2:\n max3,max2 = max2,num\n elif num > max3:\n max3 = num\n if num <= min1:\n min2,min1 = min1,num\n elif num < min2:\n min2 = num\n return max(max1*max2*max3,min1*min2*max1)\n \n \n", "class Solution:\n def maximumProduct(self, nums):\n a = b = c = -1001\n d = e = 1001\n for num in nums:\n if num >= a:\n c = b\n b = a\n a = num\n elif num >= b:\n c = b\n b = num\n elif num >= c:\n c = num\n \n if num <= d:\n e = d\n d = num\n elif num <= e:\n e = num\n return max(a * b * c, a * d * e)\n", "class Solution:\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_num = -1000\n s_max = -1000\n t_max = -1000\n min_num = 1000\n s_min = 1000\n \n for i in range(len(nums)):\n if nums[i] > max_num:\n t_max = s_max\n s_max = max_num\n max_num = nums[i]\n elif nums[i] > s_max:\n t_max = s_max\n s_max = nums[i]\n elif nums[i] > t_max:\n t_max = nums[i]\n if nums[i] < min_num:\n s_min = min_num\n min_num = nums[i]\n elif nums[i] < s_min:\n s_min = nums[i]\n \n print (max_num, s_max, t_max, min_num, s_min)\n a = max_num * s_max * t_max \n b = min_num * s_min * max_num \n if a > b:\n return(a)\n else:\n return(b)", "class Solution:\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_num = -1000\n s_max = -1000\n t_max = -1000\n min_num = 1000\n s_min = 1000\n \n for i in range(len(nums)):\n if nums[i] > max_num:\n t_max = s_max\n s_max = max_num\n max_num = nums[i]\n elif nums[i] > s_max:\n t_max = s_max\n s_max = nums[i]\n elif nums[i] > t_max:\n t_max = nums[i]\n if nums[i] < min_num:\n s_min = min_num\n min_num = nums[i]\n elif nums[i] < s_min:\n s_min = nums[i]\n \n print (max_num, s_max, t_max, min_num, s_min)\n a = max_num * s_max * t_max \n b = min_num * s_min * max_num \n if a > b:\n return(a)\n else:\n return(b)", "class Solution:\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n new=[0 for i in range(2001)]\n for i in range(len(nums)):\n new[1000+nums[i]]=new[1000+nums[i]]+1\n count=0\n product=1\n digit=[]\n for i in range(2000,-1,-1):\n while(new[i]>0):\n digit.append(i-1000)\n count=count+1\n new[i]=new[i]-1\n if count==3:\n break\n if count==3:\n break\n for i in range(2001):\n while(new[i]>0):\n digit.append(i-1000)\n count=count+1\n new[i]=new[i]-1\n if count==5:\n break\n if count==5:\n break\n if len(digit)==3:\n return digit[0]*digit[1]*digit[2]\n elif len(digit)==4:\n return max(digit[0]*digit[1]*digit[2],digit[3]*digit[1]*digit[2])\n else:\n p1=digit[0]*digit[3]*digit[4]\n p2=digit[0]*digit[1]*digit[2]\n return max(p1,p2)\n \n \n"] | {"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 IPv4 address. | ["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", "class Solution:\n def defangIPaddr(self, address: str) -> str:\n return '[.]'.join(address.split('.'))", "class Solution:\n def defangIPaddr(self, address: str) -> str:\n new_string =''\n for s in address:\n if s =='.':\n new_string+='[.]'\n else:\n new_string+=s\n return new_string\n", "class Solution:\n def defangIPaddr(self, address: str) -> str:\n return address.replace('.','[.]')"] | {"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
Explanation: You can follow the next steps to convert arr to target:
1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.
Example 3:
Input: target = [1,12], arr = [12,1]
Output: true
Example 4:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr doesn't have value 9 and it can never be converted to target.
Example 5:
Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
Output: true
Constraints:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000 | ["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 return False", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if sum(arr) != sum(target):\n return False\n boolean = True\n for i, v in enumerate(target):\n if v in arr:\n boolean = True & boolean\n else: \n boolean = False & boolean\n return boolean", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if sum(arr) != sum(target):\n return False\n boolean = True\n for i, v in enumerate(target):\n if v in arr:\n boolean = True & boolean\n else: \n boolean = False & boolean\n break\n return boolean", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n # if target == arr:\n # return True\n result = all(elem in target for elem in arr)\n if result:\n return sorted(arr) == sorted(target)\n else:\n return False", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in range(len(target)):\n if target[i] not in arr:\n return False\n arr.pop(arr.index(target[i]))\n return True", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in arr:\n if i in target:\n target.remove(i)\n else:\n return False\n return True\n", "from collections import Counter\n\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n arr_counter = Counter(target)\n tgt_counter = Counter(arr)\n \n return arr_counter == tgt_counter", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if collections.Counter(target) != collections.Counter(arr):\n return False\n return True\n \n def reverse(left,right):\n while left<right:\n arr[left],arr[right] = arr[right],arr[left]\n left += 1\n right -=1\n \n for i in range(len(target)):\n if target[i] == arr[i]:\n continue\n j = arr.find(target[i])\n reverse(i,j)\n \n \n", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n # time O(n); space O(1)\n return Counter(target) == Counter(arr)", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return collections.Counter(target) == collections.Counter(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 return False\n", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n import numpy as np\n return((np.sort(target) == np.sort(arr)).all())", "def sort(list_a):\n low =[]\n high=[]\n if len(list_a)<=1:\n return list_a\n else:\n v=list_a.pop()\n for i in range(len(list_a)):\n if list_a[i]> v:\n high.append(list_a[i])\n else:\n low.append(list_a[i])\n return sort(low) + [v] + sort(high)\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n target = sort(target)\n arr = sort(arr)\n if arr == target:\n return True\n else:\n return False", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n # this is basically a buble sort kinda technique, but not sorted\n # if need to do this then??\n # put first element in place based on target\n # reverse from i to numIndex\n # increase i\n \n # or iterate both at the same time and check for 0 at the end\n if len(target) != len(arr):\n return False\n mp = {}\n for num in target:\n mp[num] = mp.get(num, 0) + 1\n \n for num in arr:\n if num not in mp:\n return False\n mp[num] -= 1\n if mp[num] < 0:\n return False\n return True\n \n \n", "class Solution:\n def canBeEqual(self, target, arr) -> bool:\n \n target = sorted(target)\n arr = sorted(arr)\n\n return target == arr", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if len(target)!=len(arr):\n return False\n \n p=0\n a=sorted(arr)\n t=sorted(target)\n while(p<len(t)):\n if a[p]!=t[p]:\n return False\n p+=1\n \n return True", "class Solution:\n def partition(self, arr, start, end):\n follower = leader = start\n while leader < end:\n if arr[leader] <= arr[end]:\n arr[leader], arr[follower] = arr[follower], arr[leader]\n follower += 1\n leader += 1\n arr[follower], arr[end] = arr[end], arr[follower]\n return follower\n \n def quicksort(self, arr, start, end):\n if start >= end:\n return\n else:\n p = self.partition(arr, start, end)\n self.quicksort(arr, p + 1, end)\n self.quicksort(arr, start, p - 1)\n \n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n self.quicksort(arr, 0, len(arr) - 1)\n self.quicksort(target, 0, len(arr) - 1)\n return target == arr\n \n \n", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for a in arr:\n if a in target:\n target.remove(a)\n else:\n return False\n return True", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in range(len(target)):\n if target[i] != arr[i]:\n if target[i] not in arr[i:]:\n return False\n else:\n j = arr[i:].index(target[i]) + len(arr[:i])\n arr[i], arr[j] = arr[j], arr[i]\n return True", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in target:\n if i not in arr:\n return False\n arr[arr.index(i)] = None\n return True\n", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in range(len(target)):\n for j in range(i, len(target)):\n if arr[j] == target[i]:\n break\n else:\n return False\n \n arr[i:j+1] = reversed(arr[i:j+1:])\n \n return arr == target", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n count = 0\n for item in target:\n if item not in arr:\n return False\n hash_map_arr = {}\n hash_map_target = {}\n for i in range(len(arr)):\n if arr[i] not in hash_map_arr:\n hash_map_arr[arr[i]] = 1\n else:\n hash_map_arr[arr[i]] += 1\n if target[i] not in hash_map_target:\n hash_map_target[target[i]] = 1\n else:\n hash_map_target[target[i]] += 1\n for item in target:\n if hash_map_arr[item] != hash_map_target[item]:\n return False\n return True", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \n for i in range(len(target)):\n if target[i] not in arr:\n return False\n if target[i] in arr:\n arr[arr.index(target[i])] = 0\n return True\n", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in range(len(target)):\n if target[i] in arr:\n arr.remove(target[i])\n else:\n pass\n if arr==[]:\n return True\n else:\n return False", "class Solution:\n \n def compare(self,x,y):\n x_ = set(x)\n for i in x_:\n if x.count(i)!=y.count(i):\n return False\n return True\n \n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return self.compare(target,arr) ", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n for i in arr:\n if i not in target:\n return 0\n else:\n target.remove(i)\n else:\n return 1\n", "from collections import Counter\n\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n c1 = Counter(target)\n c2 = Counter(arr)\n return not set(c1.keys()).symmetric_difference(set(c2.keys())) and all([c1[k1]==c2[k1] for k1 in c1])", "from collections import defaultdict\n\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if (len(target) != len(arr)):\n return False\n \n numbers = defaultdict(int) \n for val in arr:\n numbers[val] += 1\n \n for val in target:\n numbers[val] -= 1\n \n print(numbers)\n \n if (min(numbers.values()) == 0 and max(numbers.values()) == 0):\n return True\n \n return False", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \n d1 = {}\n d2 = {}\n \n for i in target:\n if i not in d1:\n d1[i] = 1\n else:\n d1[i] += 1\n \n for i in arr:\n if i not in d2:\n d2[i] = 1\n else:\n d2[i] += 1\n \n for k,v in d1.items():\n if k not in d2:\n return False\n elif v != d2[k]:\n return False\n \n return True", "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \n differences_dict = {}\n for i in range(len(target)):\n differences_dict[target[i]] = differences_dict.get(target[i], 0) + 1\n \n differences_dict[arr[i]] = differences_dict.get(arr[i], 0) - 1\n \n if not differences_dict[target[i]]:\n differences_dict.pop(target[i])\n \n if arr[i] != target[i] and not differences_dict[arr[i]]:\n differences_dict.pop(arr[i]) \n \n return False if differences_dict else True "] | {"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, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Constraints:
The given dates are valid dates between the years 1971 and 2100. | ["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 months = {1:0, 2:3,3:3,4:6,5:1,6:4,7:6,8:2,9:5,10:0,11:3,12:5}\n print(('month add:', months[month]))\n if year == 2100:\n leap = -1\n elif month <=2 and (year - 1968)%4 == 0:\n leap = -1\n else:\n leap = 0\n weekdate = (diff_year + months[month] + day + leap -1)%7\n print(('day:', day))\n print(weekdate)\n weekdays = {5:'Wednesday', 6:'Thursday', 7:'Friday',0:'Friday', \n 1:'Saturday', 2:'Sunday', 3: 'Monday', 4:'Tuesday'}\n return weekdays[weekdate]\n \n", "import calendar, datetime\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n return calendar.day_name[datetime.date(year, month, day).weekday()]\n", "from datetime import datetime\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n\n # index mapping: 0 1 2 3 4 5 6 \n weekday_name= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n \n # datetime is a class, whose constructor can output corresponding date-time object\n #\n # for example:\n # datetime(2020, 1, 15) = '2020-01-15 00:00:00'\n\n # And its strftime('%w') can convert a date-time object into a index string of weekday, start from Sunday as 0\n #\n # for example:\n # datetime(2020, 1, 15).strftime('%w') = '3'\n\n # Finally, use int( ... ) to carry out explicit type conversion fron str to integer as weekday index\n return weekday_name[ int( datetime(year, month, day).strftime('%w') ) ]", "import datetime\nimport calendar\n\nclass Solution:\n \n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n return datetime.datetime(year, month, day).strftime('%A')"] | {"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 consecutive odds.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000 | ["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 else:\n odd += 1\n i += 1\n else:\n if not flag:\n i += 1\n else:\n flag = False\n odd = 0\n i+= 1\n \n if odd == 3:\n return True\n \n return False\n \n \n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n if len(arr)<3:\n return False\n \n count=0\n for i in arr:\n if i%2!=0: \n count+=1\n elif i%2==0:\n count=0\n if count==3:\n return True\n \n return False\n \n \n \n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n ########################################################################### \n if len(arr) < 3:\n return False \n\n elif arr[0] % 2 + arr[1] % 2 + arr[2] % 2 == 3:\n return True \n else:\n return self.threeConsecutiveOdds(arr[1:])\n \n \n ###########################################################################\n \n\n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n \n for i in range(0, len(arr)):\n if arr[i] %2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\n return False", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n \n # Walk through the list\n # stop at an odd number\n # are the next 2 odd?\n # if so, yes and return\n # if not, walk forward one and try again\n \n \n for i in range(len(arr)):\n # I found an odd, are the next two odd?\n if arr[i] % 2 != 0:\n toCheck = arr[i: i + 3]\n \n print(toCheck)\n if len(toCheck) >= 3:\n if toCheck[1] % 2 != 0 and toCheck[2] % 2 != 0:\n return True\n \n return False\n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n for i in range(len(arr) - 2):\n if self.is_odd(arr[i]) and self.is_odd(arr[i+1]) and self.is_odd(arr[i+2]):\n return True\n return False\n \n def is_odd(self, num):\n return num % 2 != 0", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n a=0\n while(a < len(arr)-2):\n if arr[a]&1 and arr[a+1]&1 and arr[a+2]&1:\n return True\n elif arr[a+2]&1==0:\n a+=3\n elif arr[a+1]&1==0:\n a+=2\n elif arr[a]&1==0:\n a+=1 \n return False\n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n \n oddFound = False\n numOdd = 0\n for num in arr:\n if num % 2 != 0:\n oddFound = True\n numOdd += 1\n if numOdd == 3: return True\n else:\n oddFound = False\n numOdd = 0\n return False\n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n for i in range(len(arr)-2):\n newArr = arr[i:i+3]\n if newArr[0]%2 != 0 and newArr[1]%2 != 0 and newArr[2]%2 != 0:\n return True\n return False", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n number_of_cons_odds = 0\n \n for elem in arr:\n if elem % 2 == 0:\n number_of_cons_odds = 0\n continue\n \n number_of_cons_odds += 1\n if number_of_cons_odds == 3:\n return True\n \n return False", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n \n if len(arr) < 3:\n return False\n \n for i in range(len(arr)-2):\n if arr[i]%2 == 1 and arr[i+1]%2 == 1 and arr[i+2]%2 == 1:\n return True\n \n return False", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n return any(arr[i] % 2 != 0 and arr[i+1] % 2 != 0 and arr[i+2] % 2 != 0 for i in range(len(arr) - 2))", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n \n inds = [n%2 for n in arr]\n \n temp =[]\n for i, v in enumerate(inds):\n if v==1:\n temp.append(i)\n \n if len(temp)<3:\n return False\n \n for i in range(1, len(temp)-1):\n if (temp[i]-temp[i-1]==1) and (temp[i+1]-temp[i]==1):\n return True\n return False\n \n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n odd1 = False\n odd2 = False\n for num in arr:\n if num % 2:\n if odd2:\n return True\n odd2 = odd1\n odd1 = True\n else:\n odd1 = False\n odd2 = False\n \n return False\n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n odds = 0\n for i in range(len(arr)):\n if arr[i] % 2 != 0:\n odds += 1\n else:\n odds = 0\n if odds >= 3:\n return True\n return False\n \n", "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n for i in range(len(arr)-2):\n if arr[i] % 2 == 1 and arr[i+1]%2 == 1 and arr[i+2]%2 == 1:\n return True\n return False"] | {"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 lexicographicaly in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in words[i] and order are English lowercase letters. | ["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 if prev[k] == curr[k]:\n k += 1\n elif char_map[prev[k]] > char_map[curr[k]]:\n return False\n else:\n break\n if k >= len(curr):\n return False\n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n record = {o:i for i, o in enumerate(order)}\n \n def checkOrdered(w1, w2):\n p = min(len(w1), len(w2))\n i = 0\n while(i < p):\n if w1[i] == w2[i]:\n i += 1\n else:\n break\n if i != p:\n l, r = record[w1[i]], record[w2[i]]\n # l, r = order.index(w1[i]),order.index(w2[i]) \n if l < r:\n return True\n if l > r:\n return False\n else:\n return len(w1) <= len(w2)\n \n if len(words) <= 1:\n return True\n \n left = self.isAlienSorted(words[:len(words)//2], order)\n mid = checkOrdered(words[len(words)//2-1], words[len(words)//2])\n right = self.isAlienSorted(words[len(words)//2:], order)\n \n\n return left and right and mid\n", "class Solution:\n def alienCompare(self, word1: str, word2: str, order: str) -> int:\n if word1 == word2:\n return 0\n else:\n i: int = 0\n while i < len(word1) and i < len(word2) and word1[i] == word2[i]:\n i += 1\n if i == len(word1):\n return -1\n elif i == len(word2):\n return 1\n elif order.index(word1[i]) < order.index(word2[i]):\n return -1\n else:\n return 1\n \n def isAlienSorted(self, words: List[str], order: str) -> bool:\n n: int = len(words)\n if n == 0 or n == 1:\n return True\n else:\n for i in range(1, n):\n if self.alienCompare(words[i - 1], words[i], order) == 1:\n return False\n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n # shorter strings with common alphabets are always preferred in ordering\n # given the order, a O(m) dictionary mapping letter to a number can be made\n # and by iterating through every word and computing the sum of numbers,\n # when the number is smaller for earlier one, then terminate with False\n # if the loop finishes without returning False, then return True\n \n if len(words) == 1:\n return True\n \n i = 0\n\n lex_dict = {l: o for o, l in enumerate(order)}\n print(lex_dict)\n # for o in range(len(order)):\n # lex_dict[order[o]] = o + 1\n\n # instead of scrolling through each letter in all words,\n # just compare the pairs in the order (list is an ordered data structure anyway)\n \n prev_word = words[0]\n for i in range(1, len(words)):\n word = words[i]\n # do comparison\n # print(\\\"prev_word: {}, word: {}\\\".format(prev_word, word))\n for l1, l2 in zip(prev_word, word):\n if lex_dict[l2] < lex_dict[l1]:\n return False\n elif lex_dict[l2] > lex_dict[l1]:\n break # no need for further checking\n # # handle special case, if it survived and the length of prev_word is > word, return False\n else: # amazing trick! if no breakpoint occurred in the above for-loop, then come here\n if len(prev_word) > len(word):\n return False\n prev_word = word \n \n \n return True\n", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n for i in range(len(words)-1):\n s1,s2 = words[i],words[i+1]\n if not self.checkWords(s1,s2,order):\n return False\n return True\n \n def checkWords(self,s1,s2,order):\n for i in range(len(s1)):\n if i < len(s2):\n if s1[i] != s2[i]:\n if order.index(s1[i]) > order.index(s2[i]): return False\n return True\n else:\n return False\n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n index_lookup = {char: i for i,char in enumerate(order)}\n for i in range(len(words) - 1):\n first, second = words[i:i+2]\n for j in range(min(len(first), len(second))):\n if first[j] != second[j]:\n if index_lookup[first[j]] > index_lookup[second[j]]:\n return False\n break\n else:\n if len(first) > len(second):\n return False\n return True\n", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n '''\n Questions:are all char in the order? any missing? any duplicates?\n \n O(wn) len of longest word, compare all words\n order would be in a map to see\n \n '''\n word_indexes = {ch : i for i, ch in enumerate(list(order))}\n \n for i, word1 in enumerate(words[1:], start=1):\n word2 = words[i-1] # word before\n \n for j in range(min(len(word1), len(word2))):\n if word1[j] != word2[j]: # only compare when they are different\n if word_indexes[word1[j]] < word_indexes[word2[j]]:\n return False\n break\n else: # when break not hit\n # complete word but there is more characters for one of the words: \n # should be ordered after the shorter word\n if len(word1) < len(word2):\n # word before is longer\n return False\n \n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n d = {c: i for i, c in enumerate(order)}\n def compare(w1, w2):\n for i in range(min(len(w1), len(w2))):\n if d[w1[i]] < d[w2[i]]:\n return True\n if d[w1[i]] > d[w2[i]]:\n return False\n return len(w1) <= len(w2)\n \n for i in range(len(words) - 1):\n if not compare(words[i], words[i+1]):\n return False\n \n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n order_index = {c: i for i, c in enumerate(order)}\n\n for i in range(len(words) - 1):\n word1 = words[i]\n word2 = words[i+1]\n\n # Find the first difference word1[k] != word2[k].\n for k in range(min(len(word1), len(word2))):\n # If they compare badly, it's not sorted.\n if word1[k] != word2[k]:\n if order_index[word1[k]] > order_index[word2[k]]:\n return False\n break\n else:\n # If we didn't find a first difference, the\n # words are like (\\\"app\\\", \\\"apple\\\").\n if len(word1) > len(word2):\n return False\n\n return True", "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n \n order_map = {c: i for i, c in enumerate(order)}\n \n words = [[order_map[w] for w in word] for word in words]\n \n return all([w1<=w2 for w1,w2 in zip(words, words[1:])])\n \n \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,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.
Example 3:
Input: deck = [1]
Output: false
Explanation: No possible partition.
Example 4:
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].
Example 5:
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
Constraints:
1 <= deck.length <= 10^4
0 <= deck[i] < 10^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]+=1\n else:\n hash_cards[card]=1\n value_ = list(hash_cards.values())\n res = value_[0]\n for x in value_[1:]:\n res = findGCD(res,x)\n if res <2:\n return False\n return True\n \n", "class Solution:\n def gcd(a,b):\n if(b%a==0):\n return a \n else: \n if(a%b==0):\n return b\n else:\n if b>a:\n return gcd(a,b-a) \n else:\n return gcd(a-b,b) \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if(len(deck)==0 or len(deck)==1):\n return False\n d=list(set(deck))\n if(len(d)==1 and len(deck)>=2):\n return True\n s=gcd(deck.count(d[0]),deck.count(d[1]))\n if(s<2):\n return False\n for i in range(2,len(d)):\n if(gcd(s,deck.count(d[i]))<2):\n return False\n s=gcd(s,deck.count(d[i]))\n \n return True ", "def gcd (a,b):\n if (b == 0):\n return a\n else:\n return gcd (b, a % b)\n \nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n arr = {}\n for i in range(len(deck)):\n if deck[i] in arr:\n arr[deck[i]] += 1\n else:\n arr[deck[i]] = 1\n list1 = list(arr.values())\n mi = list1[0]\n for c in list1[1::]:\n mi = gcd(mi , c)\n if mi < 2:\n return False\n for i in list(arr.values()):\n if i % mi != 0:\n return False\n return True\n", "class Solution:\n def gcd(self,a,b):\n if b == 0:\n return a\n else:\n return gcd(b,a%b)\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n\n hashmap = {}\n for i in range(len(deck)):\n try:\n hashmap[deck[i]] += 1\n except:\n hashmap[deck[i]] = 1\n vals = set(list(hashmap.values()))\n gcd_val = next(iter(vals))\n \n for i in vals:\n gcd_val = gcd(gcd_val,i)\n if gcd_val == 1:\n return False\n return True ", "class Solution:\n \n def fill(self,A,B):\n for i in range(len(A)):\n B[A[i]] +=1\n return list(filter(lambda a : a != 0,B))\n \n def mcd(self,arr):\n MCD = min(arr)\n for i in range (1,len(arr)):\n MCD = math.gcd(MCD,arr[i])\n return MCD\n \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if len(deck) < 2:\n return False\n deck.sort()\n B = [0] * (max(deck) + len(deck))\n B = self.fill(deck,B)\n \n for i in range(len(B)-1):\n if B[i] == 1 :\n return False\n \n MCD = self.mcd(B)\n if MCD == 1:\n return False\n \n return True", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n hashMap = {}\n boolean = False\n lenght = len(deck)\n if lenght < 2:\n return False\n \n def commonFactor(a,b): \n if(b==0): \n return a \n else: \n return commonFactor(b,a%b) \n \n for i in range(lenght):\n if hashMap.get(deck[i]) is not None:\n hashMap[deck[i]] = hashMap[deck[i]] + 1\n else:\n hashMap[deck[i]] = 1\n \n for i in range(lenght):\n if hashMap[deck[i]] == 1:\n return False\n elif i < lenght-1 and commonFactor(hashMap[deck[i]],hashMap[deck[i+1]]) > 1:\n boolean = True\n elif i == lenght-1 and commonFactor(hashMap[deck[i]],hashMap[deck[i-1]]) > 1:\n boolean = True\n else:\n return False\n return boolean", "class Solution:\n def hasGroupsSizeX(self, deck):\n count = collections.Counter(deck)\n N = len(deck)\n for X in range(2, N+1):\n if N % X == 0:\n if all(v % X == 0 for v in count.values()):\n return True\n return False", "class Solution:\n def commondenominator(self, a, b):\n temp = b\n while(temp > 1):\n #print(\\\"temp:\\\", temp, \\\"a:\\\", a, \\\"b:\\\", b)\n if a % temp == 0 and b % temp == 0:\n return temp\n temp -= 1\n return -1 \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if not deck or len(deck) < 2:\n return False\n d = dict()\n for x in deck:\n if x not in d:\n d[x] = 1\n else:\n d[x] += 1\n #print(\\\"d:\\\", d)\n mini = float('inf')\n ret = 1\n for x in d: \n if mini == float('inf'):\n mini = d[x]\n continue\n if d[x] != mini: \n ret = self.commondenominator(d[x], mini)\n #print(\\\"ret:\\\", ret)\n if ret < 0:\n return False\n else:\n mini = ret \n #print(\\\"mini:\\\", mini) \n return True \n", "from functools import reduce\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n from fractions import gcd\n vals = list(collections.Counter(deck).values())\n return reduce(gcd, vals) >=2\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n N = len(deck)\n \n if N<=2:\n if N==1:\n return False\n \n if len(set(deck))==1:\n return True\n else:\n return False\n \n cardCount = defaultdict(int)\n \n for card in deck:\n cardCount[card]+=1\n \n gcd = list(cardCount.values())[0]\n \n for val in list(cardCount.values())[1:]:\n gcd = math.gcd(gcd,val)\n \n return True if gcd>=2 else False\n \n \n \n \n \n \n \n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n from collections import Counter\n \n cards = Counter(deck)\n \n min_cnt = min(cards.values())\n \n for i in range(2, min_cnt+1):\n divided = [v%i for v in list(cards.values())]\n if not any(divided):\n return True\n \n return False\n \n \n \n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n count = collections.Counter(deck)\n N = len(deck)\n for X in range(2, N+1):\n if N % X == 0:\n if all(v % X == 0 for v in list(count.values())):\n return True\n return False\n \n", "from collections import Counter\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if(len(deck) < 2): return False \n deck_count = Counter(deck)\n v = set(deck_count.values())\n min_v = min(v)\n v_dict = dict()\n all_factors = set()\n for num in v :\n for j in range(2, min_v + 1):\n if(num % j == 0):\n if(num in v_dict): v_dict[num].add(j)\n else:\n v_dict[num] = set()\n v_dict[num].add(j)\n all_factors.add(j)\n if(len(v_dict) != len(v)): return False\n for i in list(v_dict.values()):\n all_factors = all_factors.intersection(i)\n if(len(all_factors) > 0):\n return True\n return False\n \n", "class Solution:\n def hasGroupsSizeX(self, deck):\n def gcd(a, b):\n while b: \n a, b = b, a % b\n return a\n count = [*list(Counter(deck).values())]\n # print(count)\n g = count[0]\n for i in range(len(count)):\n g = gcd(g, count[i])\n if g == 1:\n return False\n return True\n \n \n # return reduce(gcd, count) > 1\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n deck1=list(set(deck))\n len1=[]\n for j in range(len(deck1)):\n leny=len([number for number in deck if number ==deck1[j]])\n len1.append(leny)\n count=2\n while(count<=len(deck)):\n if len(deck)%count==0:\n ty=len([number for number in len1 if number%count > 0])\n if ty==0:\n return True\n break\n count=count+1\n return False\n\n", "def gcd (a,b):\n if (b == 0):\n return a\n else:\n return gcd (b, a % b)\n \nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n # arr = {}\n # for i in range(len(deck)):\n # if deck[i] in arr:\n # arr[deck[i]] += 1\n # else:\n # arr[deck[i]] = 1\n count = list(collections.Counter(deck).values())\n list1 = list(count)\n mi = list1[0]\n for c in list1[1::]:\n mi = gcd(mi , c)\n if mi < 2:\n return False\n for i in count:\n if i % mi != 0:\n return False\n return True\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n counter=collections.Counter(deck);\n # check if X>=2\n \n for i in counter:\n if(counter[i]<2):\n return False\n cur_gcd=0\n for i in counter:\n cur_gcd=gcd(cur_gcd, counter[i])\n if cur_gcd==1:\n return False\n return True\n \n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n count = collections.Counter(deck)\n \n val = list(count.values())\n gcd =val[0]\n \n for i in val[1:]:\n gcd = math.gcd(i, gcd)\n \n #print(gcd)\n return gcd>=2", "class Solution:\n def hasGroupsSizeX(self, deck):\n count = Counter(deck)\n N = len(deck)\n # for X in range(2, N+1):\n # if N % X == 0:\n # if all(v % X == 0 for v in count.values()):\n # return True\n g = lambda X: all(v % X == 0 for v in count.values())\n f = lambda X: not N % X and g(X)\n return any(map(f, range(2, N+1)))\n return False", "class Solution:\n def fun(m,k,c):\n for i in k:\n if len(i)==m:\n g=len(i)//m\n c+=g\n elif len(i)%m==0:\n c+=len(i)//m\n return c \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n deck.sort()\n l=[]\n k=[]\n l.append(deck[0])\n for i in range(1,len(deck)):\n if l[-1]!=deck[i]:\n k.append(l)\n l=[]\n l.append(deck[i])\n k.append(l)\n k.sort()\n j=len(k[0])\n if len(k[-1])==1:\n return(bool(0))\n for i in range(2,len(deck)+1):\n c=0\n c+=Solution.fun(i,k,c)\n if len(deck)/i==c:\n return(bool(1))\n return(bool(0)) ", "def compute_gcd(a, b):\n if(b == 0):\n return a \n else:\n return compute_gcd(b, a % b)\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n max_size = int(1e4 + 1)\n n = len(deck)\n freq = [0 for _ in range(max_size)]\n \n for i in range(n):\n freq[deck[i]] += 1\n \n gcd = freq[deck[0]]\n \n for i in range(max_size):\n gcd = compute_gcd(gcd, freq[i])\n \n if gcd == 1: return False\n \n return True", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n d = collections.Counter(deck)\n parts = {}\n #for num in deck: d[num] = d.get(num,0)+1\n for key in d:\n m = d[key]\n if(m==1):return False\n parts[m] = parts.get(m,0)+1\n i = 2\n while(m/i>=2):\n if(m%i==0):parts[m//i] = parts.get(m//i,0)+1\n i+=1\n for key in parts:\n if(parts[key]==len(d)):return True\n return False\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n from collections import Counter\n from math import gcd\n c=Counter(deck)\n cur_g=0\n for i in c.values():\n cur_g=gcd(cur_g,i)\n return cur_g>1", "class Solution:\n def checkMultiple(self, num, maxLCM):\n d = 2\n while d <= maxLCM:\n if num % d == 0:\n return True\n d += 1\n return False\n \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n intCnt = {}\n for num in deck:\n if num not in intCnt:\n intCnt[num] = 0\n intCnt[num] += 1\n i = 1\n n = len(intCnt)\n cnts = list(intCnt.values())\n cnts.sort()\n leastDiff = None\n leastCnt = cnts[0]\n while i < n:\n curDiff = cnts[i] - cnts[i-1]\n if leastDiff == None or curDiff < leastDiff:\n leastDiff = curDiff\n if cnts[i] < leastCnt:\n leastCnt = cnts[i]\n i += 1\n if leastDiff == 0 or leastDiff == None:\n leastDiff = leastCnt\n for num in intCnt:\n if intCnt[num] < 2 or leastDiff <= 1 or not self.checkMultiple(intCnt[num], leastDiff):\n return False\n return True", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n num = dict()\n for i in range(len(deck)):\n if not deck[i] in list(num.keys()):\n num[deck[i]]=1\n else:\n num[deck[i]]+=1\n \n minv = 10005\n for key,value in list(num.items()):\n if value < minv:\n minv = value\n \n if minv<2:\n return False\n \n possible_share=[]\n for i in range(2, minv+1): ## !!! max i is minv\n if minv % i ==0:\n possible_share.append(i)\n \n for i in possible_share:\n Flag = True\n for key,value in list(num.items()):\n if value % i !=0:\n Flag = False\n break\n if Flag:\n return True\n \n return False\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n seen = {}\n for card in deck:\n if card in seen:\n seen[card] += 1\n else:\n seen[card] = 1\n \n for i in range(2, len(deck)+1):\n if self.helper(seen, i):\n return True\n\n return False\n \n def helper(self, seen, val):\n for key,item in list(seen.items()):\n if item % val != 0:\n return False\n return True\n", "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n if len(deck) <= 1:\n return False\n \n dict1 = {}\n \n for ele in deck:\n if ele in dict1:\n dict1[ele] += 1\n else:\n dict1[ele] = 1\n \n for i in range(2,len(deck)+1):\n if all(v%i==0 for v in list(dict1.values())):\n return True\n \n return False\n \n", "import collections\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n if len(deck) <= 1:\n return False\n \n dict1 = collections.Counter(deck)\n \n for i in range(2,len(deck)+1):\n if all(v%i==0 for v in list(dict1.values())):\n return True\n \n return False\n \n"] | {"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 = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Example 3:
Input: s = "triplepillooooow"
Output: 5
Example 4:
Input: s = "hooraaaaaaaaaaay"
Output: 11
Example 5:
Input: s = "tourist"
Output: 1
Constraints:
1 <= s.length <= 500
s contains only lowercase English letters. | ["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 \n if (i < n - 1 and \n s[i] == s[i + 1]): \n cur_count += 1\n \n # If doesn't match, update result \n # (if required) and reset count \n else: \n if cur_count > count: \n count = cur_count \n res = s[i] \n cur_count = 1\n return count \n \n \n \n", "class Solution:\n def maxPower(self, s: str) -> int:\n cnt = 0\n current = s[0]\n current_cnt = 1\n for l in s[1:]:\n if l == current:\n current_cnt += 1\n else:\n if current_cnt > cnt:\n cnt = current_cnt\n current = l\n current_cnt = 1\n if current_cnt > cnt:\n cnt = current_cnt\n return cnt", "class Solution:\n def maxPower(self, s: str) -> int:\n\n count = 0\n new_count = 0\n for i,char in enumerate(s):\n\n print(char)\n try:\n if s[i+1] == char:\n new_count += 1\n else:\n print('afwww')\n if new_count >= count:\n count = new_count\n new_count = 0\n except:\n print('sefesf')\n if new_count >= count:\n print('sfwafawfawfawfawfawf')\n count = new_count\n new_count = 0\n break\n\n return count+1\n", "class Solution:\n def maxPower(self, s: str) -> int:\n c = {'power': 1}\n for i in range(len(s)) :\n if i == len(s)-1 :\n break\n if ord(s[i]) == ord(s[i+1]) :\n c['power'] += 1\n\n else:\n c['new start#%s' % i] = c['power']\n c['power'] = 1\n return max(c.values())", "class Solution:\n def maxPower(self, s: str) -> int:\n power = 1\n max_power = 0\n for idx, i in enumerate(s):\n if len(s) < 2:\n return len(s)\n if idx == 0: \n pass\n elif i == s[idx -1]:\n power += 1\n print(f' i is {i}, power is {power}')\n else:\n print(f' i is {i}, power is {power}')\n if power > max_power:\n max_power = power\n power = 1\n return max(power, max_power)", "class Solution:\n def maxPower(self, s: str) -> int:\n '''\n does: given a string s, the power of the string is the maximum length of \n a non-empty substring that contains only one unique character.\n parameters: s\n returns: the power of the string.\n '''\n # initialize the letter to None\n letter = None\n # initialize the temporary length and maximum length to 0\n length = 0\n max_length = 0\n\n # loop through the string\n for i in s:\n\n # if encountered the same letter, length plus one\n if i == letter:\n length += 1\n # set maximum length to the max of (max_length, length, 1)\n max_length = max(max_length, length)\n\n # if encountered a different letter\n else:\n # set maximum length to the max of (max_length, length, 1)\n max_length = max(max_length, length, 1)\n # reset the length to 0\n length = 1\n # reset the target to current letter\n letter = i\n print(i, max_length)\n\n return max_length", "class Solution:\n def maxPower(self, s: str) -> int:\n z=[]\n c=0\n if len(s)==1:\n return 1\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n c=c+1\n else:\n z.append(c)\n c=0\n z.append(c)\n return max(z)+1\n", "class Solution:\n def maxPower(self, s: str) -> int:\n if len(s) <= 1:\n return len(s)\n last_char = s[0]\n count = 1\n max_count = 0\n for c in s[1:]:\n if c == last_char:\n count += 1 \n else:\n if count > max_count:\n max_count = count\n count =1 \n \n last_char =c\n if count > max_count:\n max_count = count\n \n return max_count\n", "class Solution:\n def maxPower(self, s: str) -> int:\n prev = None\n count = 0\n max_count = 0\n for char in s:\n if char == prev:\n count +=1\n else:\n prev = char\n count =1\n max_count = max(max_count,count)\n return max_count", "class Solution:\n def maxPower(self, s: str) -> int:\n \n seq = 1\n max_seq = 1\n \n for i in range(1, len(s)):\n \n if s[i] == s[i-1]:\n seq += 1\n else:\n max_seq = max(max_seq, seq)\n seq = 1\n \n max_seq = max(max_seq, seq)\n return max_seq\n \n", "class Solution:\n def maxPower(self, s: str) -> int:\n count=0\n max_count=0\n previous=None\n for c in s:\n if c!=previous:\n previous=c\n count=1\n else:\n count+=1\n max_count=max(max_count,count)\n return max_count", "class Solution:\n def maxPower(self, s: str) -> int:\n # Assign variables\n ans = 0\n consec_count_per_letter = 1\n prev_letter = s[0]\n\n # Return 1 when the length of the input is 1\n if len(s) == 1:\n return 1\n\n # Loop from 1 to the length of the input\n for i in range(1, len(s)):\n # If the current letter is the same as the prev letter,\n # then add 1 to consec_count_per_letter\n if s[i] == prev_letter:\n consec_count_per_letter += 1\n else:\n consec_count_per_letter = 1\n\n # Update the prev letter\n prev_letter = s[i]\n # Update the answer with a maximum\n # between the answer and consec_count_per_letter\n ans = max(ans, consec_count_per_letter)\n\n return ans\n", "class Solution:\n def maxPower(self, s: str) -> int:\n c = 1\n maxc = c\n for i in range(len(s)-1): \n if s[i] == s[i+1]: \n c +=1\n maxc = max(maxc, c)\n else: \n c = 1\n \n return maxc\n", "class Solution:\n def maxPower(self, s: str) -> int:\n maxcount = 1\n i = 0 \n while i < len(s)-1 :\n count = 1\n while i < len(s)-1 and s[i] == s[i+1] :\n i = i +1 \n count = count +1 \n if( count > maxcount ) :\n maxcount = count\n if ( i <len(s) -1) :\n i = i+1\n return maxcount\n \n \n"] | {"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 other as original.
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000] | ["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, s, k):\n res = ''\n i = 0\n while i < len(s):\n if i + k <= len(s) and i + 2 * k > len(s) or i + k > len(s):\n sub = s[i:i + k]\n res += sub[::-1]\n if i + 2 * k > len(s):\n res += s[i + k:]\n i = len(s)\n else:\n sub = s[i:i + k]\n res += sub[::-1]\n res += s[i + k:i + 2 * k]\n i += 2 * k\n return res\n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n list_s = list(s)\n n = len(list_s)\n for i in range(0,n,2*k):\n if n-i>=k:\n list_s[i:i+k] = reversed(list_s[i:i+k])\n elif n-i<k:\n list_s[i:] = reversed(list_s[i:])\n \n return ''.join(list_s)", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n n = len(s)\n p = 0\n \n s = list(s)\n \n while True:\n if p >= n:\n break\n p1 = p + k\n if p1>n:\n p1 = n\n p0 = p\n while p0 < p1:\n p1-=1\n s[p0], s[p1] = s[p1],s[p0]\n p0+=1\n p += k*2\n return ''.join(s)\n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n rst = \"\"\n for i in range(len(s)):\n if (i // k) % 2:\n rst += s[i]\n else:\n rst += s[min(len(s),(i//k+1)*k)-i%k-1]\n return rst ", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n output_chars = list()\n num_segments = (len(s) // k) + 1\n for j in range(num_segments):\n start = 2*j*k\n end = 2*(j+1)*k\n reverse_up_to = min(start+k, len(s))\n seg = min(start+2*k, len(s))\n for i in range(reverse_up_to - 1, start-1, -1):\n output_chars.append(s[i])\n for i in range(reverse_up_to, seg):\n output_chars.append(s[i])\n return ''.join(output_chars)\n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n for i in range(0,len(s),2*k):\n s1 = s[0:i]\n s2 = s[i:i+k][::-1]\n s3 = s[i+k:]\n s = s1 + s2 + s3\n return s\n \n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n result = ''\n for i in range(0, len(s), 2*k):\n result += s[i:i+k][::-1]\n result += s[i+k:i + 2*k ]\n return result", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n # l = s.split()\n r = []\n k_str = ''\n for i in range(len(s)):\n if i%k == 0:\n if i != 0:\n r.append(k_str)\n k_str = s[i]\n else:\n k_str += s[i]\n r.append(k_str)\n for i in range(len(r)):\n if i%2 == 0:\n r[i] = r[i][::-1]\n return \"\".join(r)\n \n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n l = []\n i = 0\n c = 0\n strlen = len(s)\n while(i < strlen):\n if(c % 2):\n l.append(s[i:i+k])\n else:\n temp = s[i:i+k]\n l.append(temp[::-1])\n c = c+1\n i = i+k\n return ''.join(l)\n \n \n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n w = []\n idx = 0\n while idx < len(s):\n w.append(s[idx:idx + k])\n idx += k\n w = [w[i][::-1] if i % 2 == 0 else w[i] for i in range(len(w))]\n return ''.join(w)", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n s = list(s)\n for i in range(0,len(s), 2*k):\n s[i:i+k] = reversed(s[i:i+k])\n s = \"\".join(s)\n return s", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n \n ls = [c for c in s]\n for i in range(0, len(s), 2*k):\n start = i\n end = min(i+k, len(s)) - 1\n if end >= len(s):\n break\n while end > start:\n swp = ls[start]\n ls[start] = ls[end]\n ls[end] = swp\n start += 1\n end -= 1\n \n return \"\".join(ls)", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n s = list(s)\n for i in range(0 , len(s), 2*k) :\n s[i:i+k] = reversed(s[i:i+k])\n return ''.join(s)\n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n s = list(s)\n for start in range(0, len(s), 2*k):\n p1 = start\n p2 = p1 + k - 1\n if p2 >= len(s):\n p2 = len(s) - 1\n while p1 < p2:\n s[p1], s[p2] = s[p2], s[p1]\n p1 += 1\n p2 -= 1\n result = ''\n for ele in s:\n result += ele\n return result", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n \n i = 0\n tmp = 0\n ret = \"\"\n while i < len(s):\n if len(s)-i < k:\n tmp = len(s)-i\n else:\n tmp = k\n ttmp = tmp \n while ttmp!= 0:\n ret += s[i+ttmp-1]\n ttmp -= 1\n \n i+=tmp\n if len(s)-i < k:\n tmp = len(s)-i\n else:\n tmp = k\n ttmp = tmp\n \n while ttmp!= 0:\n ret += s[i]\n i+=1\n ttmp -= 1\n \n return ret", "class Solution:\n def reverseStr(self, s, k):\n ans = \"\"\n i = 0\n \n while i < len(s):\n rev = \"\"\n j = 0\n while i + j < len(s) and j < k:\n rev += s[i + j]\n j += 1\n i += j\n ans += rev[::-1]\n j = 0\n while i + j < len(s) and j < k:\n ans += s[i + j]\n j += 1\n i += j\n return ans\n \n \n", "class Solution:\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n a = list(s)\n for i in range(0,len(a),2*k):\n a[i:i+k] = reversed(a[i:i+k])\n \n return ''.join(a)"] | {"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 (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0. | ["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 if lastPrice < price:\n profits+= (price-lastPrice)\n lastPrice = price\n return profits\n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n maxprofit = 0\n for i in range(1, len(prices)):\n if prices[i]> prices[i-1]:\n maxprofit += prices[i] - prices[i-1]\n return maxprofit\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices or len(prices)==1:\n return 0\n ans=0\n for i in range(len(prices)-1,0,-1):\n prices[i]-=prices[i-1]\n for i in range(1,len(prices),1):\n if prices[i]>0:\n ans+=prices[i]\n return ans\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n prof = 0\n for j in range(len(prices)-1):\n if prices[j+1]>prices[j]:\n prof += prices[j+1]-prices[j]\n return prof\n \n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n cum = 0\n for iprice in range(1, len(prices)):\n if prices[iprice-1] < prices[iprice]:\n cum += prices[iprice] - prices[iprice-1]\n return cum", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n #\u7a7a\u6216\u8fd9\u6709\u4e00\u4e2a\uff0c\u4e0d\u5356\n \n if len(prices) < 2:\n return 0\n #\u521d\u59cb\u5316\u4e00\u4e2a\u6700\u5927\u503c\uff0c\u5176\u5b9e\u53ea\u8981\u6700\u540e\u4e00\u4e2a\u6570\u6bd4\u5012\u6570\u7b2c\u4e8c\u4e2a\u6570\u5927\uff0c\u5c31\u53ef\u4ee5\u4ea7\u751f \u6700\u540e\u4e00\u4e2a\u6570\u4e0e\u5012\u6570\u7b2c#\u4e8c\u6570\u7684\u5dee\u503c\u7684\u3002\u4e0d\u7ba1\u6700\u540e\u4e00\u6b21\u5728\u4ec0\u4e48\u65f6\u5019\u5356\u7684\n max1 = 0\n for i in range(1,len(prices)):\n print(max1)\n max1 += max(0,prices[i] - prices[i-1])\n return max1\n \n \n \n \n \n \n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n profit = 0\n for i in range(0, len(prices)-1):\n if prices[i] < prices[i+1]:\n profit = profit + prices[i+1] - prices[i]\n return profit", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n return sum(max(prices[i] - prices[i - 1], 0) for i in range(1, len(prices)))", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) == 0:\n return 0\n hold = -prices[0]\n sell = 0;\n for i in range(1, len(prices)):\n sell = max(sell, hold + prices[i])\n hold = max(hold, sell - prices[i])\n return max(hold, sell)\n", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # 7 2 3 4 1 5 3 4\n # 7 3 2 1 5 7 9 4 5\n if len(prices) < 2:\n return 0\n buy = prices[0] #1\n sell = -1\n profit = 0\n i = 1\n while i < len(prices):\n if buy >= prices[i]:\n if sell> -1:\n profit += sell-buy #15\n sell = -1\n buy = prices[i] # 2\n else:\n buy = prices[i] #1\n if prices[i] > buy:\n if prices[i] > sell:\n sell = prices[i] #9\n else:\n profit+=sell - buy #\n sell = -1 \n buy = prices[i] #2\n \n \n i+=1\n if sell>-1:\n profit+=sell - buy\n return profit\n", "class Solution:\n # @param prices, a list of integer\n # @return an integer\n def maxProfit(self, prices):\n p = 0;\n for i in range(1, len(prices)):\n profit = prices[i] - prices[i-1]\n if profit > 0:\n p += profit\n return p", "class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # maximum profit at day i(assume i starts at 1)\n # doesn't sell: profit[i] = profit[i-1]\n # the index for prices subtract by 1\n # buy at day j, sell at day i: profit[i] = prices[i-1] + (profit[j-1]-prices[j-1])\n # if j=1: profit[i] = prices[i-1] + profit[0] - prices[0]\n # if j=(i-1): profit[i] = prices[i-1] + profit[i-2] - prices[i-2]\n # if i >= 2: profit[i] = max(profit[i-1], prices[i-1] + max(profit[j]-prices[j])(0<=j<=i-2))\n # if i == 1: profit[i] = profit[i-1]\n if len(prices) < 2: return 0\n profit = [0] * (len(prices) + 1)\n pro_minus_pri = profit[0] - prices[0]\n for i in range(2, len(prices) + 1):\n profit[i] = max(profit[i-1], prices[i-1] + pro_minus_pri)\n pro_minus_pri = max(profit[i-1] - prices[i-1], pro_minus_pri)\n return profit[len(prices)]\n", "class Solution:\n def maxProfit(self, prices):\n maxprofit = 0\n for i in range(1,len(prices)):\n if prices[i] > prices[i-1]:\n maxprofit += prices[i] - prices[i-1]\n return maxprofit"] | {"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 derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
Example 1:
Input: "aba", "cdc"
Output: 3
Explanation: The longest uncommon subsequence is "aba" (or "cdc"), because "aba" is a subsequence of "aba", but not a subsequence of any other strings in the group of two strings.
Note:
Both strings' lengths will not exceed 100.
Only letters from a ~ z will appear in input strings. | ["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 :type b: str\n :rtype: int\n \"\"\"\n if a == b:\n return -1\n \n if len(a) > len(b):\n return len(a)\n elif len(b) > len(a):\n return len(b)\n else:\n return len(a)", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n \n return -1 if a == b else max(len(a), len(b))\n", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n if len(a) != len(b):\n return max(len(a),len(b))\n elif a==b:\n return -1\n else:\n return len(a)", "class Solution:\n def findLUSlength(self, a, b):\n if len(a) != len(b):\n return max(len(a), len(b))\n else:\n if a == b:\n return -1\n else:\n return len(a)\n", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n m = len(a)\n n = len(b)\n if m != n:\n return max(m, n)\n else:\n if a != b:\n return m\n else:\n return -1", "class Solution:\n def findLUSlength(self, a, b):\n return -1 if a==b else max(len(a), len(b))\n", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n if a == b:\n return -1\n else:\n return max(len(a), len(b))", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n return -1 if a == b else max(len(a), len(b)) ", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n if len(a) < len(b): a, b = b, a\n l = len(a)\n c = -1\n for rg in range(1, l+1):\n for i in range(l - rg + 1):\n s = a[i:i+rg]\n if b.find(s) == -1:\n if len(s) > c: c = len(s)\n return c", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n result = 0 \n for i in range(len(a)):\n for j in range(i+1,len(a)+1):\n if a[i:j] not in b and len(a[i:j])>result:\n result = len(a[i:j])\n for i in range(len(b)):\n for j in range(i+1,len(b)+1):\n if b[i:j] not in a and len(b[i:j])>result:\n result = len(b[i:j])\n if not result:\n return -1\n return result\n", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n m = len(a)\n n = len(b)\n if m != n:\n return max(m, n)\n else:\n if a != b:\n return m\n else:\n return -1", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n return -1 if a == b else max(len(a), len(b))\n", "class Solution:\n def findLUSlength(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n if a == b:\n return -1\n else:\n return max(len(a), len(b))"] | {"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] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 1000 | ["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 # return total\n \n total = 0\n for i in range(len(arr)):\n totalisubarrays = (len(arr) - i) * (i+1) #this represent total number of subarrays in list that has either i as start or end.\n if totalisubarrays % 2 == 1:\n totalisubarrays += 1\n oddisubarrays = totalisubarrays//2\n total += arr[i]*oddisubarrays\n return total\n \n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n ans = 0\n n = len(arr)\n for i, j in enumerate(arr):\n ans += ((i + 1) * (n - i) + 1) // 2 * j\n return ans\n \n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n \n total = 0\n length = 1\n \n while length <= len(arr):\n for i in range(len(arr)-length+1):\n total += sum(arr[i:i+length])\n length += 2\n \n return total", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n l=len(arr)\n s=0\n for i in range(l):\n for j in range(i+1,l+1,2):\n subarr=arr[i:j]\n s+=sum(subarr)\n return s\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total = 0\n size = len(arr)\n\n for n in range(1, size + 1, 2):\n for i in range(size - (n - 1)):\n total += sum(arr[i:i+n])\n\n return total", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n li = []\n sumv = 0\n n = len(arr)\n for i in range(1, n + 1, 2):\n li.append(i)\n for i in li:\n for j in range(len(arr)):\n if i + j <= n:\n sumv += sum(arr[j:j + i])\n else:\n break\n return sumv\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n l = len(arr)\n sumtotal = 0\n for i in range (1,l+1,2):\n for j in range(1,l+1):\n if (j+i-1 < l+1):\n sumtotal += sum(arr[j-1:j+i-1])\n return(sumtotal)\n \n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n res = 0\n n = len(arr)\n \n for k in range(1, n + 1, 2):\n for i, v in enumerate(arr):\n res += v * min(n - k + 1, k, i + 1, n - i)\n \n return res", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total_sum = 0\n sum_arr = [[0] * (len(arr) + 1) for i in range (len(arr))]\n for i in range (len(arr)):\n for j in range (len(arr) - i):\n start = j\n end = j + i + 1\n sub_sum = 0\n if (end - start) == 1:\n sum_arr[start][end] = arr[start]\n sub_sum = arr[start]\n else:\n sub_sum = arr[start] + sum_arr[start + 1][end]\n sum_arr[start][end] = sub_sum\n if ((end - start) % 2 == 1):\n total_sum += sub_sum\n return total_sum\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n if arr == []:\n return 0\n \n sum_ = 0\n \n for i in range(len(arr)):\n for j in range(i + 1, len(arr) + 1):\n val = arr[i : j]\n if len(val) % 2 != 0:\n sum_ += sum(val)\n \n return sum_", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total_sum = 0\n for i in range (len(arr)):\n for j in range (len(arr) - i):\n start = j\n end = j + i + 1\n sub_arr = arr[start:end]\n if ((end - start) % 2 == 1):\n total_sum += sum(sub_arr)\n return total_sum\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n result = 0\n for i in range(1, len(arr) + 1, 2):\n for j in range(0, len(arr) + 1 - i):\n print(j, j + i)\n result += sum(arr[j : j+i])\n \n return result", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n ret = 0\n for i in range(len(arr)):\n ret += arr[i] * ceil((len(arr) - i ) * (i + 1) /2)\n return ret\n \n # 1: 3\n # 4: 3\n # 2: 5\n # 5: 3\n# # 3: 3\n \n# (5-0)//2 -> 2\n# 0//2-> 0\n# (5-1)//2 -> 2\n# 1//2 -> 0\n# (5-2)//2 -> 1\n# 2//2 -> 1\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n xdict = {}\n print(arr[0:1])\n for i in range(0, len(arr)):\n sumx = 0\n for j in range(0,len(arr)-i):\n sumx = sumx + sum(arr[j:j+i+1])\n xdict[i] = sumx\n \n print(xdict)\n sumx = 0\n for i in xdict:\n if i % 2 == 0:\n sumx = sumx + xdict[i]\n \n return sumx", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n s=0\n for i in range(1,len(arr)+1,2):\n for j in range(len(arr)):\n if len(arr[j:j+i])==i:\n s=s+sum(arr[j:j+i])\n # print(arr[j:j+i],sum(arr[j:j+i]))\n return s\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total = 0\n \n for i in range(len(arr)):\n for j in range(len(arr)):\n a = arr[i:j + 1]\n \n if not len(a) % 2 == 0:\n total += sum(a)\n return total", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n m=len(arr)\n s=0\n a=[]\n\n for i in range(m):\n t=0\n while t<=m:\n a=arr[i:t]\n t+=1\n if len(a)%2!=0:\n s=s+sum(a)\n return(s)\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n arrayLength = len(arr) + 1\n oddLengthSum = 0\n \n if (arrayLength <= 2):\n return sum(arr)\n \n for subArrayLength in range(arrayLength)[1::2]:\n for i in range(arrayLength - subArrayLength):\n for value in arr[i:i + subArrayLength]:\n oddLengthSum += value\n \n return oddLengthSum\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n ans = 0\n i = 0\n j = 1\n while True:\n if i > len(arr)-1:\n break\n if len(arr[i:j]) % 2 != 0:\n ans = ans + sum(arr[i:j])\n j += 1\n if j > len(arr):\n i += 1\n j = i+1\n return ans\n \n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n# subArrayLengths = []\n# for i in range(len(arr)):\n# if (i+1)%2!=0:\n# subArrayLengths.append(i+1)\n# print(subArrayLengths)\n \n# subSum=0\n# totalSum=0\n# totalSum=0\n# subSum=0\n# flag=True\n# subIndex=0\n# while flag==True:\n \n \n \n \n# if subIndex==len(arr) or subIndex==len(arr)-1:\n# flag = False\n# else:\n# subIndex+=2\n# return totalSum\n \n flag = True \n i=1\n subSum = 0\n totalSum = 0\n while flag:\n subFlag = True\n start = 0\n end = i\n while subFlag:\n for j in arr[start:end]:\n subSum+=j\n if end == len(arr):\n totalSum += subSum\n print((subSum, totalSum))\n\n subSum = 0\n subFlag=False\n else:\n start +=1\n end += 1\n if i == len(arr) or i == len(arr)-1:\n flag = False\n else:\n i += 2\n \n return totalSum\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n s = 0\n s+=sum(arr)\n \n for j in range(3, len(arr)+1, 2):\n for i in range(0, len(arr)):\n if(len(arr[i:i+j])%2 != 0 and len(arr[i:i+j]) != 1 and i+j<=len(arr)):\n s+=sum(arr[i:i+j])\n return s", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n ret = 0\n subArrs = []\n starting = 0\n ending = len(arr)\n\n for i in range(len(arr)):\n while (ending >= starting):\n if ((ending - starting) % 2 != 0):\n subArrs += [arr[starting:ending]]\n ending -= 2\n else:\n ending -= 1\n starting += 1\n ending = len(arr)\n\n for i in subArrs:\n for j in i:\n ret += j \n \n return ret", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n res, n = 0, len(arr)\n for i, a in enumerate(arr):\n res += ((i + 1) * (n - i) + 1) // 2 * a\n return res\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n return self.backtrack(arr, 0, 0, 0)\n \n def backtrack(self, arr,i,end, s):\n if end == len(arr):\n return s\n elif i > end:\n return self.backtrack(arr, 0, end+1,s)\n else:\n if len(arr[i:end+1]) % 2 != 0:\n s += sum(arr[i:end+1])\n return self.backtrack(arr, i+1, end,s)\n else:\n return self.backtrack(arr, i+1, end,s)", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n res = sum(arr)\n for i in range(0, len(arr)):\n count = 2\n while (i+count) < len(arr):\n for j in range(i,count+i+1):\n res += arr[j]\n count += 2\n return res\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total = 0\n size = len(arr)\n\n for n in range(1, size + 1, 2):\n for i in range(size - (n - 1)):\n for k in range(i, i + n):\n # total += sum(arr[i:i+n])\n total += arr[k]\n\n return total", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total = 0\n for length in range(1, len(arr)+1):\n if length%2 == 0:\n continue\n for i_start, start in enumerate(arr):\n if i_start + length -1 < len(arr):\n for i in range(i_start, i_start+length):\n total += arr[i]\n else:\n break\n return total", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n \n ans = 0\n for i in range(1, len(arr) + 1, 2):\n for j in range(len(arr) + 1 - i):\n for k in range(i):\n ans += arr[j + k]\n return ans\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n if len(arr) == 1:\n return arr[0]\n result = 0\n l = r = 0\n\n def getSum(array, start, end):\n local_sum = 0\n for i in range(start, end):\n local_sum += array[i]\n return local_sum\n\n while l < len(arr) - 1:\n if r > len(arr) - 1:\n l += 1\n r = l\n result += getSum(arr, l, r+1)\n r += 2\n\n return result\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n if len(arr) == 1:\n return (arr[0])\n result = 0\n l = r = 0\n def getSum(array, start, end):\n local_sum = 0\n for i in range(start,end):#\n local_sum += array[i]#1,\n return local_sum\n\n while l < len(arr) - 1:#0<4\n if r > len(arr) - 1:#1>4\n l += 1\n r = l\n result += getSum(arr, l, r+1)#arr,0,2\n r += 2\n return result\n\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n cur_sum, prefix_sum = 0, [0] * (len(arr) + 1)\n ret = 0\n for i in range(1, len(arr)+1):\n cur_sum += arr[i-1]\n prefix_sum[i] = cur_sum\n for j in range(1, i+1, 2):\n # print([i, j])\n ret += prefix_sum[i] - prefix_sum[i-j]\n return ret", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n n = len(arr)\n s = 0\n for i in range(n):\n for j in range(1, n+1, 2):\n if i + j - 1 < n:\n for x in range(j):\n s += arr[x+i]\n return s", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n ans=0\n N=len(arr)\n sumv=(N+1)*[0]\n for i in range(N):\n sumv[i+1]=sumv[i]+arr[i]\n ans=0\n for i in range(1,N+1):\n ans+=(sumv[i]*((i+1)//2-(N-i+1)//2))\n return ans", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total = 0\n subArrLen = 1\n while subArrLen <= len(arr):\n i = 0\n j = subArrLen\n subTotal = sum(arr[:j])\n total += subTotal\n while j < len(arr):\n subTotal -= arr[i]\n subTotal += arr[j]\n total += subTotal\n i += 1\n j += 1\n subArrLen += 2\n \n return total\n", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n n, sum_odd = len(arr), 0\n p_sum = [0] * ( n + 1)\n for i, a in enumerate(arr):\n p_sum[i + 1] = p_sum[i] + a\n for i, p in enumerate(p_sum):\n for j in range(i + 1, n + 1, 2):\n sum_odd += p_sum[j] - p_sum[i] \n return sum_odd", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n n = len(arr)\n prefix = [0]*(n+1)\n for i in range(n): prefix[i] = prefix[i-1]+arr[i]\n ans = 0\n for s in range(1,n+1,2): \n for i in range(n):\n if i+s > n: break\n ans += prefix[i+s-1] - prefix[i-1]\n return ans ", "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n total=0\n for i in range(len(arr)):\n temp=0\n for j in range (i,len(arr)): \n temp+=arr[j] \n if(j-i)%2 ==0:\n total+=temp\n return total\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 the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
Constraints:
rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1[0] <= rec1[2] and rec1[1] <= rec1[3]
rec2[0] <= rec2[2] and rec2[1] <= rec2[3] | ["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 r1x1 = rec1[0]\n r1y1 = rec1[1]\n r1x2 = rec1[2]\n r1y2 = rec1[3]\n \n r2x1 = rec2[0]\n r2y1 = rec2[1]\n r2x2 = rec2[2]\n r2y2 = rec2[3]\n \n if r2x1 >= r1x2 or r1x1 >= r2x2:\n return False\n if r2y1 >= r1y2 or r1y1 >= r2y2:\n return False\n return True", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n x1=rec1[0]\n y1=rec1[1]\n x2=rec1[2]\n y2=rec1[3]\n \n return x1<rec2[2] and rec2[0]<x2 and y1<rec2[3] and rec2[1]<y2", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n return not (rec1[2] <= rec2[0] or \n rec1[3] <= rec2[1] or \n rec1[0] >= rec2[2] or \n rec1[1] >= rec2[3])", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]", "class Solution:\n def isRectangleOverlap(self, r1: List[int], r2: List[int]) -> bool:\n return max(r1[0],r2[0])<min(r1[2],r2[2]) and max(r1[1],r2[1])<min(r1[3],r2[3]) \n", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n x1, y1, x2, y2 = rec1\n i1, j1, i2, j2 = rec2\n \n \n if i1 >= x2 or x1 >= i2 or y1 >= j2 or j1 >= y2:\n return False\n return True", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n sortedR1 = rec1\n if rec1[0] > rec1[2]:\n sortedR1[0] = rec1[2]\n sortedR1[2] = rec1[0]\n if rec1[1] > rec1[3]:\n sortedR1[1] = rec1[3]\n sortedR1[3] = rec1[1]\n sortedR2 = rec2\n if rec2[0] > rec2[2]:\n sortedR2[0] = rec2[2]\n sortedR2[2] = rec2[0]\n if rec2[1] > rec2[3]:\n sortedR2[1] = rec2[3]\n sortedR2[3] = rec2[1]\n \n# if (sortedR1[0] == sortedR1[2]) or (sortedR1[1] == sortedR1[3]):\n# return False\n# if (sortedR2[0] == sortedR2[2]) or (sortedR2[1] == sortedR2[3]):\n# return False\n \n# if (sortedR2[0] < sortedR1[2] <= sortedR2[2]):\n# if (sortedR2[1] < sortedR1[3] <= sortedR2[3]):\n# return True\n# elif (sortedR2[1] <= sortedR1[1] < sortedR2[3]):\n# return True\n# else:\n# return False\n \n# if (sortedR2[0] <= sortedR1[0] < sortedR2[2]):\n# if (sortedR2[1] < sortedR1[3] <= sortedR2[3]):\n# return True\n# elif (sortedR2[1] <= sortedR1[1] < sortedR2[3]):\n# return True\n# else:\n# return False\n# print('ok')\n \n if (sortedR2[0] < sortedR1[2]) and (sortedR2[2] > sortedR1[0]):\n if (sortedR2[1] < sortedR1[3]) and (sortedR2[3] > sortedR1[1]):\n return True \n return False ", "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n x1, y1, x2, y2 = rec1\n x3, y3, x4, y4 = rec2\n return not (x2 <= x3 or x4 <= x1 or y2 <= y3 or y4 <= y1)"] | {"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 map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length. | ["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 \"\"\"\n # encode strings\n count1, count2 = 0, 0\n dict1, dict2 = dict(), dict()\n for i in range(len(s1)):\n char1, char2 = s1[i], s2[i] # current characters\n if char1 in dict1 and char2 in dict2:\n pass\n elif char1 not in dict1 and char2 not in dict2:\n count1 += 1\n count2 += 1\n dict1[char1], dict2[char2] = count1, count2\n else:\n return False\n curr1 = dict1[char1] # current index of character in s1\n curr2 = dict2[char2] # current index of character in s2\n if curr1 != curr2:\n return False\n return True\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 \"\"\"\n # encode strings\n count1, count2 = 0, 0\n dict1, dict2 = dict(), dict()\n for i in range(len(s1)):\n if s1[i] in dict1:\n curr1 = dict1[s1[i]] # current index of character in s1\n else:\n count1 += 1\n dict1[s1[i]] = count1\n curr1 = dict1[s1[i]] # current index of character in s2\n if s2[i] in dict2:\n curr2 = dict2[s2[i]]\n else:\n count2 += 1\n dict2[s2[i]] = count2\n curr2 = dict2[s2[i]]\n if curr1 != curr2:\n return False\n return True\n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n from collections import defaultdict as dict\n if len(s) != len(t):\n return False\n if not s and not t:\n return True\n ssd = dict(lambda: 100)\n sst = dict(lambda: 100)\n for ss, tt in zip(s, t):\n if ssd[ss] == 100:\n ssd[ss] = ord(ss) - ord(tt)\n if sst[tt] == 100:\n sst[tt] = ord(tt) - ord(ss)\n if ssd[ss] == ord(ss) - ord(tt) and sst[tt] == ord(tt) - ord(ss):\n continue\n else:\n return False\n return True\n", "class Solution:\n def isIsomorphic(self, s1, s2):\n # encode strings\n enc1, enc2 = [], []\n count1, count2 = 0, 0\n dict1, dict2 = dict(), dict()\n for i in range(len(s1)):\n char1, char2 = s1[i], s2[i]\n if char1 in dict1:\n enc1.append(dict1[char1])\n else:\n count1 += 1\n dict1[char1] = count1\n enc1.append(dict1[char1])\n if char2 in dict2:\n enc2.append(dict2[char2])\n else:\n count2 += 1\n dict2[char2] = count2\n enc2.append(dict2[char2])\n return enc1 == enc2 # compare encodings\n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n map1 = {}\n map2 = {}\n for i in range(len(s)):\n if (s[i] in map1 and map1[s[i]] != t[i]) or (t[i] in map2 and map2[t[i]] != s[i]):\n return False\n else:\n map1[s[i]] = t[i]\n map2[t[i]] = s[i]\n return True", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) == 0:\n return True\n current_s = s[0]\n current_t = t[0]\n switch_s = 0\n switch_t = 0\n s_dict = dict()\n t_dict = dict()\n for i in range(1, len(s)):\n if s[i] != current_s:\n current_s = s[i]\n switch_s += 1\n if t[i] != current_t:\n current_t = t[i]\n switch_t += 1\n if s[i] in s_dict:\n if s_dict.get(s[i]) != t[i]:\n return False\n if t[i] in t_dict:\n if t_dict.get(t[i]) != s[i]:\n return False\n s_dict.update({current_s: current_t})\n t_dict.update({current_t: current_s})\n if switch_s != switch_t:\n return False\n return True", "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 \"\"\"\n # encode strings\n count1, count2 = 0, 0\n dict1, dict2 = dict(), dict()\n for i in range(len(s1)):\n char1, char2 = s1[i], s2[i] # current characters\n if char1 in dict1:\n curr1 = dict1[char1] # current index of character in s1\n else:\n count1 += 1\n dict1[char1] = count1\n curr1 = dict1[char1]\n if char2 in dict2:\n curr2 = dict2[char2] # current index of character in s2\n else:\n count2 += 1\n dict2[char2] = count2\n curr2 = dict2[char2]\n if curr1 != curr2:\n return False\n return True\n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n l = len(s)\n if l != len(t):\n return False\n d = {} #mapping\n for i, letter in enumerate(s):\n if letter not in d.keys():\n d[letter] = t[i]\n else:\n if d[letter] != t[i]:\n return False\n \n d2 = {} #mapping\n for i, letter in enumerate(t):\n if letter not in d2.keys():\n d2[letter] = s[i]\n else:\n if d2[letter] != s[i]:\n return False\n return True", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n mapping1 = dict()\n \n if len(s) != len(t):\n return False\n for i in range(len(s)):\n mapping1.setdefault(s[i],None)\n \n if mapping1[s[i]] == None:\n mapping1[s[i]] = t[i]\n elif mapping1[s[i]] != t[i]:\n return False\n if len(set(mapping1.values())) == len(list(mapping1.values())):\n return True\n return False\n \n \n \n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n from collections import defaultdict as dict\n if len(s) != len(t):\n return False\n if not s and not t:\n return True\n ssd = dict(lambda: 100)\n sst = dict(lambda: 100)\n for ss, tt in zip(s, t):\n if ssd[ss] == 100:\n ssd[ss] = ord(ss) - ord(tt)\n if sst[tt] == 100:\n sst[tt] = ord(tt) - ord(ss)\n for ss, tt in zip(s, t):\n if ssd[ss] == ord(ss) - ord(tt) and sst[tt] == ord(tt) - ord(ss):\n continue\n else:\n return False\n return True\n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t): return False\n dic1, dic2 = {}, {}\n for i in range(len(s)):\n if s[i] in dic1 and dic1[s[i]] != t[i]:\n return False\n if t[i] in dic2 and dic2[t[i]] != s[i]:\n return False\n dic1[s[i]] = t[i]\n dic2[t[i]] = s[i]\n return True", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n d1, d2 = [0 for _ in range(256)], [0 for _ in range(256)]\n for i in range(len(s)):\n if d1[ord(s[i])] != d2[ord(t[i])]:\n return False\n d1[ord(s[i])] = i+1\n d2[ord(t[i])] = i+1\n return True", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n \"\"\"\n # my second solution...modified based on first solution...\n l = len(s)\n \n sdic = {}\n snum = []\n i = 0\n j = 1\n while i < l:\n if s[i] not in sdic:\n sdic[s[i]] = j\n snum.append(j)\n j += 1\n else:\n snum.append(sdic[s[i]])\n i += 1\n \n tdic = {}\n tnum = []\n i = 0\n j = 1\n while i < l:\n if t[i] not in tdic:\n if j != snum[i]:\n return False\n tdic[t[i]] = j\n tnum.append(j)\n j += 1\n else:\n if tdic[t[i]] != snum[i]:\n return False\n tnum.append(tdic[t[i]])\n i += 1\n \n return True\n \n \n \"\"\"\n # my first solution...\n sdic = {}\n snum = []\n i = 0\n j = 1\n while i < len(s):\n if s[i] not in sdic:\n sdic[s[i]] = j\n snum.append(j)\n j += 1\n else:\n snum.append(sdic[s[i]])\n i += 1\n \n tdic = {}\n tnum = []\n i = 0\n j = 1\n while i < len(t):\n if t[i] not in tdic:\n tdic[t[i]] = j\n tnum.append(j)\n j += 1\n else:\n tnum.append(tdic[t[i]])\n i += 1\n \n if snum == tnum:\n return True\n else:\n return False\n", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) == 0:\n return True\n current_s = s[0]\n current_t = t[0]\n switch_s = 0\n switch_t = 0\n s_dict = dict()\n for i in range(1, len(s)):\n if s[i] != current_s:\n current_s = s[i]\n switch_s += 1\n if t[i] != current_t:\n current_t = t[i]\n switch_t += 1\n if s[i] in s_dict:\n if s_dict.get(s[i]) != t[i]:\n return False\n s_dict.update({current_s: current_t})\n if switch_s != switch_t:\n return False\n return True", "class Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n d = dict()\n for (a,b) in zip(s,t):\n # new mapping\n if a not in d:\n # duplicates in t\n if b in d.values():\n return False\n else:\n d[a] = b\n # old mapping\n else:\n # no duplicate in t\n if d[a] != b:\n return False\n return True"] | {"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 strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only. | ["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 if j in d:\n if i.count(j)>d[j]:\n flag=False\n break\n else:\n flag = False\n break\n if flag:\n l+=len(i)\n return l", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n d={}\n for i in chars:\n if i in d:\n d[i]+=1\n else:\n d[i] =1\n \n c=0\n \n for i in words:\n flag = True\n for j in i:\n if j in d:\n if(i.count(j) > d[j]):\n flag = False \n break\n else:\n flag = False\n break\n if(flag):\n c+=len(i)\n \n print(c)\n return c\n \n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charBins = {char:chars.count(char) for char in chars}\n total = 0\n\n for word in words:\n if (len(word) > len(chars)):\n continue\n \n if not set(word).issubset(chars):\n continue\n\n letterBins = {letter:word.count(letter) for letter in word}\n\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n\n if (goodWord):\n total += len(word)\n\n return total", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c = Counter(chars)\n ret = 0\n for word in words:\n if Counter(word) - c == Counter():\n ret += len(word)\n \n return ret\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return sum(len(word) for word in words if collections.Counter(word)&collections.Counter(chars)==collections.Counter(word))", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n chars_map = collections.Counter(chars)\n for word in words:\n if collections.Counter(word) == (collections.Counter(word) & chars_map):\n count += len(word)\n return count\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n num=0\n\n for word in words:\n letter = str()\n counter = Counter(chars) \n for i in word:\n if i in list(counter.keys()) and counter[i]>0:\n letter+=i\n counter[i]-=1\n \n\n\n if letter == word:\n print(letter)\n num += len(word)\n return num\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n sum = 0\n for i in words:\n check = True\n for s in i:\n if i.count(s) > chars.count(s):\n check = False\n if check == True:\n sum = sum + len(i)\n return sum", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n op = 0\n for ele in words:\n count=0\n for i in ele:\n if chars.count(i)>=ele.count(i):\n count+=1\n if count==len(ele):\n op+=len(ele)\n return (op)\n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charsums = 0\n chars = sorted(chars)\n \n for word in words:\n wordsize = len(word)\n word = sorted(word)\n charcounter = 0\n \n while len(word) > 0 and charcounter < len(chars):\n if word[0] == chars[charcounter]:\n word.remove(word[0])\n charcounter += 1\n else:\n charcounter += 1\n \n if len(word) == 0:\n charsums += wordsize\n \n return charsums", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count=0\n f=1\n for s in words:\n f=1\n for c in s:\n if s.count(c) > chars.count(c):\n f=0\n if f:\n print (s)\n count+=len(s)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n output = 0\n add = True\n for word in words:\n for c in word:\n if(word.count(c) > chars.count(c)):\n add = False\n if add:\n output += len(word)\n else:\n add = True\n return output\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n n = len(chars)\n for word in words:\n ok_word = True\n copy = chars\n visit = []\n for i in range(n):\n visit.append(0)\n for letter in word:\n ok_letter = False\n for i in range(n):\n if visit[i] == 0 and letter == copy[i]:\n ok_letter = True\n visit[i] = 1\n break\n if not ok_letter:\n ok_word = False\n break;\n if ok_word:\n count += len(word)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charBins = {char:chars.count(char) for char in chars}\n goodWords = []\n\n for word in words:\n if (len(word) > len(chars)):\n continue\n \n if not set(word).issubset(chars):\n continue\n\n letterBins = {letter:word.count(letter) for letter in word}\n\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n\n if (goodWord):\n goodWords.append(word)\n\n return sum(len(word) for word in goodWords)", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n from collections import Counter\n res = 0\n for j in words:\n tmp = Counter(j) & Counter(chars)\n if tmp==Counter(j):\n res+= len(j)\n return(res)\n \n \n \n \n\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n # go through each word:\n goodCount = 0\n for word in words:\n # go through each letter in each word:\n wordLen = len(word)\n letterCount = 0\n chars_list = list(chars)\n for letter in word:\n if letter in chars_list:\n letterCount += 1\n chars_list.remove(letter)\n if letterCount == wordLen:\n goodCount +=letterCount\n return goodCount\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n op = 0\n for ele in words:\n count=0\n for i in set(ele):\n if chars.count(i)>=ele.count(i):\n count+=1\n if count==len(set(ele)):\n op+=len(ele)\n return (op)\n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n suma =0\n for word in words:\n cur_word = list(word)\n cur_len = len(word)\n for c in chars:\n if c in cur_word:\n cur_word.remove(c)\n if len(cur_word)==0:\n suma+=cur_len\n return suma", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans=0\n from collections import Counter\n cd =Counter(chars)\n for w in words:\n wd=Counter(w)\n # print(wd & cd)\n if len(wd & cd) and len(list((wd & cd).elements())) == len(w):\n # print(list((wd & cd).elements())) \n # print(w)\n ans+=len(w)\n \n return ans\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n start = 0\n for i in words:\n count = 0\n t = list(chars)\n for j in i:\n if j in t:\n count+=1\n t.remove(j)\n if count == len(i):\n start+=count\n return start", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n total = 0\n for word in words:\n mod_chars = list(chars)\n found = 0\n for c in word:\n if c in mod_chars:\n p = mod_chars.index(c)\n del mod_chars[p]\n found += 1\n if found == len(word):\n total += found\n \n return total", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n # go through each word:\n goodCount = 0\n for word in words:\n # go through each letter in each word:\n wordLen = len(word)\n letterCount = 0\n chars_list = list(chars)\n for letter in word:\n if letter in chars_list:\n letterCount += 1\n chars_list.remove(letter)\n if letterCount == wordLen:\n goodCount +=letterCount\n return goodCount\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charBins = {char:chars.count(char) for char in chars}\n goodWords = []\n\n for word in words:\n if (len(word) > len(chars)) or not set(word).issubset(chars):\n continue\n \n letterBins = {letter:word.count(letter) for letter in word}\n\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n\n if (goodWord):\n goodWords.append(word)\n\n return sum(len(word) for word in goodWords)", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n total = 0\n for word in words:\n mod_chars = list(chars)\n found = 0\n for c in word:\n if c in mod_chars:\n del mod_chars[mod_chars.index(c)]\n found += 1\n if found == len(word):\n total += found\n \n return total", "class Solution:\n def countCharacters(self, words, chars: str) -> int:\n myd = {}\n for i in chars:\n if hash(i) in list(myd.keys()):\n myd[hash(i)] +=1\n else:\n myd[hash(i)]= 1\n wdata = []\n for i in range(0,len(words)):\n x = dict()\n for letter in words[i]:\n if hash(letter) in list(x.keys()):\n x[hash(letter)]+=1\n else:\n x[hash(letter)]=1\n wdata.append(x)\n count = 0\n for data in wdata:\n allin = True\n lcount = 0\n for letter in list(data.keys()):\n if letter in list(myd.keys()):\n if data[letter] > myd[letter]:\n allin = False\n else:\n lcount+=data[letter]\n else:\n allin = False\n if allin == True:\n count+= lcount\n return count\n \n \n# def countCharacters(self, words: List[str], chars: str) -> int:\n# myd = {}\n# count = 0\n# for i in chars:\n# if i in myd.keys():\n# myd[i] +=1\n# else:\n# myd[i]= 1\n \n# for word in words:\n# allin = True\n\n# for letter in word:\n# if letter in myd.keys():\n# if word.count(letter) > myd[letter]:\n# allin = False\n# else:\n# allin = False\n# if allin==True:\n# count+=len(word)\n# return count\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n ans = 0\n for word in words:\n \n charscopy = [i for i in chars]\n length = 0\n for char in word:\n if char in charscopy:\n length+=1\n charscopy.remove(char)\n \n if length == len(word):\n ans += length\n \n return ans\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n char_counter = Counter(chars)\n return sum([len(word) for word in words if len(char_counter - Counter(word)) > 1 and len(Counter(word) - char_counter) == 0])", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d = Counter(chars)\n ans = 0\n for word in words:\n cur = Counter(word)\n if cur == cur & d:\n ans += len(word)\n return ans", "import copy\nclass Solution:\n def countCharacters(self, w: List[str], c: str) -> int:\n \n d = {}\n \n for i in c:\n d[i] = d.get(i, 0)+1\n ans = 0\n for i in range(len(w)):\n x = copy.deepcopy(d)\n f = True\n for j in w[i]:\n if j in x and x[j]>0:\n x[j] -= 1\n else:\n f = False\n break\n if f:\n ans += len(w[i])\n return ans\n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n r=0\n a=list(chars)\n #print(a)\n for i in words:\n b=a.copy()\n s=False\n for j in i:\n if j not in b:\n s=True\n else:\n b.remove(j) \n \n if s!=True:\n r+=len(i)\n #print(s,r,b,a)\n return r", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n char_set = collections.Counter(chars)\n N = len(chars)\n result = 0\n for i in words:\n if len(i) <= N and self.check(char_set,i):\n result += len(i)\n return result\n def check(self, char_ctr, S):\n S_ctr = collections.Counter(S)\n for i in S_ctr:\n if i not in char_ctr or S_ctr[i] > char_ctr[i] :\n return False\n return True\n \n \n \n", "import copy\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charmap = dict()\n \n for c in chars:\n if c in charmap:\n charmap[c] += 1\n else:\n charmap[c] = 1\n size = 0\n for word in words:\n temp = copy.deepcopy(charmap)\n flag = True\n for c in word:\n if c in temp and temp[c] > 0:\n temp[c] -= 1\n else:\n flag = False\n break\n if flag:\n size += len(word)\n return size\n \n \n", "import copy\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n tracker = dict()\n result = 0\n \n for s in chars:\n tracker.setdefault(s, 0)\n tracker[s] += 1\n \n for word in words:\n _temp = copy.deepcopy(tracker)\n for ch in word:\n if ch not in _temp:\n break\n if _temp[ch] <= 0:\n break\n \n _temp[ch] -= 1\n else:\n result += len(word)\n \n return result\n \n \n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n \n ans = 0\n \n for word in words:\n charscopy = [i for i in chars]\n count = 0\n for char in word:\n if char in charscopy:\n count+=1\n charscopy.remove(char)\n if count==len(word):\n ans+=len(word)\n \n return ans", "import copy\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n s = dict()\n for c in chars:\n if c not in s:\n s[c] = 0\n \n s[c] += 1\n \n t = 0\n for word in words:\n s_copy = copy.deepcopy(s)\n valid = True\n for letter in word:\n if letter not in s_copy:\n valid = False\n break\n else:\n s_copy[letter] -= 1\n if s_copy[letter] == 0:\n del s_copy[letter]\n if valid:\n t += len(word)\n \n return t\n", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c1 = Counter(chars)\n ans = 0\n for i in words:\n c2 = Counter(i)\n print((c2 - c1))\n if not c2 - c1:\n ans += len(i)\n return ans\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n import copy\n total = 0\n y = {}\n for char in chars:\n if char in y:\n y[char] += 1\n else:\n y[char] = 1\n\n for word in words:\n x = copy.deepcopy(y)\n temp = 0\n for char in word:\n if char in x and x[char] > 0:\n x[char] -= 1\n temp += 1\n else:\n temp = 0\n break\n total += temp\n\n return (total)", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n out = 0\n \n for word in words:\n good = True\n \n for char in word:\n if word.count(char) > chars.count(char):\n good = False\n \n if good:\n out += len(word)\n \n return out", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charBins = {char:chars.count(char) for char in chars}\n goodWords = []\n\n for word in words:\n if (len(word) > len(chars)):\n continue\n \n if not set(word).issubset(chars):\n continue\n\n letterBins = {letter:word.count(letter) for letter in word}\n if min([letterBins[letter] <= charBins[letter] for letter in letterBins]):\n goodWords.append(word)\n\n return sum(len(word) for word in goodWords)", "import collections\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n for w in words:\n letters = list(set(w))\n isin = True\n for l in letters:\n if l not in chars or w.count(l) > chars.count(l):\n isin = False\n break\n if isin:\n count += len(w)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n a=0\n for word in words:\n res=True\n for i in word:\n if word.count(i)>chars.count(i):\n res=False\n break\n if res:\n a+=len(word)\n return a\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n res = 0\n dtar = Counter(chars)\n for i in range(len(words)):\n for j in words[i]:\n if j not in chars:\n break\n if words[i].count(j) > 1:\n if words[i].count(j) > dtar[j]:\n break\n else:\n res += len(words[i])\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d=Counter(chars)\n ans=0\n for w in words:\n temp=d.copy()\n b=True\n for i in w:\n try:\n if temp[i]!=0:\n temp[i]-=1\n else:\n b=False\n break\n \n except:\n b=False\n break\n if b:\n ans+=len(w)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n freq = {}\n for n in range(len(chars)):\n if chars[n] not in freq.keys():\n freq[chars[n]] = 1\n else:\n freq[chars[n]] += 1\n \n for word in words:\n word_fq = {}\n is_match = True\n for m in range(len(word)):\n if word[m] not in freq.keys():\n is_match = False\n break\n if word[m] not in word_fq.keys():\n word_fq[word[m]] = 1\n else:\n word_fq[word[m]] += 1\n \n if is_match:\n is_fit = True\n for key in word_fq.keys():\n if key not in freq.keys():\n is_fit = False\n break\n if word_fq[key] > freq[key]:\n is_fit = False\n break\n if is_fit:\n count += len(word)\n \n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c=collections.Counter(chars)\n res=0\n \n def valid(word):\n s=collections.Counter(word)\n for ch in s:\n if ch not in c or s[ch]>c[ch]:\n return False\n return True\n \n for word in words:\n if valid(word):\n res+=len(word)\n return res\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans = 0\n \n mp = Counter(chars)\n for word in words:\n ok = True\n mp_word = Counter(word)\n for ch, f in mp_word.items():\n if ch not in mp or mp_word[ch] > mp[ch]:\n ok = False\n break\n \n if ok:\n ans += len(word)\n \n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n from collections import Counter\n ans = 0\n chars_set = set(chars)\n count0 = Counter(chars)\n for word in words:\n count = Counter(word)\n if all((s in chars_set and count[s] <= count0[s]) for s in word):\n ans += len(word)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d_chars = Counter(chars)\n ans = 0\n for w in words:\n d_w = Counter(w)\n for k, v in d_w.items():\n if d_chars[k] < v:\n break\n else:\n ans += len(w)\n \n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n from collections import Counter\n ans = 0\n chars_set = set(chars)\n count0 = Counter(chars)\n for word in words:\n count = Counter(word)\n if all((s in chars_set and count[s] <= count0[s]) for s in word):\n ans += len(word)\n print(word)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n sum, ct = 0, collections.Counter\n chars_counter = ct(chars)\n for word in words:\n word_counter = ct(word)\n if all(word_counter[c] <= chars_counter[c] for c in word_counter):\n sum += len(word)\n return sum\n", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c_dict = dict(Counter(chars))\n \n count = 0\n \n for word in words:\n word_d = dict(Counter(word))\n match = True\n for k,v in list(word_d.items()):\n if(k not in c_dict or v>c_dict[k]):\n match = False\n break\n if(match):\n count+=len(word)\n return count\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n res = 0\n dtar = Counter(chars)\n for i in range(len(words)):\n for j in words[i]:\n if j not in dtar:\n break\n if words[i].count(j) > 1:\n if words[i].count(j) > dtar[j]:\n break\n else:\n res += len(words[i])\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n char_sum = 0\n \n def isValid(word, chars):\n for letter in word:\n if chars[letter] > 0:\n chars[letter] -= 1\n else:\n return False\n return True\n \n for word in words:\n counter = Counter(chars)\n if isValid(word, counter):\n char_sum += len(word)\n \n return char_sum\n \n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n tot = 0\n for w in words:\n d = {}\n for c in chars:\n if c in d: d[c] += 1\n else: d[c] = 1\n temp = 0\n for l in w:\n if l in d and d[l] > 0:\n d[l] -= 1 \n temp += 1\n else:\n temp = 0\n break\n \n tot += temp\n \n return tot", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n# ans = 0\n# for word in words:\n \n# charscopy = [i for i in chars]\n# length = 0\n# for char in word:\n# if char in charscopy:\n# length+=1\n# charscopy.remove(char)\n \n# if length == len(word):\n# ans += length\n \n# return ans\n ans = 0\n for word in words:\n \n charscopy = [i for i in chars]\n length = 0\n for char in word:\n if char not in charscopy:\n break\n charscopy.remove(char)\n else:\n ans += len(word)\n \n return ans\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans=0\n for w in words:\n tc=chars\n flag=True\n for l in w:\n if l in tc:\n tc = tc.replace(l,'',1)\n else:\n flag=False\n if flag:\n ans+=len(w)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d={}\n c=0\n for i in chars:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n for i in words:\n dd={}\n for j in i:\n if j in dd:\n dd[j]+=1\n else:\n dd[j]=1\n c1=0\n for x in dd.keys():\n if x in d:\n if d[x]>=dd[x]:\n c1+=dd[x]\n else:\n c1=0\n break\n else:\n c1=0\n break\n c+=c1\n return c", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n '''\n # first solution\n register = {}\n for char in chars: register[char] = register.get(char, 0) + 1\n result = 0\n for word in words:\n temp = {}\n for char in word: temp[char] = temp.get(char, 0) + 1\n for char, num in temp.items():\n if temp[char] > register.get(char, 0):\n break\n else:\n result+=len(word)\n return result\n '''\n # second solution\n tot = 0\n for w in words:\n d = {}\n for c in chars:\n if c in d: d[c] += 1\n else: d[c] = 1\n \n temp = 0\n for l in w:\n if l in d and d[l] > 0:\n d[l] -= 1 \n temp += 1\n else:\n temp = 0\n break\n \n tot += temp\n \n return tot \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n \n ans = 0\n \n for word in words:\n tempDict = charsDict.copy()\n isGood = True\n for char in word:\n if char not in tempDict:\n isGood = False\n continue\n else:\n if tempDict[char] == 0:\n isGood = False\n continue\n \n else:\n tempDict[char] -= 1\n \n if isGood:\n ans += len(word)\n \n \n return ans\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n cCounter = collections.Counter(chars)\n sum = 0\n for word in words:\n wCounter = collections.Counter(word)\n match = True\n for k,v in wCounter.items():\n if cCounter[k] < v:\n match = False\n if match:\n sum += len(word)\n return sum", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c1 = [0] * 256\n for c in chars:\n c1[ord(c)] += 1\n \n res = 0\n for word in words:\n if len(chars) < len(word):\n continue\n c2 = [0] * 256\n for c in word:\n c2[ord(c)] += 1\n \n goodStr = True\n for i in range(256):\n if c1[i] < c2[i]:\n goodStr = False\n break\n \n if goodStr:\n res += len(word)\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n def get_freq(input):\n freq = {}\n for c in input:\n if c not in freq:\n freq[c] = 0\n freq[c] += 1\n return freq\n \n def can_contain(freq_source, freq_word):\n for key, item in freq_word.items():\n if key not in freq_source or freq_source[key] < item:\n return False\n \n return True\n \n total_length = 0\n freq_source = get_freq(chars)\n for word in words:\n freq_word = get_freq(word)\n if can_contain(freq_source, freq_word):\n total_length += len(word)\n \n return total_length", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n \n ans = 0\n \n for word in words:\n wordDict = {}\n for char in word:\n if char not in wordDict:\n wordDict[char] = 0\n wordDict[char] += 1\n \n \n isGood = True\n for key, val in list(wordDict.items()):\n\n if key not in charsDict:\n isGood = False\n break\n elif val > charsDict[key]:\n isGood = False\n break \n \n if isGood:\n ans += len(word)\n \n \n return ans\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n res = 0\n d = dict()\n for char in chars:\n d[char] = d.get(char,0) + 1\n for word in words:\n c = dict()\n for char in word:\n c[char] = c.get(char,0) + 1\n bad = False\n while c and not bad:\n char = c.popitem()\n if char[0] in d and d[char[0]] >= char[1]:\n continue\n else:\n bad = True\n if not bad:\n res += len(word)\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n out=0\n chars=list(chars)\n for i in words:\n f=0\n temp=chars[:]\n for j in i:\n if j in temp:\n temp.remove(j)\n else:\n f=1\n break\n if f==0:\n out+=len(i)\n return out", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n # first solution\n register = {}\n for char in chars: register[char] = register.get(char, 0) + 1\n result = 0\n for word in words:\n temp = {}\n for char in word: temp[char] = temp.get(char, 0) + 1\n for char, num in list(temp.items()):\n if temp[char] > register.get(char, 0):\n break\n else:\n result+=len(word)\n return result\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charChars = Counter(chars)\n counter = 0\n for word in words:\n countC = Counter(word)\n count = 0\n for letter in countC.items():\n if letter[0] in charChars and charChars[letter[0]] >= letter[1]:\n count += 1\n \n if count == len(countC):\n counter += len(word)\n return counter", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n dic_char = {}\n for i in chars:\n if i not in dic_char:\n dic_char[i] = 1\n else:\n dic_char[i] += 1\n \n cnt = 0\n \n for i in words:\n dic_word = {}\n for j in i:\n if j not in dic_word:\n dic_word[j] = 1\n else:\n dic_word[j] += 1\n print(dic_word)\n for k, v in dic_word.items():\n if k not in dic_char or dic_char[k] < v:\n break\n else:\n cnt += len(i) \n \n return cnt", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n \n ans = 0\n \n for word in words:\n wordDict = {}\n for char in word:\n if char not in wordDict:\n wordDict[char] = 0\n wordDict[char] += 1\n \n \n isGood = True\n for key, val in list(wordDict.items()):\n\n if key not in charsDict:\n isGood = False\n continue\n elif val > charsDict[key]:\n isGood = False\n continue \n \n if isGood:\n ans += len(word)\n \n \n return ans\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n def strToList(word):\n return [char for char in word]\n \n def canForm(word, bank):\n tmp = word\n while(tmp != []):\n x = tmp[0]\n tmp.remove(tmp[0])\n if(x in bank):\n bank.remove(x)\n else:\n return False\n return True\n \n totalLen = 0\n for word in words:\n bank = strToList(chars)\n wordAsList = strToList(word)\n if(canForm(wordAsList, bank)):\n totalLen += len(word)\n return totalLen", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n setChars = set(chars)\n counts = [0] * len(setChars)\n map = {}\n res = 0\n for i, val in enumerate(setChars):\n map[val] = i\n for i, val in enumerate(chars):\n counts[map.get(val)] += 1\n for word in words:\n tempCounts = counts[:]\n flag = 1\n for char in word:\n index = map.get(char, -1)\n if index == -1:\n flag = 0\n continue\n tempCounts[index] -= 1\n if tempCounts[index] < 0:\n flag = 0\n continue\n if flag:\n res += len(word)\n return res\n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d = {}\n for i in range(len(chars)):\n if(chars[i] not in d):\n d[chars[i]] = 1\n else:\n d[chars[i]]+=1\n c = 0\n for i in range(len(words)):\n di = {}\n for j in range(len(words[i])):\n if(words[i][j] not in di):\n di[words[i][j]] = 1\n else:\n di[words[i][j]] += 1\n l = list(di.keys())\n temp = 0\n for j in range(len(l)):\n if(l[j] not in d):\n temp = 1\n break\n else:\n if(di[l[j]] > d[l[j]]):\n temp = 1\n break\n else:\n temp = 0\n if(temp==0):\n c+=len(words[i])\n return c \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n freq = {}\n for n in range(len(chars)):\n if chars[n] not in freq.keys():\n freq[chars[n]] = 1\n else:\n freq[chars[n]] += 1\n for word in words:\n word_fq = {}\n for m in range(len(word)): \n if word[m] not in word_fq.keys():\n word_fq[word[m]] = 1\n else:\n word_fq[word[m]] += 1\n \n is_fit = True\n for key in word_fq.keys():\n if key not in freq.keys():\n is_fit = False\n break\n if word_fq[key] > freq[key]:\n is_fit = False\n break\n if is_fit:\n count += len(word)\n \n return count", "class Solution:\n def countCharacters(self, words, chars):\n sum = 0\n count = {}\n for c in chars:\n if c in count:\n count[c] += 1\n else:\n count[c] = 1\n for word in words:\n seen = {}\n validWord = True\n for c in word:\n if c in seen:\n seen[c] += 1\n else:\n seen[c] = 1\n if c not in count or seen[c] > count[c]:\n validWord = False\n if validWord:\n sum += len(word)\n return sum", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return bruteforce_with_counter(words, chars)\n\n# words=[\\\"cat\\\", \\\"bat\\\", \\\"mat\\\", \\\"battle\\\"], chars=[\\\"catbtle\\\"] \n# cat vs catbtle\n# mat vs catbtle\n\nfrom collections import Counter\ndef bruteforce_with_counter(words, chars):\n counter = Counter(chars)\n # BUG. SHIT.\n #return sum(len(w) for w in words if min((counter - Counter(w)).values()) >= 0)\n #return sum(len(w) for w in words if max((Counter(w)-counter).values()) <= 0)\n return sum(len(w) for w in words if not (Counter(w)-counter))", "from collections import Counter as di\n\n\nclass Solution:\n def countCharacters(self, a: List[str], c: str) -> int:\n d = di(c)\n ans = 0\n for i in a:\n d1 = di(i)\n if len(d1 - d) == 0:\n ans += sum(d1.values())\n return ans\n", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n letters = Counter(chars)\n out = 0\n for word in words:\n length = len(word)\n if not(Counter(word)-letters):\n out += length\n return out", "from collections import Counter\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n def issubset(wc, cc):\n for x in wc.keys():\n cc[x]=cc.get(x,0)-wc[x]\n for x in cc.keys():\n if cc[x]<0:\n return False\n return True\n res=0\n cc=Counter(chars)\n for word in words:\n wc=Counter(word)\n if issubset(wc, cc.copy()):\n res+=len(word)\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n char_count = collections.Counter(chars)\n total = 0\n for word in words:\n if not collections.Counter(word) - char_count:\n total += len(word)\n \n return total", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n d = Counter(chars)\n cnt = [Counter(w) for w in words]\n ans = 0\n for i, x in enumerate(cnt):\n found = True\n print(x)\n for k in x:\n if k not in d or x[k] > d[k]:\n found = False\n break\n if found:\n ans += len(words[i])\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n chars = Counter(chars)\n return sum(len(w) for w in words if not Counter(w) - chars)\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = Counter(chars)\n out = 0\n \n for word in words:\n curr = Counter(word)\n if not curr-count:\n out += len(word)\n return out\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n chars = Counter(chars)\n return sum(len(word) for word in words if not (Counter(word) - chars))\n", "from collections import Counter\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c_c = Counter(chars)\n good_w = []\n for w in words:\n w_c = Counter(w)\n sampled_w = ''.join([c for c in w if c_c[c] >= w_c[c]])\n if w == sampled_w:\n good_w.append(w)\n return sum(len(w) for w in good_w)", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n char_map = {c:chars.count(c) for c in set(chars)}\n count = 0\n for w in words:\n good = True\n for c in w:\n if c not in char_map.keys() or w.count(c) > char_map[c]:\n good = False\n if good:\n count += len(w)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n ### Method 1:\n letters = {}\n for char in chars:\n letters[char] = letters.get(char, 0) + 1\n \n count = 0\n for word in words:\n tmp = letters.copy()\n flag = 1\n for char in word:\n if char in tmp and tmp[char] >= 1:\n tmp[char] -= 1\n else:\n flag = 0\n break\n if flag:\n count += len(word)\n return count \n", "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 if j in d:\n if i.count(j)>d[j]:\n flag=False\n else:\n flag = False\n if flag:\n l+=len(i)\n return l", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans = 0\n \n for word in words:\n c = collections.Counter(chars)\n add = True\n \n for letter in word:\n if c[letter] > 0:\n c[letter] -= 1\n else:\n add = False\n \n if add == True:\n ans += len(word)\n \n return ans\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans = 0\n cmap = {ch:chars.count(ch) for ch in chars}\n for word in words:\n wmap = {ch:word.count(ch) for ch in word}\n count_me_in = True\n \n for k,v in wmap.items():\n try:\n v1 = cmap[k]\n if v1 < v:\n raise Exception('Frequency not enough!')\n except:\n count_me_in = False\n break\n \n if count_me_in:\n \n ans += len(word)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n char_count = collections.Counter(chars)\n \n good_str_len = 0\n \n for word in words:\n temp = char_count.copy()\n temp_str_len = 0\n for ch in word:\n if ch in temp and temp[ch] > 0:\n temp_str_len += 1\n temp[ch] -= 1\n if temp_str_len == len(word):\n good_str_len += len(word)\n \n \n return good_str_len\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n c1 = [0] * 256\n for c in chars:\n c1[ord(c)] += 1\n \n res = 0\n for word in words:\n c2 = [0] * 256\n for c in word:\n c2[ord(c)] += 1\n \n goodStr = True\n for i in range(256):\n if c1[i] < c2[i]:\n goodStr = False\n break\n \n if goodStr:\n res += len(word)\n return res", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n if(len(chars) == 0 or len(words) == 0):\n return 0\n \n # Go through the valid characters and store the counts in a hash table\n letterCounts = {}\n for c in chars:\n if(str(c) in letterCounts):\n letterCounts[str(c)]+=1\n else:\n letterCounts[str(c)] = 1\n \n totalLength = 0\n for word in words:\n currentLetterCounts = {}\n for letter in word:\n if(str(letter) in currentLetterCounts):\n currentLetterCounts[str(letter)]+=1\n else:\n currentLetterCounts[str(letter)] = 1\n \n valid = True\n for key, value in currentLetterCounts.items():\n if(key not in letterCounts):\n valid=False\n break\n \n if(letterCounts[key] < value):\n valid=False\n break\n if(valid):\n totalLength+=len(word)\n \n return totalLength", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans = 0\n chars_number = collections.Counter(chars)\n for w in words:\n word_number = collections.Counter(w)\n print(word_number)\n for i in word_number:\n print(word_number[i])\n if word_number[i] > chars_number[i]:\n \n break\n else:\n ans+=len(w)\n return ans", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n flag = [0 for i in range(len(words))]\n total = 0\n \n \n for word in words :\n \n dic = {}\n \n for char in word :\n if char in dic : \n dic[char] += 1 \n else :\n dic[char] = 1 \n \n count = 0 \n \n for i in range(len(chars)) :\n if chars[i] in dic and dic[chars[i]] > 0: \n dic[chars[i]] -= 1 \n count += 1\n \n good = True\n \n for char in dic :\n if dic[char] > 0 :\n good = False \n break\n \n if good : \n total += count\n \n return total\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n myd = {}\n count = 0\n for i in chars:\n if i in myd.keys():\n myd[i] +=1\n else:\n myd[i]= 1\n \n for word in words:\n allin = True\n\n for letter in word:\n if letter in myd.keys():\n if word.count(letter) > myd[letter]:\n allin = False\n else:\n allin = False\n if allin==True:\n count+=len(word)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n good_words_len_sum = 0\n counter = {}\n for char in chars:\n if not char in counter:\n counter[char] = 1\n else:\n counter[char] += 1\n for word in words:\n my_counter = counter.copy()\n for char in word:\n if my_counter.get(char, 0) > 0:\n my_counter[char] -= 1\n else:\n break\n else:\n good_words_len_sum += len(word)\n return good_words_len_sum", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n\n return sum([len(word) for word in words if(len(collections.Counter(word) - collections.Counter(chars)) == 0)])", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n length=0\n \n m=Counter(chars)\n \n for word in words:\n \n passed=True\n \n for char in word:\n \n if m[char]<word.count(char):\n \n passed=False\n \n if passed:\n \n length+=len(word)\n \n \n return length\n \n \n \n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n from collections import Counter as cnt\n return sum([not cnt(word)-cnt(chars) and len(word) for word in words])", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n count = 0\n dic = collections.Counter(chars)\n for word in words:\n passed = True\n for ch in word:\n if dic[ch] < word.count(ch):\n passed = False\n if passed:\n count += len(word)\n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return sum( len(w) for w in words if not Counter(w) - Counter(chars))\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n counter = 0\n for i in words:\n a = i\n for j in chars:\n if j in a:\n a = a[:a.index(j)] + a[a.index(j)+1:]\n if len(a) == 0:\n counter += len(i)\n return counter\n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return sum(not Counter(w) - Counter(chars) and len(w) for w in words)", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \n words = [collections.Counter(word) for word in words]\n \n c = collections.Counter(chars)\n \n print(words)\n print(c)\n \n return sum([sum(list(w.values())) for w in words if all([c[i] >= w[i] for i in w])])", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n freq = defaultdict(int)\n \n for l in chars:\n freq[l] += 1\n \n count = 0\n for word in words:\n testFreq = freq.copy()\n match = True\n for letter in word:\n if testFreq[letter] <= 0:\n match = False\n break\n testFreq[letter] -= 1\n if match:\n count += len(word)\n \n return count", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n tot = 0\n totchars = {}\n for char in chars:\n if char in totchars:\n totchars[char] += 1\n else:\n totchars[char] = 1\n for word in words:\n word = sorted(word)\n works = True\n i = 0\n while i < len(word):\n count = 0\n while word[i + count] == word[i]:\n count += 1\n if i + count == len(word):\n break\n if word[i] in totchars:\n if count > totchars[word[i]]:\n works = False\n else:\n works = False\n i += count\n if works:\n tot += len(word)\n \n return tot", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n sum=0\n p=0\n for th in words:\n for i in range(len(th)):\n if th[i] in chars:\n if th.count(th[i])<=chars.count(th[i]):\n p=p+1\n if p==len(th):\n sum=sum+p\n p=0\n return sum", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans = 0\n for i in range(len(words)):\n if Counter(words[i]) & Counter(chars) == Counter(words[i]):\n ans += len(words[i])\n \n return ans\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n from collections import Counter\n sum_=0\n for word in words:\n s=Counter(chars)\n flag=0\n for letter in word:\n if letter in list(s.keys()) and s[letter]!=0:\n s[letter]-=1\n else:\n flag=1\n if flag==0:\n sum_+=len(word)\n return sum_\n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n out = 0 \n \n for word in words:\n cnt = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n cnt += 1\n if cnt == len(word):\n out += len(word)\n return out \n \n \n \n \n \n \n \n", "from collections import Counter\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n letters = Counter(chars)\n \n c = 0\n \n for w in words:\n if Counter(chars) & Counter(w) == Counter(w):\n c += len(w)\n \n \n return c", "import collections\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n n = 0\n for word in words:\n count = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n count += 1\n if count == len(word):\n n += len(word)\n return n \n \n", "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n res = []\n for word in words:\n count = 0\n for char in word:\n if char in chars and word.count(char)<=chars.count(char):\n count+=1\n if count==len(word):\n res.append(count)\n \n return sum(res)\n \n \n", "from collections import Counter\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n r = Counter(chars)\n return sum([len(word) if Counter(word) - r == Counter() else 0 for word in words])"] | {"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 and the non selected students remain on their seats.
Example 1:
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.
Example 2:
Input: heights = [5,1,2,3,4]
Output: 5
Example 3:
Input: heights = [1,2,3,4,5]
Output: 0
Constraints:
1 <= heights.length <= 100
1 <= heights[i] <= 100 | ["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(heights)\n for num in heights:\n places[freq[num] - 1] = num\n freq[num] -= 1\n return sum(a != b for a , b in zip(places,heights))", "\nclass Solution:\n def heightChecker(self, heights: List[int]) -> int:\n count = 0 # Counter\n b = sorted(heights)\n for x in range(len(heights)):\n if heights[x] != b[x]:\n count += 1\n return count", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n \n heights_sort = sorted(heights)\n \n cnt=0\n i=0\n while i< len(heights):\n if heights[i] != heights_sort[i] :\n cnt+=1\n i+=1\n \n return cnt\n", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n count = 0\n for idx, num in enumerate(sorted(heights)):\n if heights[idx] != num:\n count += 1\n \n return count", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n # my method 2: counting sort and compare difference O(n+r): r number of max_value O(n); only works for small numbers sorting\n \n maxVal = max(heights)\n \n # create frequency table for each digit from 0 to maxVal\n freq = [0] * (maxVal + 1)\n # get freq for all index\n for num in heights:\n freq[num] += 1\n # acc index by num[i] += num[i-1]\n for i in range(1,len(freq)):\n freq[i] += freq[i-1]\n \n # loop heights, find its freq and index back in places\n places = [0] * len(heights)\n for num in heights:\n # num has freq[num] th in ranking, but -1 to be index\n places[freq[num]-1] = num\n freq[num] -= 1\n \n ans = 0\n for i in range(len(heights)):\n if heights[i] != places[i]:\n ans += 1\n return ans\n \n", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n sortedHeights = sorted(heights)\n return sum([1 if sortedHeights[i] != heights[i] else 0 for i in range(len(heights))])", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n # my method 1: sort and compare different elements O(NlogN) O(n)\n heightsSorted = sorted(heights)\n \n # compare and acc different index\n ans = 0\n for i in range(len(heights)):\n if heights[i]!=heightsSorted[i]:\n ans += 1\n \n return ans", "class Solution:\n def heightChecker(self, h: List[int]) -> int:\n return sum([x!=y for (x,y) in zip(h,sorted(h))])", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n return sum([1 if sorted(heights)[i] != heights[i] else 0 for i in range(len(heights))])", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n diff=[sorted(heights)[k]-heights[k] for k in range(len(heights))]\n move=0\n for x in diff:\n if x!=0:\n move=move+1\n return move", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n hs = heights[:]\n for e in range(len(hs) - 1, 0, -1):\n mx, ix = float('-inf'), -1\n for i, h in enumerate(hs[:e + 1]):\n if h >= mx:\n ix, mx = i, h\n hs[e], hs[ix] = hs[ix], hs[e]\n return sum(a != b for a, b in zip(hs, heights))", "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n sorted_arry = []\n for x in heights:\n sorted_arry.append(x)\n for i in range(len(sorted_arry)):\n curr_ele = sorted_arry[i]\n j = i + 1\n curr_index = i\n while(j< len(sorted_arry)):\n if curr_ele > sorted_arry[j]:\n curr_ele = sorted_arry[j]\n curr_index = j\n j = j + 1\n sorted_arry[curr_index] = sorted_arry[i]\n sorted_arry[i] = curr_ele\n change_count = 0\n for i in range(len(heights)):\n if heights[i] != sorted_arry[i]:\n change_count = change_count + 1 \n return change_count"] | {"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] => [3,4,3] => [4,4,4] | ["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: List[int]\n :rtype: int\n \"\"\"\n # Adding n-1 elements by 1, same as subtracting one element by 1\n m = min(nums)\n res = 0\n for i in nums:\n res += (i - m)\n return res\n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum(nums)-len(nums)*min(nums)\n", "class Solution:\n \n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n if not nums:\n return 0\n \n lowest = nums[0]\n for num in nums:\n lowest = min(num, lowest)\n \n res = 0\n for num in nums:\n res += num - lowest\n \n return res", "class Solution:\n def minMoves(self, nums):\n s = sum(nums)\n minimum = min(nums)\n n = len(nums)\n result = s - minimum * n\n return result\n \n \n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum(nums)-min(nums)*len(nums)\n \n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n=len(nums)\n mn=min(nums)\n \n return sum(nums)-n*mn", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n min_num = min(nums)\n result = 0\n for num in nums:\n result += num-min_num\n return result", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = 0\n smallest = min(nums)\n \n for num in nums:\n count += abs(num - smallest)\n \n return(count)\n \n \n \n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n m = min(nums)\n return sum(i-m for i in nums)\n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums_min = nums[0]\n res = 0\n for i in range(len(nums)):\n if nums[i] >= nums_min:\n res += nums[i] - nums_min\n else:\n res += i * (nums_min - nums[i])\n nums_min = nums[i]\n \n return res", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \n let\u2019s define sum as the sum of all the numbers, before any moves; \n minNum as the min number int the list; \n n is the length of the list;\n \n After, say m moves, we get all the numbers as x , and we will get the following equation\n \n sum + m * (n - 1) = x * n\n and actually,\n \n x = minNum + m\n and finally, we will get\n \n sum - minNum * n = m\n So, it is clear and easy now. \n \"\"\"\n tt = 0\n mx = nums[0]\n n = 0\n for x in nums:\n tt += x\n n += 1\n if x < mx:\n mx = x\n return tt - mx * n\n \n \n", "class Solution:\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum(nums) - min(nums) * len(nums)\n"] | {"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 the game. Write a function to determine whether you can win the game given the number of stones in the heap.
Example:
Input: 4
Output: false
Explanation: If there are 4 stones in the heap, then you will never win the game;
No matter 1, 2, or 3 stones you remove, the last stone will always be
removed by your friend. | ["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 return False\n return True", "class Solution:\n def canWinNim(self, n):\n return n % 4 != 0\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n", "class Solution:\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n return n%4!=0\n", "class Solution:\n def canWinNim(self, n):\n if n%4==0:\n return False\n else:\n return True\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n", "class Solution:\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n % 4 == 0:\n return False\n else: \n return True\n", "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 return False\n else:\n return True", "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 return n % 4 != 0\n", "class Solution:\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n if n%4==0:\n return False\n else:\n return True"] | {"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 <= A[i] < 10000
A.length is even | ["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 range(1, len(A)):\n if A[i] == A[i - 1] or (i - 2 >= 0 and A[i] == A[i - 2]):\n return A[i]\n return A[0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n from collections import Counter\n c = Counter(A)\n c = list(c.most_common(1))\n return c[0][0]\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n N = len(A)\n counter = {}\n for num in A:\n if num in counter:\n counter[num] += 1\n else:\n counter[num] = 1\n \n if counter[num] == N//2:\n return num", "from collections import Counter as di\n\nclass Solution:\n def repeatedNTimes(self, a: List[int]) -> int:\n d = di(a)\n maxi = (len(a) // 2)\n return d.most_common(1)[0][0]\n for i in d:\n if d[i] == maxi:\n return i\n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n rep=len(A)//2\n d={}\n for i in A:\n if i in d:\n d[i]+=1\n if i not in d:\n d[i]=1\n if d[i]==rep:\n return i\n \n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n nums = {}\n for i in A:\n if i not in list(nums.keys()):\n nums[i] = 1\n else:\n nums[i] += 1\n \n print(nums)\n \n for i in nums:\n if nums[i] == len(A) / 2:\n return i\n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n N = len(A)\n \n freq = {}\n maxv = (None, -math.inf)\n for v in A:\n # Initialize the map entry if v is not in the map\n if v not in freq: freq[v] = 0\n # Increment the frequency of v\n freq[v] += 1\n # Check if v is the maxmimum frequency element\n if freq[v] > maxv[1]:\n maxv = (v, freq[v])\n # Check if we're done\n if freq[v] == N:\n return v\n \n return maxv[0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n N = len(A) // 2\n return ((sum(A) - sum(set(A))) // (N - 1))", "from collections import Counter\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n ans = 0\n c = Counter(A)\n count = 0\n # print(c)\n for i in c:\n print(('{} = {}'.format(i,c[i])))\n if c[i]>count:\n count = c[i]\n ans = i\n return ans\n \n \n \n \n \n # dic = {}\n# ans = 0\n# for x in range(0,len(A),1):\n# if A[x] in dic:\n# dic[A[x]] += 1\n \n# if dic[A[x]] >ans:\n# ans = A[x]\n# else:\n# dic[A[x]]=1\n \n \n# return ans\n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d={}\n for i in A:\n if i in d:\n return i\n else:\n d[i]=1", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n for i in range(len(A)):\n for j in A[:i]:\n if j == A[i]:\n return j", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dic = collections.Counter(A)\n for num in dic:\n if dic[num] > 1:\n return num", "from collections import Counter as C\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n s = C(A).most_common()\n return s[0][0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dic = {}\n for element in A:\n if(not (element in dic)):\n dic[element] = 1\n else:\n return element", "class Solution:\n def repeatedNTimes(self, qq: List[int]) -> int:\n stack = []\n for i in qq:\n if i not in stack:\n stack.append(i)\n else:\n return i", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n return (sum(A) - sum(set(A))) // (len(A)// 2 -1)", "from collections import Counter\n\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n cnt = Counter(A).most_common(1)\n return cnt[0][0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n count = collections.Counter(A)\n for i in count:\n if count[i] > 1:\n return i\n", "from collections import Counter\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n ct = Counter(A)\n return ct.most_common(1)[0][0]\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n size = len(A)\n n = size/2\n appear = {}\n for i in range(size):\n if A[i] not in list(appear.keys()):\n appear[A[i]] = 1\n else:\n appear[A[i]] += 1\n # print(appear)\n for i in list(appear.items()):\n if i[1] == n:\n return i[0]\n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n tracker = set()\n for num in A:\n if not num in tracker:\n tracker.add(num)\n else:\n return num", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n counter = collections.Counter(A)\n mostc = counter.most_common(1)\n \n for key,value in mostc:\n return key", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n if A==[]:\n return 0\n d={}\n for i in A:\n if i not in d.keys():\n d[i]=1\n else:\n return i\n return 0", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n maos = {x:0 for x in set(A)}\n for x in A:\n maos[x]+=1\n for x in maos:\n if maos[x] == len(A)//2:\n return x", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n #N = len(A)/2\n #for num in A:\n # if A.count(num) == N:\n # return num\n check = set()\n for num in A:\n if num in check:\n return num\n check.add(num)", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n sA = sorted(A)\n temp = None\n for i in sA:\n if i == temp:\n return i\n temp = i", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n count = collections.Counter(A)\n \n for i in count:\n if count[i] > 1:\n return i", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n temp = None\n for i in A:\n if i == temp:\n return i\n temp = i\n \n if A[0] == A[-2] or A[0] == A[-1]:\n return A[0]\n elif A[-1] == A[-3]:\n return A[-1]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n record = set()\n for a in A:\n if a in record:\n return a\n else:\n record.add(a)", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d={}\n for i in A:\n if i in d:\n return i\n else:\n d[i]=1\n return None", "class Solution:\n def repeatedNTimes(self, A):\n for i in range(len(A)):\n if A[i - 1] == A[i] or A[i - 2] == A[i]:\n return A[i]\n return A[0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n ans = Counter(A)\n return sorted(list(ans.keys()), key=lambda x: ans.get(x), reverse=True)[0]\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d = {}\n \n for value in A:\n if value in d:\n return value\n d[value] = 1", "class Solution:\n def repeatedNTimes(self, A) -> int:\n B = list(A)\n B.sort()\n for i in range(0, len(B)):\n if B[i] == B[i+1]:\n return B[i] \n else:\n pass\n\np = Solution() \ntestList = [5,1,5,2,5,3,5,4]\nprint(p.repeatedNTimes(testList))", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n for i, a in enumerate(A):\n if a in A[:i]:\n return a", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n myDict = collections.Counter(A)\n \n for _ in myDict:\n if myDict[_]>1:\n return _", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n n = len(A)\n if n == 0:\n return []\n if n == 2:\n return A[0]\n A.sort()\n for i in range(n):\n if A[i] == A[i+1]:\n return A[i]\n \n \n", "from collections import Counter\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n stack = []\n \n for n in A:\n if n not in stack:\n stack.append(n)\n else:\n return n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n B = A.copy()\n for x in A:\n B.remove(x)\n if x in B:\n return x", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n rep = {}\n for item in A:\n if item not in rep:\n rep[item] = 1\n else:\n return item\n return None", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n N = len(A)/2\n for num in A:\n if A.count(num) == N:\n return num\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n \n for i in range(0,len(A)):\n new = [A[i]]\n for j in range(i+1, len(A)):\n if (A[i] == A[j]) :\n new.append(A[i])\n if len(new) == len(A)/2: \n print(new)\n return A[i]\n \n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n a = set()\n for i in A:\n if i in a:\n return i\n else:\n a.add(i)", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n \n myDict = {}\n \n for i in A:\n \n myDict[i] = myDict.get(i, 0) + 1\n if myDict[i] == len(A)/2:\n return i\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dic={}\n for i in A:\n if i not in dic:\n dic[i]=0\n else:\n return i", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n count_dict = collections.Counter(A)\n for key, value in list(count_dict.items()):\n if value > 1:\n return key\n \n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n # check the first elem first\n result = A[0]\n count = 0\n if A.count(result) == len(A)//2:\n return result\n for i in A[1:]:\n if count == 0:\n result = i\n print('a')\n count = 1\n elif result == i:\n print('b')\n count += 1\n else:\n print('c')\n count -= 1\n \n return result\n", "from collections import Counter\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n n = len(A) // 2 \n d = Counter(A)\n \n for idx, val in d.items():\n if val == n:\n return idx\n return -1", "import collections\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dic=Counter(A)\n for i in dic:\n if(dic[i]>1):\n return i\n # dic={}\n # if(len(A)>0):\n # for i in A:\n # if i in dic:\n # return i\n # else:\n # dic[i]=1\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n occurences = set()\n for val in A:\n if val in occurences:\n return val\n occurences.add(val)\n", "class Solution(object):\n def repeatedNTimes(self, A):\n for k in range(1, 4):\n for i in range(len(A) - k):\n if A[i] == A[i+k]:\n return A[i]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n length = len(A)\n n = length // 2\n mydict = {}\n for item in A:\n mydict[item] = mydict.get(item, 0) + 1\n if mydict[item] == n:\n return item", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n count_dict = collections.Counter(A)\n for key, value in list(count_dict.items()):\n if value == len(A) / 2:\n return key\n \n", "from collections import Counter\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n counter = Counter(A)\n return counter.most_common(1)[0][0]", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n from collections import Counter\n cc = Counter(A)\n for key in list(cc.keys()):\n if cc[key] == len(A)//2:\n return key\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n j = set()\n for num in A:\n if num in j:\n return num\n else:\n j.add(num)\n return False\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n a = sum(A)\n b = sum(set(A))\n n = len(A)//2\n if a==0:\n return 0\n c = (a-b)//(n-1)\n return c", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n c = collections.Counter(A)\n for k in c:\n if c[k] == len(A)//2:\n break\n return k", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n N = len(A)//2\n \n A_map = defaultdict(int)\n for a in A:\n A_map[a] +=1\n if A_map[a] == N:\n return a\n", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n twoN = len(A)\n N = twoN//2\n unique = N+1\n hashMap = {}\n for num in A:\n if num not in hashMap:\n hashMap[num] =1\n else:\n hashMap[num] +=1\n for key,value in hashMap.items():\n if value == N:\n return key", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n count = collections.Counter(A)\n repeat = len(A)//2\n for key in count:\n if count[key] == repeat:\n return key\n return -1", "class Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n dic = self.convert_to_dic(A)\n for i in dic:\n if dic[i] > 1:\n return i\n \n \n def convert_to_dic(self, A):\n dic = {}\n for i in A:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n return dic"] | {"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 [email protected], 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 an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "[email protected]" and "[email protected]" forward to the same email address. (Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example [email protected] will be forwarded to [email protected]. (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?
Example 1:
Input: ["[email protected]","[email protected]","[email protected]"]
Output: 2
Explanation: "[email protected]" and "[email protected]" actually receive mails
Note:
1 <= emails[i].length <= 100
1 <= emails.length <= 100
Each emails[i] contains exactly one '@' character.
All local and domain names are non-empty.
Local names do not start with a '+' character. | ["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 = '';\n for x in localname:\n if x=='+':\n break;\n local += x;\n local = local.replace('.','');\n s.append(local+domainname);\n break;\n return len(set(s));", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n result = set()\n for email in emails:\n state = 0\n real = []\n for c in email:\n if state == 0:\n if c == '.':\n continue\n elif c == '+':\n state = 1\n elif c == '@':\n real.append('@')\n state = 2\n else:\n real.append(c)\n elif state == 1:\n if c == '@':\n real.append('@')\n state = 2\n elif state == 2:\n real.append(c)\n result.add(''.join(real))\n return len(result)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n emailSet = set()\n for email in emails:\n newemail = []\n afterplus = False\n afterat = False\n for ch in email:\n if afterat:\n newemail.append(ch)\n else:\n if ch == '.':\n pass\n elif ch == '+':\n afterplus=True\n elif ch == '@':\n newemail.append(ch)\n afterat=True\n else:\n if not afterplus:\n newemail.append(ch)\n emailSet.add(''.join(newemail))\n return len(emailSet)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n dic = {}\n for email in emails:\n new_email=''\n flag = 0\n for i in range(len(email)):\n if email[i] == '.':\n continue\n if email[i] == '+':\n flag = 1\n elif email[i] == '@':\n new_email += email[i:]\n break\n else:\n if flag == 0:\n new_email += email[i]\n dic[new_email] = 1\n return len(dic)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n dic = set([])\n for email in emails:\n new_email=''\n flag = 0\n for i in range(len(email)):\n if email[i] == '.':\n continue\n if email[i] == '+':\n flag = 1\n elif email[i] == '@':\n new_email += email[i:]\n break\n else:\n if flag == 0:\n new_email += email[i]\n dic.add(new_email)\n return len(dic)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n emailDict = {}\n total = 0\n for email in emails:\n domain = email.split('@')[1]\n localPart = email.split('@')[0]\n localPart = localPart.split('+')[0]\n localPart = localPart.replace('.', '')\n \n if domain not in emailDict:\n emailDict[domain] = set({ localPart })\n total += 1\n elif localPart not in emailDict[domain]:\n emailDict[domain].add(localPart)\n total += 1\n \n return total", "class Solution(object):\n def numUniqueEmails(self, emails):\n seen = set()\n for email in emails:\n local, domain = email.split('@')\n if '+' in local:\n local = local[:local.index('+')]\n seen.add(local.replace('.','') + '@' + domain)\n return len(seen)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n \n out = set()\n \n for email in emails:\n \n ar = email.split('@');\n \n out.add(ar[0].split('+')[0].replace('.', '') + '@' + ar[1])\n \n return len(out)\n", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n tmp = set()\n for email in emails:\n local_name, domain_name = email.split('@')\n before_first_plus = local_name.split('+')[0]\n without_dot_list = before_first_plus.split('.')\n final_local_name = ''.join(without_dot_list)\n tmp.add(final_local_name + '@' + domain_name)\n return len(tmp)", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n \n final = set()\n for email in emails:\n first, second = email.split('@')\n if '+' in first: \n first = first.split('+')\n f = [i for i in first[0] if i != '.']\n else:\n f = [i for i in first if i != '.']\n final.add(''.join(f) + '@' + second)\n \n return len(final)\n \n", "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n l=[]\n for i in emails:\n end=i[i.index('@'):]\n s=''\n string=''\n for j in i:\n if j=='.':\n continue\n if j=='+':\n break \n if j=='@':\n break\n else:\n s=s+j\n l.append(s+end) \n \n return (len(set(l))) "] | {"fn_name": "numUniqueEmails", "inputs": [[["\"[email protected]\"", "\"[email protected]\"", "\"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, 9, 10, 11, ... is a 0, which is part of the number 10. | ["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(i, count, div, mod)\n target = (i//9-1) + div\n if mod == 0:\n print(target, int(str(target)[-1]))\n return int(str(target)[-1])\n else:\n return int(str(target+1)[mod-1])", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n digs = 1\n while n > 9*(10**(digs-1))*digs:\n n -= 9*(10**(digs-1))*digs\n digs += 1\n return int(str(int(10**(digs-1)+(n-1)/digs))[n%digs-1])", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n digitCount = 1\n totalNumbersWithDigitCount = 9*(10**(digitCount-1))*digitCount\n while n > totalNumbersWithDigitCount:\n n -= totalNumbersWithDigitCount\n digitCount += 1\n totalNumbersWithDigitCount = 9*(10**(digitCount-1))*digitCount\n \n baseNumber = 10**(digitCount-1) - 1\n targetNumber = baseNumber + math.ceil(n/digitCount)\n targetDigitIndex = (n%digitCount) - 1\n \n return int(str(targetNumber)[targetDigitIndex])", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n start=0;\n digit=0;\n while True:\n temp=9*10**digit;\n if temp*(digit+1)<n:\n n-=temp*(digit+1);\n start+=10**digit*9\n digit+=1;\n else:break\n step=int(n/(digit+1))\n start+=step;\n n-=(digit+1)*step;\n if n==0:return start%10;\n start+=1;\n return (int(start/10**(digit+1-n)))%10", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n n -= 1\n for digits in range(1, 11):\n first = 10**(digits - 1)\n if n < 9 * first * digits:\n return int(str(first + n/digits)[n%digits])\n n -= 9 * first * digits", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # 1-9: 9, 10-99: 90, 100-999: 900, 1000-9999: 9000\n i, count = 1, 9\n total = 9\n while total < n:\n i += 1\n count *= 10\n total += i*count\n \n n -= total - i*count + 1\n return int(str(n//i+10**(i-1))[n%i])", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n n -= 1\n for digits in range(1, 11):\n first = 10**(digits - 1)\n if n < 9 * first * digits:\n return int(str(first + n/digits)[n%digits])\n n -= 9 * first * digits", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n # my fourth solution.........\n if n <= 0:\n return\n \n i = 0\n nbase = 0\n thres = 1*9\n if n <= thres:\n return n\n \n while 1:\n i += 1\n nbase += 9*10**(i-1)\n thres += (i+1)*9*10**i\n if n <= thres:\n return int(str((n+i-(thres-(i+1)*9*10**i))//(i+1) + nbase)[(n+i-(thres-(i+1)*9*10**i))%(i+1)])\n \n \n \n \n \"\"\"\n # my third solution....beat 93%....\n if n <= 0:\n return\n \n nbase = 0\n thres = 1*9\n if n <= thres:\n return n\n \n nbase += 9*10**0\n thres += 2*9*10**1\n if n <= thres:\n return int(str((n+1-(thres-2*9*10**1))//2 + nbase)[(n+1-(thres-2*9*10**1))%2])\n \n nbase += 9*10**1\n thres += 3*9*10**2\n if n <= thres:\n return int(str((n+2-(thres-3*9*10**2))//3 + nbase)[(n+2-(thres-3*9*10**2))%3])\n \n nbase += 9*10**2\n thres += 4*9*10**3\n if n <= thres:\n return int(str((n+3-(thres-4*9*10**3))//4 + nbase)[(n+3-(thres-4*9*10**3))%4])\n \n nbase += 9*10**3\n thres += 5*9*10**4\n if n <= thres:\n return int(str((n+4-(thres-5*9*10**4))//5 + nbase)[(n+4-(thres-5*9*10**4))%5])\n \n nbase += 9*10**4\n thres += 6*9*10**5\n if n <= thres:\n return int(str((n+5-(thres-6*9*10**5))//6 + nbase)[(n+5-(thres-6*9*10**5))%6])\n \n nbase += 9*10**5\n thres += 7*9*10**6\n if n <= thres:\n return int(str((n+6-(thres-7*9*10**6))//7 + nbase)[(n+6-(thres-7*9*10**6))%7])\n \n nbase += 9*10**6\n thres += 8*9*10**7\n if n <= thres:\n return int(str((n+7-(thres-8*9*10**7))//8 + nbase)[(n+7-(thres-8*9*10**7))%8])\n \n nbase += 9*10**7\n thres += 9*9*10**8\n if n <= thres:\n return int(str((n+8-(thres-9*9*10**8))//9 + nbase)[(n+8-(thres-9*9*10**8))%9])\n \"\"\"\n \n \n \n \n \"\"\"\n # my second solution........beat 96%....\n if n <= 0:\n return\n \n if n <= 1*9:\n return n\n \n if n <= 1*9+2*90:\n return int(str((n+1 - 1*9)//2 + 9)[(n+1 - 1*9)%2])\n \n if n <= 1*9+2*90+3*900:\n return int(str((n+2 - 1*9-2*90)//3 + 99)[(n+2 - 1*9-2*90)%3])\n \n if n <= 1*9+2*90+3*900+4*9000:\n return int(str((n+3 - 1*9-2*90-3*900)//4 + 999)[(n+3 - 1*9-2*90-3*900)%4])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000:\n return int(str((n+4 - 1*9-2*90-3*900-4*9000)//5 + 9999)[(n+4 - 1*9-2*90-3*900-4*9000)%5])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000:\n return int(str((n+5 - 1*9-2*90-3*900-4*9000-5*90000)//6 + 99999)[(n+5 - 1*9-2*90-3*900-4*9000-5*90000)%6])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000:\n return int(str((n+6 - 1*9-2*90-3*900-4*9000-5*90000-6*900000)//7 + 999999)[(n+6 - 1*9-2*90-3*900-4*9000-5*90000-6*900000)%7])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000+8*90000000:\n return int(str((n+7 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000)//8 + 9999999)[(n+7 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000)%8])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000+8*90000000+9*900000000:\n return int(str((n+8 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000-8*90000000)//9 + 99999999)[(n+8 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000-8*90000000)%9])\n \"\"\"\n \n \n \n \n \n \n \"\"\"\n # my first solution...........beat 93%.....\n if n <= 0:\n return\n \n if n <= 1*9:\n return n\n \n if n <= 1*9+2*90:\n return int(str((n+1 - 1*9)//2 + 9)[n%2])\n \n if n <= 1*9+2*90+3*900:\n return int(str((n+2 - 1*9-2*90)//3 + 99)[n%3-1])\n \n if n <= 1*9+2*90+3*900+4*9000:\n return int(str((n+3 - 1*9-2*90-3*900)//4 + 999)[n%4-2])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000:\n return int(str((n+4 - 1*9-2*90-3*900-4*9000)//5 + 9999)[n%5])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000:\n return int(str((n+5 - 1*9-2*90-3*900-4*9000-5*90000)//6 + 99999)[n%6-4])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000:\n return int(str((n+6 - 1*9-2*90-3*900-4*9000-5*90000-6*900000)//7 + 999999)[n%7])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000+8*90000000:\n return int(str((n+7 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000)//8 + 9999999)[n%8-2])\n \n if n <= 1*9+2*90+3*900+4*9000+5*90000+6*900000+7*9000000+8*90000000+9*900000000:\n return int(str((n+8 - 1*9-2*90-3*900-4*9000-5*90000-6*900000-7*9000000-8*90000000)//9 + 99999999)[n%9-1])\n \"\"\"\n", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n multiple = math.floor(math.log10(n))\n subtract = sum([math.pow(10,i) for i in range(0, multiple)])\n boundary = multiple*math.pow(10,multiple)-subtract\n diff = n-boundary\n \n if(diff>0):\n x = (math.pow(10, multiple) - 1) + math.ceil(diff/(multiple+1))\n p = (diff-1)%(multiple+1)\n elif(diff<=0):\n x = math.pow(10,multiple)+ math.ceil(diff / (multiple))-1\n p = (diff-1)%(multiple)\n \n r = [ch for ch in str(x)][int(p)]\n \n \n return int(r)", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n n -= 1\n for digits in range(1, 11):\n first = 10**(digits - 1)\n if n < 9 * first * digits:\n return int(str(first + n//digits)[n%digits])\n n -= 9 * first * digits", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n g = 1\n while True:\n g_len = (10 ** g - 10 ** (g - 1)) * g\n if n <= g_len:\n break\n \n n -= g_len\n g += 1\n \n idx = (n - 1) // g\n pos = (n - 1) % g\n \n num = 10 ** (g - 1) + idx\n return int(str(num)[pos])\n", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n multiple = math.floor(math.log10(n))\n subtract = sum([math.pow(10,i) for i in range(0, multiple)])\n boundary = multiple*math.pow(10,multiple)-subtract\n diff = n-boundary\n \n if(diff>0):\n x = (math.pow(10, multiple) - 1) + math.ceil(diff/(multiple+1))\n p = (diff-1)%(multiple+1)\n elif(diff<=0):\n x = math.pow(10,multiple)+ math.ceil(diff / (multiple))-1\n p = (diff-1)%(multiple)\n \n r = [ch for ch in str(x)][int(p)]\n \n \n return int(r)", "class Solution:\n def findNthDigit(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n n_digit=1\n while n>(n_digit*9*(10**(n_digit-1))):\n n-=n_digit*9*(10**(n_digit-1))\n n_digit+=1\n n_pre=(n-1)//n_digit\n digit_position=(n-1)%n_digit+1\n num=10**(n_digit-1)+n_pre\n tmp=0\n num=(num%10**(n_digit-digit_position+1))//(10**(n_digit-digit_position))\n return num"] | {"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
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2
Example 2:
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
Example 3:
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
Constraints:
1 <= arr1.length, arr2.length <= 500
-10^3 <= arr1[i], arr2[j] <= 10^3
0 <= d <= 100 | ["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 count+=1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n dist_matrix = [[abs(x-y) for y in arr2] for x in arr1]\n \n return len([1 for dist_lst in dist_matrix if min(dist_lst)>d])\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n return sum([sum([abs(i-j)>d for i in arr2])==len(arr2) for j in arr1])", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n bound = [(n+d,n-d) for n in arr2]\n out = 0\n for n in arr1:\n if any([ Up >= n >= Low for Up, Low in bound]):\n out += 1\n return len(arr1) - out\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n bound = [(n+d,n-d) for n in arr2]\n out = 0\n for n in arr1:\n if all([ n > Up or n < Low for Up, Low in bound]):\n out += 1\n return out\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n return sum([sum([abs(a - b) > d for b in arr2]) == len(arr2) for a in arr1])", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n c = 0\n c1 = 0\n for a in arr1:\n for r in arr2:\n if abs(a - r) > d:\n c1 += 1\n if c1 == len(arr2):\n c += 1\n c1 = 0\n return c", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n cnt = 0\n fcnt = 0\n lnb = len(arr2)\n for a in arr1:\n cnt = 0\n for b in arr2:\n if abs(a-b) > d:\n cnt = cnt + 1\n if cnt == lnb:\n fcnt = fcnt + 1\n return fcnt", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n total = 0\n for n in arr1:\n if all(abs(n - _n) > d for _n in arr2):\n total += 1\n return total", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n n, m = len(arr1), len(arr2)\n ans = 0\n for i in range(n):\n flag = 0\n for j in range(m):\n if abs(arr1[i] - arr2[j]) <= d:\n flag = 1\n if not flag:\n ans+=1\n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n qual = []\n \n for k in set(arr1):\n if False not in [True if abs(k-k2)>d else False for k2 in set(arr2)]:\n qual.append(k)\n \n k=0\n \n for q in qual:\n k+=arr1.count(q)\n \n return k\n \n \n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n \n c = 0\n l2 = len(arr2)\n for i in arr1:\n tmp = 0\n for j in arr2:\n \n if abs(i - j) > d:\n tmp+=1\n \n\n \n if tmp == l2:\n c += 1\n \n \n return c\n \n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for i in range(len(arr1)):\n is_dist = True\n for j in range(len(arr2)):\n if abs(arr1[i]-arr2[j]) <= d:\n is_dist = False\n \n if is_dist == True:\n count += 1\n \n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for i in range(len(arr1)):\n flag = 0\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j])<=d:\n flag = 1\n if flag ==1:\n count+=1\n return(len(arr1) - count)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n m = len(arr1)\n n = len(arr2)\n \n distance = 0\n for i in range(m):\n is_valid = True\n for j in range(n):\n if abs(arr1[i]-arr2[j])<= d:\n is_valid = False\n if is_valid:\n distance += 1\n return distance", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n n = len(arr1)\n m = len(arr2)\n count = 0\n for i in range(n):\n bad = False\n for j in range(m):\n if abs(arr1[i] - arr2[j]) <= d:\n bad = True\n if not bad:\n count+=1\n \n return count\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n\n arr = []\n for i in range(len(arr1)):\n count = 0\n for j in range(len(arr2)):\n if(abs(arr1[i]-arr2[j])<=d):\n count = count+1\n if(count==0):\n arr.append(arr1[i])\n return len(arr)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n c = 0\n for i in range(len(arr1)):\n f = 0\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j])<=d:\n f = 1\n if f==1:\n c+=1\n return(len(arr1) - c)\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n op = 0\n for i in range(len(arr1)):\n ref = [abs(arr1[i] - a2) <= d for a2 in arr2]\n if sum(ref) == 0:\n op += 1\n return op\n # def findTheDistanceValue(self, A, B, d):\n # return sum(all(abs(a - b) > d for b in B) for a in A)\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n dists = []\n for x in arr1:\n dists.append([abs(x-y) > d for y in arr2])\n \n return sum([all(x) for x in dists])", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count =0\n for i in arr1 :\n new_list= list(map(lambda m : abs(m -i), arr2))\n if all(x>d for x in new_list):\n count += 1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count =0\n for i in arr1 :\n new_list= list([abs(m -i) for m in arr2])\n if all(x>d for x in new_list):\n count += 1\n return count\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in range(len(arr1)):\n for j in range (len(arr2)):\n a= abs((arr1[i])-(arr2[j]))\n if (a<=d):\n break\n else:\n count=count+1\n return (count) \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = len(arr1)\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n count -= 1\n break\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if abs(arr1[i]-arr2[j])<=d:\n break\n else:\n count=count+1\n \n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n c = 0\n for i in range(len(arr1)):\n temp = 0\n for j in range(len(arr2)):\n if(abs(arr1[i]-arr2[j])<=d):\n temp = 1\n break\n if(temp == 0):\n c+=1\n return c\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: \n el_num = 0\n \n for i in range(len(arr1)):\n el_num += 1\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n el_num -= 1\n break\n \n return el_num", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n forbid_set = set()\n for a2 in arr2:\n forbid_set |= set(range(a2-d, a2+d+1))\n \n return sum(1 for a1 in arr1 if a1 not in forbid_set)", "from collections import Counter\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr1, arr2 = Counter(arr1), set(arr2)\n \n # print(arr1)\n # print(arr2)\n \n res = 0\n for num in arr1:\n target = range(num - d, num + d + 1)\n if not arr2.intersection(target):\n res += arr1[num]\n \n return res", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n val = 0\n dist = 0\n for i in range(0,len(arr1)):\n for j in range(0,len(arr2)):\n\n if abs(arr1[i]-arr2[j]) > d:\n val += 1\n else:\n break\n if val == len(arr2):\n dist += 1\n val = 0\n return dist", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n count = 0\n \n for i in range(len(arr1)):\n for j in range(len(arr2)):\n temp = arr1[i] - arr2[j]\n if temp < 0 :\n temp = -temp\n \n if temp <= d :\n break\n \n if j == len(arr2) - 1:\n count += 1\n return count\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n distanceValue = 0\n \n for i in range(len(arr1)):\n val = arr1[i]\n shouldCount = True\n for j in range(len(arr2)):\n if abs(val - arr2[j]) <= d:\n shouldCount = False\n break\n if shouldCount == True:\n distanceValue+=1\n return distanceValue", "class Solution:\n def findTheDistanceValue(self, arr1, arr2, d):\n d = abs(d);\n res = 0\n for i in range(len(arr1)):\n count = 0\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n break\n else:\n count += 1\n if count == len(arr2):\n res += 1\n return res\n \nsol = Solution();\nx = sol.findTheDistanceValue([4,5,8],[10,9,1,8],2);\nprint(x);\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n c=len(arr1)\n for i in arr1:\n for j in arr2:\n if abs(i-j)<=d:\n c-=1\n break\n return c", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = 0\n for x in arr1:\n for y in arr2:\n if abs(x-y) <= d:\n break\n else:\n ans += 1\n continue\n return ans", "class Solution:\n def findTheDistanceValue(self, a1: List[int], a2: List[int], d: int) -> int:\n x = set(a1)\n x -= {a + i for a in a2 for i in range(-d, d+1)}\n return sum(n in x for n in a1)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n dist_matrix = [all(abs(x-y)>d for y in arr2) for x in arr1]\n \n return sum(dist_matrix)\n \n # return len([1 for dist_lst in dist_matrix if min(dist_lst)>d])\n", "class Solution:\n def findTheDistanceValue(self, arr1, arr2, d):\n arr1.sort()\n arr2.sort()\n i = 0\n j = 0\n dist = 0\n while i < len(arr1) and j < len(arr2):\n if arr1[i] >= arr2[j]:\n if arr1[i] - arr2[j] > d:\n j += 1\n else:\n i += 1\n else:\n if arr2[j] - arr1[i] > d:\n i += 1\n dist += 1\n else:\n i += 1\n dist += len(arr1) - i\n return dist", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = 0\n for i in arr1:\n for j in arr2:\n if abs(i-j) <= d:\n break\n else:\n ans += 1\n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n for j in arr2:\n if abs(i-j)<=d:\n break\n else:\n count+=1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n nums = set()\n for number in arr2:\n for n in range(number-d, number+d+1):\n nums.add(n)\n \n cnt = 0\n for number in arr1:\n if number not in nums:\n cnt += 1\n \n return cnt", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n '''count=0\n for x,y in zip(arr1[:],arr2[:]):\n print(x,y)\n if abs(x-y)<d:\n count=count+1\n return count'''\n cnt = 0\n \n for i in arr1:\n for j in arr2:\n if abs(i-j) <= d:\n break\n else:\n cnt += 1\n return cnt\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr = []\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <=d:\n arr.append(arr1[i])\n break\n print(arr)\n \n return len(arr1) - len(arr)\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n distance_value=[]\n for i in arr1:\n valid=True\n for j in arr2:\n if abs(i-j)<=d:\n valid=False\n break\n if valid:\n distance_value.append(i)\n return len(distance_value)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n flag=1\n if abs(arr1[i]-arr2[j])<=d:\n break\n else:\n flag=0\n if flag==0:\n count=count+1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n print([x for x in arr1 if all (abs(x-y) > d for y in arr2)])\n return len([x for x in arr1 if all (abs(x-y) > d for y in arr2)])", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n cnt = 0\n for i in range(len(arr1)):\n cnt += 1\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n cnt -= 1\n break\n return cnt", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr1 = sorted(arr1)\n arr2 = sorted(arr2)\n \n i1 = 0\n i2 = 0\n ans = 0\n while i1 < len(arr1):\n while i2 < len(arr2) and arr2[i2] < arr1[i1]:\n i2 += 1\n \n if i2 == 0:\n ans = ans + 1 if abs(arr2[i2] - arr1[i1]) > d else ans\n elif i2 == len(arr2):\n ans = ans + 1 if abs(arr2[i2 - 1] - arr1[i1]) > d else ans\n else:\n ans = ans + 1 if min(abs(arr2[i2 - 1] - arr1[i1]), abs(arr2[i2] - arr1[i1])) > d else ans\n \n i1 += 1\n \n return ans\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n # c=0\n # for a in arr1:\n # t = 1\n # for b in arr2:\n # if abs(a-b)<=d:\n # t*=0\n # else:\n # t*=1\n # if t==1:\n # c +=1\n # return c\n return sum(all(abs(a - b) > d for b in arr2) for a in arr1)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = len(arr1)\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n \n if(abs(arr1[i] - arr2[j])) <= d:\n ans -= 1\n break\n \n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n return sum(all(abs(a - b) > d for b in arr2) for a in arr1)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n cnt=0\n ans=0\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if abs(arr1[i]-arr2[j])>d:\n cnt+=1\n else:\n cnt=0\n break\n if j==len(arr2)-1 and cnt==len(arr2):\n ans+=1\n cnt=0\n \n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr1.sort()\n arr2.sort()\n ans = 0\n for i in arr1:\n is_valid = True\n for j in arr2:\n if abs(i-j)<=d:\n is_valid = False\n break\n if is_valid:\n ans += 1\n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n res = len(arr1)\n for i in arr1:\n for j in arr2:\n if abs(i - j) <= d:\n res -= 1\n break\n return res\n \n# res = 0\n# cnt = 0\n# l = len(arr2)\n# for i in arr1:\n# for j in arr2:\n# if abs(i - j) > d:\n# cnt += 1\n# if cnt == l:\n# res += 1\n# cnt = 0\n# return res\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n ans = 0\n for i in arr1:\n is_valid = True\n for j in arr2:\n if abs(i-j)<=d:\n is_valid = False\n break\n if is_valid:\n ans += 1\n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n count = 0\n arr2.sort()\n \n \n for i in arr1:\n for j in arr2:\n if abs(i-j) <= d:\n break\n else:\n count += 1\n \n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n Distance = 0\n for x in arr1:\n if all(abs(x-y) > d for y in arr2):\n Distance += 1\n return Distance", "def bs(a, t, d):\n l, r = 0, len(a)\n while l < r:\n mid = l + (r - l) // 2\n if abs(a[mid] - t) <= d:\n return 0\n elif a[mid] > t:\n r = mid\n else:\n l = mid + 1\n return 1\n\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n total = 0\n arr2.sort()\n for n in arr1:\n total += bs(arr2, n, d)\n return total", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n total = 0\n \n arr1.sort()\n arr2.sort()\n \n for i in arr1:\n for j in arr2:\n if abs(i-j) <= d:\n total -=1\n break\n total += 1\n \n return total", "from collections import Counter\n\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res = 0\n cnt = Counter(arr2)\n for n in arr1:\n td = d\n vals_to_find = []\n while td >= -d:\n vals_to_find.append(n - td)\n td -= 1\n add = True\n for j in vals_to_find:\n if cnt[j] > 0:\n add = False\n break\n if add:\n res += 1\n return res", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n l = len(arr2)\n arr2.sort()\n for i in arr1:\n temp_count = 0\n for j in arr2:\n if(abs(i-j) <= d):\n break\n else:\n temp_count += 1\n if(temp_count == l):\n count += 1\n temp_count = 0\n return count ", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = 0\n \n arr2.sort()\n \n for i in range(len(arr1)):\n \n flag = True\n \n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n flag = False\n break\n \n if flag:\n ans += 1\n \n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr1.sort()\n arr2.sort()\n m=len(arr1)\n n=len(arr2)\n cnt=0\n for i in range(m):\n flag=True\n for j in range(n):\n dis=abs(arr1[i]-arr2[j])\n if(dis<=d):\n flag=False\n break\n if(flag):\n cnt+=1\n \n return cnt\n\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n dpcache = {}\n distance = 0\n \n for el1 in arr1:\n # check cache for this number\n if dpcache.get(el1) is True:\n distance += 1\n continue\n elif dpcache.get(el1) is False:\n continue\n else:\n # otherwise go and calculate solution for cur number\n pass\n \n for el2_idx, el2 in enumerate(arr2): \n # if condition fails, save failure in cache\n if abs(el1 - el2) <= d:\n dpcache[el1] = False\n break\n \n # if condition wins, save it in cache too\n if el2_idx == len(arr2) - 1:\n dpcache[el1] = True\n distance += 1\n \n return distance", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n arr2.sort()\n count = len(arr1)\n \n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j])<= d:\n count-= 1\n break\n \n return count\n \n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr1.sort()\n arr2.sort() \n \n el_num = 0\n \n for i in range(len(arr1)):\n el_num += 1\n for j in range(len(arr2)):\n if abs(arr1[i] - arr2[j]) <= d:\n el_num -= 1\n break\n \n return el_num", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n res = 0\n for i in arr1:\n found = True\n for j in arr2:\n \n if j > i + d:\n break\n elif abs(i - j) <= d:\n found = False\n break\n res += found \n return res \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n def min_d(num, arr): \n # use binary search to find the first arr element >= than num \n left = 0\n right = len(arr2) - 1 \n while left <= right:\n mid = (left + right) // 2 \n if arr[mid] < num:\n left = mid + 1\n else:\n right = mid - 1\n \n if left == len(arr): # all elements less than num\n return num - arr[-1]\n elif left == 0: # all elements greater than num\n return arr[0] - num \n return min(arr[left] - num, num - arr[left-1])\n \n arr2.sort() \n distance = 0 \n for num in arr1:\n if min_d(num, arr2) > d:\n distance += 1\n \n return distance", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n tot = 0\n for i in arr1:\n found = False\n for j in arr2:\n diff = i - j\n if abs(diff) <= d:\n found = True\n break\n if diff <= -d:\n break\n if not found:\n tot += 1\n return tot", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n arr2.sort()\n ans = 0\n \n for base in arr1:\n count = 0\n idx = 0\n while idx < len(arr2) and base > arr2[idx]: idx += 1 # util arr2[idx] >= base\n if idx == 0:\n ans += abs(base - arr2[idx]) > d\n elif idx == len(arr2):\n ans += abs(base - arr2[idx - 1]) > d\n else:\n ans += ((abs(base - arr2[idx]) > d) and (abs(base - arr2[idx-1]) > d))\n \n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ok = 0\n arr2.sort() \n for test1 in arr1:\n ele = 0\n sign = 0\n for test2 in arr2: \n test = test2-test1\n if abs(test) <= d: \n ele = 1\n break\n if (test > d) or (d < 0):\n break\n if ele == 0: ok += 1\n return ok", "import numpy\n\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n s = 0\n n2 = len(arr2)\n for x in arr1:\n k = numpy.searchsorted(arr2, x)\n if k < n2 and arr2[k] - x <= d:\n s += 1\n else:\n if k >= 1 and x - arr2[k - 1] <= d:\n s += 1\n return len(arr1) - s\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for a in set(arr1):\n if all(abs(a - b) > d for b in set(arr2)):\n count += arr1.count(a)\n return count", "import numpy\n\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2 = sorted(arr2)\n s = len(arr1)\n n2 = len(arr2)\n for x in arr1:\n k = numpy.searchsorted(arr2, x)\n if k < n2 and arr2[k] - x <= d:\n s -= 1\n else:\n if k >= 1 and x - arr2[k - 1] <= d:\n s -= 1\n return s\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n add=1\n for j in range(d+1):\n if (i+j) in arr2 or (i-j) in arr2:\n add=0\n break\n count+=add\n return count", "import numpy as np\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res=0\n for num1 in arr1:\n if all(abs(np.subtract(num1,arr2))>d):\n res+=1\n return res", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = 0\n for num1 in arr1:\n flag = 1\n for num2 in arr2:\n if abs(num1 - num2) <= d:\n flag = 0\n if flag:\n ans+=1\n return ans \n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res = 0\n for a in arr1:\n temp = True\n for b in arr2:\n if(abs(a-b) <= d):\n temp = False\n if(temp):\n res += 1\n return res\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n distance = 0\n for i in arr1:\n is_there = False\n for j in arr2:\n if abs(i-j)>d:\n continue\n else:\n is_there = True\n if not is_there:\n distance+=1\n return distance\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n count=0\n for i in arr1:\n flag=False\n for j in arr2:\n if abs(i-j)<=d:\n flag=True\n if flag==False:\n count+=1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n r = 0\n for i in arr1:\n ir = 1\n for j in arr2:\n if abs(i - j) <= d:\n ir = 0\n continue\n r += ir\n return r\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n result = 0\n for i in arr1:\n a = 1\n for j in arr2:\n if abs(i-j)<=d:\n a = 0\n result += a\n return result\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n yes=0\n for j in arr2:\n if abs(i-j)<=d:\n yes=1\n # break\n if(yes==1):\n count+=1\n return len(arr1)-count\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n cnt=0\n for a in arr1:\n mark=0\n for b in arr2:\n if abs(a-b) <=d:\n mark=1\n cnt+=1 if mark==0 else 0\n return cnt\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n distance = [[val - d, val + d] for val in arr1]\n total = 0\n for ran in distance:\n for val in arr2:\n if(ran[0] <= val and val <= ran[1]):\n total += 1\n break\n return len(arr1) - total\n \n \n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n result = 0\n for num in arr1:\n greater = True\n for sub in arr2:\n if abs(num-sub) <= d:\n greater = False\n if greater:\n result += 1\n return result", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for num1 in arr1:\n flag = False\n for num2 in arr2:\n if abs(num1 - num2) <= d:\n flag = True\n if not flag:\n count += 1\n return count\n", "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 if flag==0:\n count+=1\n return count", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for i in arr1:\n curr = 0\n for j in arr2:\n if abs(i-j) <= d:\n curr += 1\n \n if curr == 0:\n count += 1\n \n return count\n", "class Solution:\n def findTheDistanceValue(self, arr1, arr2, d: int) -> int:\n counter = 0\n if 1 <= len(arr1) <= 500 and 1 <= len(arr2) <= 500:\n for i in range(len(arr1)):\n val = 1\n for j in range(len(arr2)):\n if pow(-10, 3) <= arr1[i] <= pow(10, 3) and pow(-10, 3) <= arr2[j] <= pow(10, 3):\n if 0 <= d <= 100:\n check_value = (abs(arr1[i] - arr2[j]))\n if check_value <= d:\n val = 0\n break\n if val == 1:\n counter += 1\n # print(counter)\n return counter", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n boss = 0 \n for val1 in arr1 : \n cnt = 0 \n for val2 in arr2 : \n if abs(val2 - val1) <= d : \n cnt += 1 \n if cnt == 0 : \n boss += 1 \n return boss\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans=0\n for i in arr1:\n for j in range(i-d,i+d+1):\n if(j in arr2):\n break\n \n else:\n ans+=1\n return ans", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n ans = 0\n for x in arr1:\n ans += all([abs(x-y) > d for y in arr2])\n return ans\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n ans = 0\n \n for a in arr1:\n isGood = True\n \n for b in arr2:\n if (abs(a-b)<=d):\n isGood = False\n break\n \n if (isGood): \n ans += 1\n \n return ans\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res = 0\n for a in arr1:\n add = True\n for b in arr2:\n if abs(a - b) <= d:\n add = False\n if add:\n res += 1\n return res", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n c = list(set([i for i in arr1 for j in arr2 if abs(i-j) <= d ]))\n i = len(arr1)\n for j in c:\n i -= arr1.count(j)\n return i\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n return sum([1 - any([abs(i-j) <= d for j in arr2]) for i in arr1])", "class Solution:\n def findTheDistanceValue(self, A: List[int], B: List[int], d: int) -> int:\n return sum(1 - any([abs(a - b) <= d for b in B]) for a in A)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n return sum([all([abs(i-j) > d for j in arr2]) for i in arr1])", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \n count=0\n for i in arr1:\n a = True\n for j in arr2:\n a=a & (abs(i-j)>d)\n if a==True:\n count+=1\n return count ", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n a = set()\n out=0\n for i in range(len(arr1)):\n for j in arr2:\n if abs(arr1[i]-j)<=d:\n out+=1\n if i not in a:\n a.add(i)\n\n return len(arr1)-len(a)", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n return len([g for g in [min(k) for k in [[abs(t - y) for t in arr2] for y in arr1]] if g>d])\n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count = 0\n for i in arr1:\n d_l = [abs(i-j) > d for j in arr2]\n if all(d_l):\n count += 1\n return count\n \n", "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n\n final_count = 0\n for arr_1_val in arr1:\n #store the matches\n correct_count = 0\n for arr_2_val in arr2:\n\n if abs(arr_1_val- arr_2_val) > d:\n correct_count += 1\n if correct_count == len(arr2):\n final_count += 1\n return final_count\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" to the end of the word.
For example, the word 'apple' becomes 'applema'.
If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.
Example 1:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Notes:
S contains only uppercase, lowercase and spaces. Exactly one space between each word.
1 <= S.length <= 150. | ["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 + aAppend\n if c == ' ':\n result += newWord + fullAppend + ' '\n aAppend += 'a'\n newWord = ''\n maAppend = ''\n continue\n if maAppend == '' and c in vowel:\n maAppend = 'ma'\n newWord += c\n continue\n if maAppend == '' and (not c in vowel):\n maAppend = c + 'ma'\n continue\n\n newWord += c\n if lastC != ' ':\n result += newWord + maAppend + aAppend\n\n return result", "class Solution:\n def toGoatLatin(self, S: str) -> str:\n \n vowels = set(['a','e','i','o','u'])\n s = ''\n for i,item in enumerate(S.strip().split()):\n if item[0].lower() in vowels:\n s+=item\n else:\n s+=item[1:]+item[0]\n \n s+='ma'+'a'*(i+1)+' '\n \n return s[:-1]", "class Solution:\n def toGoatLatin(self, S: str) -> str:\n words = S.split(' ')\n def trans(word):\n ret = ''\n if word[0] in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:\n ret = word + 'ma'\n else:\n ret = word[1:] + word[0] + 'ma'\n return ret\n ret = [trans(x) for x in words]\n for idx in range(len(ret)):\n ret[idx] += 'a' * (idx + 1)\n return ' '.join(ret)", "class Solution:\n def toGoatLatin(self, S: str) -> str:\n list_str = S.split(' ')\n s = ''\n for index, word in enumerate(list_str):\n if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:\n s += ''.join('{word}ma{a} ' .format(word=word, a='a'*(index+1)))\n else:\n s += ''.join('{word}{alp}ma{a} ' .format(word=word[1:], alp=word[0], a='a'*(index+1)))\n return s.strip()", "class Solution:\n def toGoatLatin(self, S: str) -> str:\n list_str = S.split(' ')\n s = ''\n for index, word in enumerate(list_str):\n if word[0].lower() in ('a', 'e', 'i', 'o', 'u'):\n s += ''.join('{word}ma{a} ' .format(word=word, a='a'*(index+1)))\n else:\n s += ''.join('{word}{alp}ma{a} ' .format(word=word[1:], alp=word[0], a='a'*(index+1)))\n return s.strip()"] | {"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
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false | ["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(num,0)+1\n for num in d:\n if d[num]>1:\n index1=-1\n index2=-1\n for i in range(len(nums)):\n if nums[i]==num and index1==-1:index1=i\n elif nums[i]==num and index2==-1:index2=i\n elif nums[i]==num and index1!=-1 and index2!=-1:\n index1=index2\n index2=i\n print(index2,index1)\n if index1!=-1 and index2!=-1 and abs(index2-index1)<=k:return True\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n \n dic = {}\n for i, v in enumerate(nums):\n if v in dic and i - dic[v] <= k:\n return True\n dic[v] = i\n return False\n", "class Solution(object):\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n #Initial approach using map O(n) time and space\n m = {} #Stores value -> index mapping\n \n for i, n in enumerate(nums):\n if n in m and abs(m[n] - i) <= k:\n return True\n #Insert new element or replace old one with index that is more right (decreases distance to next)\n m[n] = i\n \n return False\n \n '''\n Ex testcase: [1,2,3,4,5,6,7,1,9,1] k = 3\n '''", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if nums == None or len(nums) <= 1 or k == 0:\n return False\n maps = {}\n for i, item in enumerate(nums):\n if item in maps and abs(maps[item] - i) <= k:\n return True\n else:\n maps[item] = i\n \n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n hashmap = {}\n for i in range(len(nums)):\n if nums[i] in hashmap.keys():\n if abs(i-hashmap[nums[i]]) <= k:\n return True\n else:\n hashmap[nums[i]] = i\n else:\n hashmap[nums[i]] = i\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n hashmap = {}\n for i in range(len(nums)):\n if nums[i] in hashmap.keys():\n if abs(i-hashmap[nums[i]]) <= k:\n return True\n else:\n hashmap[nums[i]] = i\n else:\n hashmap[nums[i]] = i\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n d = {}\n for i, num in enumerate(nums):\n if num in d and i - d[num] <= k:\n return True\n d[num] = i\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n last_seen_idx = {}\n for i, num in enumerate(nums):\n if num in last_seen_idx and i - last_seen_idx[num] <= k:\n return True\n last_seen_idx[num] = i\n \n return False", "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()\n for i in range(len(nums)):\n if i-k-1 >= 0:\n s.remove(nums[i-k-1])\n \n if nums[i] in s:\n return True\n s.add(nums[i])\n return False\n", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if k == 0:\n return False\n d = {}\n for i in range(len(nums)):\n if nums[i] in d.keys() and abs(i - d[nums[i]]) <= k:\n return True\n else:\n d[nums[i]] = i\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n if not nums or k<0 or len(nums)==len(set(nums)):\n return False\n mapD={}\n for i,v in enumerate(nums):\n if v in mapD and i-mapD[v]<=k:\n return True\n mapD[v]=i\n return False\n \n", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if not nums or len(nums) < 2:\n return False\n \n from collections import defaultdict\n dup_idx = defaultdict(list)\n for i, num in enumerate(nums):\n dup_idx[num].append(i)\n \n for idxes in dup_idx.values():\n if len(idxes) == 1:\n continue\n idxes = sorted(idxes)\n for i in range(1, len(idxes)):\n if idxes[i] - idxes[i - 1] <= k:\n return True\n \n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if not nums:\n return False\n d = collections.defaultdict(list)\n for i, n in enumerate(nums):\n if n in d:\n for index in d[n]:\n if i - index <= k:\n return True\n d[n].append(i)\n return False", "class Solution:\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n d = {}\n for i in range(len(nums)):\n l = d.get(nums[i], [])\n if nums[i] in d:\n for j in l:\n if abs(i - j) <= k:\n return True\n l.append(i)\n d[nums[i]] = l\n \n return False"] | {"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 is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. | ["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] + ans[i-3]\n return ans[n]", "class Solution:\n \n \n \n \n \n def tribonacci(self, n: int) -> int:\n \n if n == 0:\n return 0\n if n == 1:\n return 1\n \n \n F = [0] * 38\n \n F[0] = 0\n F[1] = 1\n F[2] = 1\n \n for i in range(3,n+1):\n F[i] = F[i-1] + F[i-2] + F[i-3]\n \n return F[n]", "from collections import deque \nclass Solution:\n def tribonacci(self, n: int) -> int:\n if n>0 and n<3:\n return 1\n if n==0:\n return 0\n queue = deque([0,1,1])\n t = 2\n while t!=n:\n queue.append(sum(queue))\n queue.popleft()\n t+=1\n return queue[2]", "class Solution:\n def tribonacci(self, n: int) -> int:\n T = [0, 1, 1]\n for n in range(3, n + 1):\n T.append(T[n - 3] + T[n - 2] + T[n - 1])\n return T[n]", "class Solution:\n def tribonacci(self, n: int) -> int:\n trib = []\n trib.append(0)\n trib.append(1)\n trib.append(1)\n for i in range(3, n):\n trib.append(trib[i-1] + trib[i-2] + trib[i-3])\n \n if n > 2:\n return trib[n-1] + trib[n-2] + trib[n-3]\n else:\n return trib[n]\n", "class Solution:\n trib = [0,1,1]\n def tribonacci(self, n: int) -> int:\n try:\n return self.trib[n]\n except:\n currlen = len(self.trib)\n for i in range(currlen,n+1):\n self.trib.append(self.trib[i-1]+self.trib[i-2]+self.trib[i-3])\n return self.trib[n]\n", "class Solution:\n def tribonacci(self, n: int) -> int:\n if n<3:\n return 1 if n else 0\n \n nums = [0]*(n+1)\n nums[0]=0\n nums[1]=1\n nums[2]=1\n \n for i in range(3, n+1):\n nums[i]=nums[i-1]+nums[i-2]+nums[i-3]\n \n return nums[n]\n \n \n", "class Solution:\n DP: List[int] = [0, 1, 1]\n \n def tribonacci(self, n: int) -> int:\n if n >= 0:\n if n < len(self.DP):\n return self.DP[n]\n else:\n offset: int = len(self.DP)\n self.DP.extend([0] * (n - offset + 1))\n for i in range(offset, n + 1):\n self.DP[i] = self.DP[i - 3] + self.DP[i - 2] + self.DP[i - 1]\n return self.DP[n]\n else:\n raise ValueError\n", "class Solution:\n def tribonacci(self, n: int) -> int:\n t = [0,1,1]\n if n < 3:\n return t[n]\n \n for i in range(n-2):\n t.append(sum(t))\n t = t[1:]\n \n return t[2]", "class Solution:\n def tribonacci(self, n: int) -> int:\n if n == 0:\n return 0\n if n < 3:\n return 1\n t0, t1, t2 = 0, 1, 1\n for _ in range(3, n+1):\n ans = t0 + t1 + t2\n t0, t1, t2 = t1, t2, ans\n return ans"] | {"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.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note:
The n belongs to [1, 10,000]. | ["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 return False\n possibility_flag = True\n if (i-2 < 0 or i-2 >= 0 and nums[i-2] < nums[i]) or (i+1 >= len(nums) or i+1 < len(nums) and nums[i+1] > nums[i-1]):\n pass\n else:\n return False\n return True\n \n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n if len(nums) == 1:\n return True\n for i in range(0,len(nums)-1):\n if nums[i] > nums[i+1]:\n if nums[i+1] < nums[i-1] and i-1 >= 0:\n count += 1\n if count > 1:\n break\n if i+1 != (len(nums)-1):\n nums[i+1] = nums[i]\n else:\n nums[i] = nums[i+1]\n count += 1\n if count > 1:\n break\n if count == 1:\n nums[i] -= 1\n \n if count > 1:\n return False\n else:\n return True\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n if len(nums) == 1:\n return True\n for i in range(0,len(nums)-1):\n if nums[i] > nums[i+1]:\n if nums[i+1] < nums[i-1] and i-1 >= 0:\n count += 1\n if i+1 != (len(nums)-1):\n nums[i+1] = nums[i]\n else:\n nums[i] = nums[i+1]\n count += 1\n if count == 1:\n nums[i] -= 1\n \n if count > 1:\n return False\n else:\n return True\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n if len(nums) == 1:\n return True\n for i in range(0,len(nums)-1):\n if nums[i] > nums[i+1]:\n if nums[i+1] < nums[i-1] and i-1 >= 0:\n count += 1\n if count > 1:\n break\n if i+1 != (len(nums)-1):\n nums[i+1] = nums[i]\n else:\n nums[i] = nums[i+1]\n count += 1\n if count > 1:\n break\n if count == 1:\n nums[i] -= 1\n \n if count > 1:\n return False\n else:\n return True\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n idx=-1\n if len(nums)>=2:\n if nums[0]>nums[1]:\n r=0\n else:\n r=1\n for i in range(2,len(nums)):\n if nums[i]<nums[i-1]:\n # idx=i-2\n r=r-1\n if nums[i]<nums[i-2]:\n nums[i]=nums[i-1]\n # if idx>=0:\n # pre=nums[idx]\n # else:\n # pre=-2**32\n # if i<len(nums)-1 and nums[i+1]<pre:\n # r=r-1\n # print(i,r)\n if r<0:\n return False\n return True\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n if len(nums) == 1:\n return True\n for i in range(0,len(nums)-1):\n if nums[i] > nums[i+1]:\n if nums[i+1] < nums[i-1] and i-1 >= 0:\n count += 1\n if count > 1:\n break\n if i+1 != (len(nums)-1):\n nums[i+1] = nums[i]\n else:\n nums[i] = nums[i+1]\n count += 1\n if count > 1:\n break\n if count == 1:\n nums[i] -= 1\n \n if count > 1:\n return False\n else:\n return True\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count=0\n for i in range(len(nums)-1):\n if nums[i]>nums[i+1]:\n count+=1\n if count>1 or ((i-1>=0 and nums[i-1]>nums[i+1]) and (i+2<len(nums) and nums[i+2]<nums[i])):\n return False\n return True", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0;\n front = nums[0];\n for i in range(1,len(nums)):\n print(front);\n if front > nums[i]:\n if count > 0:\n return False;\n else:\n if i > 1 and nums[i - 2] > nums[i]:\n front = nums[i - 1];\n else:\n front = nums[i];\n count += 1;\n else:\n front = nums[i];\n return True;\n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n \n n = len(nums)\n \n decreasing = []\n \n for i in range(n-1):\n if nums[i] > nums[i+1]:\n decreasing.append(i)\n \n if not decreasing:\n return True\n \n if len(decreasing) > 1:\n return False\n \n def check(array):\n n = len(array)\n for i in range(n-1):\n if array[i] > array[i+1]:\n return False\n \n return True\n \n i = decreasing[0]\n \n temp = nums[i]\n nums[i] = nums[i+1]\n if check(nums):\n return True\n nums[i] = temp\n \n nums[i+1] = nums[i]\n if check(nums):\n return True\n \n return False \n \n", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n modified = False\n for i in range(1, len(nums)):\n if i and nums[i] < nums[i - 1]:\n if modified:\n return False\n modified = True\n if i > 1 and nums[i] <= nums[i - 2]:\n nums[i] = nums[i - 1]\n return True", "class Solution:\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n return sum(list(map(lambda t: t[0] - t[1] < 0, zip(nums[1:], nums[:-1])))) <= 1 and sum(list(map(lambda t: t[0] - t[1] < 0, zip(nums[2:], nums[:-2])))) <= 1"] | {"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 index of the first word (minimum index). If there is no such word return -1.
A prefix of a string S is any leading contiguous substring of S.
Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
Input: sentence = "i am tired", searchWord = "you"
Output: -1
Explanation: "you" is not a prefix of any word in the sentence.
Example 4:
Input: sentence = "i use triple pillow", searchWord = "pill"
Output: 4
Example 5:
Input: sentence = "hello from the other side", searchWord = "they"
Output: -1
Constraints:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters. | ["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 sentence = sentence.split(' ')\n a = []\n for i in range(len(sentence)):\n if len(sentence[i]) >= len(searchWord):\n if sentence[i][0:len(searchWord)] == searchWord:\n a.append(i)\n if a:\n return min(a)+1\n else:\n return -1", "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n word_list = sentence.split(' ')\n for i in range(len(word_list)):\n if word_list[i].startswith(searchWord):\n return i + 1\n return -1", "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n arr = sentence.split()\n #print(len(arr))\n for i in range(len(arr)):\n #print(arr[i][:len(searchWord)])\n if arr[i][:len(searchWord)] == searchWord:\n return i+1\n return -1", "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n arr = sentence.split()\n print(len(arr))\n for i in range(len(arr)):\n print(arr[i][:len(searchWord)])\n if arr[i][:len(searchWord)] == searchWord:\n return i+1\n return -1", "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n words = sentence.split(' ')\n match = [i for i,w in enumerate(words) if w.startswith(searchWord)]\n if not match:\n return -1\n return match[0]+1"] | {"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 the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. | ["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 return y", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n \n if x>=0:\n x=str(x)[::-1]\n x=int(x)+0\n else:\n x=str(-x)[::-1]\n x=0-int(x)\n if x<-2**31 or x>=2**31-1:\n x=0\n return x\n \"\"\"\n x = str(x)\n if x[0] == '-':\n x = x[1:]\n ans = int()\n \"\"\"", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x > 0:\n x = int(str(x)[::-1])\n elif x < 0:\n x = 0 - int(str(abs(x))[::-1])\n if -2 ** 31 < x < 2 ** 31:\n return x\n else:\n return 0", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n str_x = str(x)\n n = len(str_x)\n if str_x[0] != '-':\n y = int(str_x[::-1]) #[a:b:c] from a to exclusive b by c\n else:\n y = -int(str_x[:0:-1])\n \n return(y*(y.bit_length() < 32))\n", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x == 0:\n return 0\n \n s = -1 if x < 0 else 1\n v = int(str(abs(x))[::-1])\n \n if s == -1:\n t = -v & -0x80000000\n if t == -0x80000000:\n return -v\n else:\n return 0\n else:\n t = v & 0x7fffffff\n if t == v:\n return v\n else:\n return 0\n", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n flag = x < 0\n p = x\n if flag == True:\n p = -1 * x\n \n digit = []\n while p != 0:\n digit.append(p % 10)\n p = p // 10\n \n n = 0\n for i in digit:\n n = n * 10 + i\n \n if -2 ** 31 <= n <= 2 ** 31 - 1:\n return n if flag == False else -1 * n\n \n return 0", "class Solution:\n flag = 0\n def reverse(self, x):\n if x < 0:\n self.flag = 1\n self.x = str(-x)\n else:\n self.x = str(x)\n \n list1 = []\n \n for i in self.x:\n if i != 0:\n self.flag1 = 1\n if self.flag1 == 1:\n list1.insert(0,i)\n self.x = int(\"\".join(list1))\n \n if self.flag == 1 :\n self.x = -self.x\n if self.x <= 2147483647 and self.x >= -2147483648:\n return self.x\n else:\n return 0", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n sign = 1\n if x<0:\n x=-x\n sign = -1\n result = 0\n while x>0:\n end = x%10\n result = result*10 + end\n x = x//10\n result *= sign\n if result > 2**31-1 or result < -2**31:\n return 0\n else:\n return result", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x.bit_length()>32 :\n \n print(\"wrong\");\n else:\n number = [];\n digit_num = [];\n new_num = 0;\n \n error = abs(x);\n for i in range(len(str(abs(x)))):\n if not number:\n digit = abs(x)//10**(len(str(abs(x)))-1); \n number.append(str(digit));\n digit_num.append(digit);\n else:\n error = error - digit_num[i-1]*10**(len(str(abs(x)))-i);\n digit = error//10**(len(str(abs(x)))-1-i); \n number.append(str(digit));\n digit_num.append(digit);\n \n number.reverse();\n \n while(int(number[0])==0 and len(number)>1):\n del number[0];\n \n for i in range(len(number)):\n new_num = new_num + int(number[i])*10**(len(number)-i-1);\n if new_num.bit_length()>=32:\n return 0;\n \n if x<0:\n new_num = -new_num;\n return new_num;", "class Solution:\n def reverse(self, x):\n str_x = str(x)\n \n if x >= 0 and int(str_x[::-1]) <= (2**31-1):\n return int(str_x[::-1])\n elif x < 0 and -int(str_x[:0:-1]) >= (-2**31):\n return -int(str_x[:0:-1])\n else:\n return 0", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x is 0:\n return 0;\n ori_str = str(x)\n answer = 0\n if ori_str[0] is '-':\n answer = -1 * int(ori_str[:0:-1].lstrip('0'))\n else:\n answer = int(ori_str[::-1].lstrip('0'));\n \n if answer >= 2 ** 31 or answer < -(2 ** 31):\n return 0\n else:\n return answer", "class Solution(object):\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x>=0:\n sign=1\n else:\n sign=-1\n x=abs(x)\n reserve=0\n while x>0:\n reminder= x%10\n reserve= reserve*10+reminder\n x=x//10\n if reserve>(2**31-1):\n reserve=0\n return reserve*sign", "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x==0:\n return 0\n if x>0:\n sign=1\n else:\n sign=-1\n x=0-x\n \n bits=[]\n for i in range (10):\n bits.append(x%10)\n x=x//10\n print (bits)\n \n left_i=0\n right_i=9\n \n for i in range (10):\n if bits[i]==0:\n left_i=left_i+1\n else:\n break\n \n for i in range (9,-1,-1):\n if bits[i]==0:\n right_i=right_i-1\n else:\n break\n \n print (left_i,right_i)\n \n factor=1\n result=0\n for i in range (right_i,left_i-1,-1):\n result=result+factor*bits[i]\n factor=factor*10\n \n result=result*sign\n \n if result>2147483647 or result<-2147483648:\n return 0\n else:\n return result"] | {"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 reformatted string or return an empty string if it is impossible to reformat the string.
Example 1:
Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.
Example 3:
Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.
Example 4:
Input: s = "covid2019"
Output: "c2o0v1i9d"
Example 5:
Input: s = "ab123"
Output: "1a2b3"
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits. | ["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 = ''\n if len(a) == len(b):\n while a:\n r += a.pop()\n r += b.pop()\n elif len(a) > len(b):\n while b:\n r += a.pop()\n r += b.pop()\n r += a[0]\n else:\n while a:\n r += b.pop()\n r += a.pop()\n r += b[0]\n return r", "class Solution:\n def reformat(self, s: str) -> str:\n chars = []\n nums = []\n for i in s:\n try:\n nums.append(int(i))\n except ValueError:\n chars.append(i)\n if abs(len(nums)-len(chars)) > 1:\n return ''\n \n out = [0]*len(s)\n if len(nums) >= len(chars):\n out[::2], out[1::2] = nums, chars\n else:\n out[::2], out[1::2] = chars,nums\n \n \n return ''.join([str(i) for i in out])", "class Solution:\n def reformat(self, s: str) -> str:\n cA = []\n cD = []\n for i in s:\n if(i.isalpha()):\n cA.append(i)\n else:\n cD.append(i)\n res = ''\n if(len(s) % 2 == 0):\n if(len(cA) == len(cD)):\n for i in range(len(cA)):\n res += (cA[i] + cD[i])\n else:\n if(abs(len(cA)-len(cD)) == 1):\n if(len(cA) > len(cD)):\n res = cA[0]\n for i in range(len(cD)):\n res += (cD[i] + cA[i+1])\n else:\n res = cD[0]\n for i in range(len(cA)):\n res += (cA[i] + cD[i+1]) \n return res"] | {"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 count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211" | ["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 let = l\n count = 1\n temp += str(count) + let\n s = temp\n return s\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n s = '1'\n for _ in range(n - 1):\n temp, pre, count = '', s[0], 0\n for i in s:\n if i == pre:\n count += 1\n else:\n temp += str(count) + pre\n count = 1;\n pre = i;\n temp += str(count) + pre\n s = temp\n return s\n \n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n L=\"1\"\n if(n==1):\n return L\n while(n>1):\n M=\"\"\n i=0\n while(i<len(L)):\n k=1\n x=L[i];\n while(i<len(L)-1 and L[i+1]==x):\n i=i+1\n k=k+1\n M=M+str(k)+x\n i=i+1\n n=n-1\n L=M\n return L", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n s = '1'\n for _ in range(n - 1):\n s = re.sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), s)\n return s", "class Solution:\n def countAndSay(self, n):\n if n < 1:\n raise ValueError('Input should be greater than or equal to 1')\n elif n == 1:\n return '1'\n currentCharacter = ''\n currentCharacterCount = 0\n result = list()\n for character in list(self.countAndSay(n-1)):\n if character != currentCharacter:\n if currentCharacter != '':\n result.extend([str(currentCharacterCount), currentCharacter])\n currentCharacter = character\n currentCharacterCount = 1\n else:\n currentCharacterCount += 1\n result.extend([str(currentCharacterCount), currentCharacter])\n return ''.join(result)\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n s = ['1']\n result = '1'\n # The n-th sequance, input 1 should output '1'\n for i in range(n-1):\n start = 0\n temp = []\n \n # Process one sequence, scan from start to end\n while start < len(s):\n count = 1\n next = start + 1\n \n # Scan until s[next] is different\n while next < len(s) and s[start] == s[next]:\n next += 1\n count += 1\n \n # Get the new items in\n temp.append(str(count))\n temp.append(s[start])\n \n # Start from next one\n start = next\n \n # Concatenate list into string, using \",\" as separator in default\n result = ''.join(temp)\n s = temp\n \n return result\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n \n if n == 1:\n return \"1\"\n \n seq = self.countAndSay(n-1)\n \n seq2 = \"\"\n count = 0\n \n for i in range(len(seq)):\n num = seq[i]\n count += 1\n if i == len(seq)-1:\n seq2 = seq2 + str(count) + num\n elif seq[i+1] != seq[i]:\n seq2 = seq2 + str(count) + num\n count = 0 #reset count\n \n return seq2 \n", "class Solution:\n def countAndSay(self, n):\n s = [['1']]\n for i in range(n): # \u67d0\u4e00\u4e2a\u5b50\u4e32\n str1 = s[i]\n temp = []\n # for j in range(len(str1)): # \u67d0\u4e00\u4e2a\u65b0\u5b57\u7b26\n j = 0\n while j < len(str1):\n count = 1\n while j <= len(str1)-2 and str1[j] == str1[j+1]:\n count += 1\n j += 1\n temp.append(str(count))\n temp.append(str1[j])\n j += 1\n s.append(temp)\n \n # res = 0\n # for t in s[n-1]:\n # res = res * 10 + int(t)\n \n res = [''.join(s[n-1])]\n \n return res[0]\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n res = '1'\n if n < 2:\n return res\n while 1:\n n -= 1\n if n == 0:\n return res\n res = self._say(res)\n \n def _say(self, s):\n s += '*'\n curr, res = '', ''\n t = 0\n for i, c in enumerate(s):\n if i == 0:\n curr = c\n t = 1\n else:\n if c == curr:\n t += 1\n else:\n res = res + str(t) + curr\n t = 1\n curr = c\n return res", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n if n == 0:\n return 0\n else:\n s = '1'\n for i in range(n-1):\n res = ''\n k = 0\n m = len(s)\n count = 1\n while k < m:\n say = s[k]\n if k+1 < m:\n if s[k] == s[k+1]:\n count +=1\n k+=1\n else:\n res += str(count)\n res += say\n count = 1\n k+= 1\n else:\n res += str(count)\n res += say\n break\n s = res\n return s\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n if n == 0:\n return 0\n else:\n s = '1'\n for i in range(n-1):\n res = ''\n k = 0\n m = len(s)\n count = 1\n while k < m:\n say = s[k]\n if k+1 < m:\n if s[k] == s[k+1]:\n count +=1\n k+=1\n else:\n res += str(count)\n res += say\n count = 1\n k+= 1\n else:\n res += str(count)\n res += say\n break\n s = res\n return s\n", "class Solution:\n def countAndSay(self, n):\n '''\n not mine!\n '''\n s = '1'\n for _ in range(n - 1):\n s = re.sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), s)\n return s\n", "class Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n if n == 1:\n return \"1\"\n \n n = n-1\n string = '1'\n for i in range(n):\n a = string[0]\n count = 0\n final = ''\n for s in string:\n if a != s:\n final+=str(count)\n final+=a\n count = 1\n a = s\n else:\n count += 1\n final+=str(count)\n final+=s\n string = final\n \n return final "] | {"fn_name": "countAndSay", "inputs": [[1]], "outputs": ["1"]} | INTRODUCTORY | PYTHON3 | LEETCODE | 8,782 |
class Solution:
def countAndSay(self, n: int) -> str:
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.