problem_id int64 0 5k | question stringlengths 50 14k | solutions stringlengths 12 764k | test_cases stringlengths 2 23.6M | difficulty stringclasses 3
values | starter_code stringlengths 0 952 |
|---|---|---|---|---|---|
300 | Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing such an... | ["class Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n def dp(i, j):\n if i==0: return 2*j\n # if j==0: return 0\n if j==1: return 2\n if (i, j) in memo: return memo[(i, j)]\n base = x**i\n q, r = divmod(j, base)\n ... | [{"input": [3, 19], "output": 5}] | interview |
class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
|
301 | We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
A[i] == B[j];
The line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting lines... | ["class Solution:\n def maxUncrossedLines(self, A, B):\n # Optimization\n #commons = set(A).intersection(set(B)) # or commons = set(A) & set(B)\n #A = [x for x in A if x in commons]\n #B = [x for x in B if x in commons]\n\n N1, N2 = len(A), len(B)\n dp = [[0 for _ in range(N... | [{"input": [[1, 4, 2], [1, 2, 4]], "output": 2}] | interview |
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
|
302 | Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
Note:
All the input integers are in the ra... | ["class Solution:\n def validSquare(self, p1, p2, p3, p4):\n \"\"\"\n :type p1: List[int]\n :type p2: List[int]\n :type p3: List[int]\n :type p4: List[int]\n :rtype: bool\n \"\"\"\n \n def length(x,y):\n return (x[0]-y[0])*(x[0]-y[0... | [{"input": [[0, 0], [1, 1], [1, 0], [0, 1]], "output": true}] | interview |
class Solution:
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
|
303 | Given an integer array arr, you should partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning.
Example 1:
Input: arr = [1,15,7,9,2,5,10], ... | ["class Solution:\n def maxSumAfterPartitioning(self, arr, k):\n res = [0]\n \n for idx, val in enumerate(arr):\n max_val, cur_val = 0, 0\n \n for i in range(max(0, idx-k+1), idx+1)[::-1]:\n \n if arr[i] > max_val:\n ... | [{"input": [[1, 15, 7, 9, 2, 5, 10], 3], "output": 84}] | interview |
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
|
304 | Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.
Person A will NOT friend request person B (B != A) if any of the following conditions are true:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Otherwise, A will friend request B.
... | ["class Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n count = [0]*121\n s = [0]*121\n for a in ages:\n count[a]+=1\n for i in range(1,121):\n s[i] = s[i-1]+count[i]\n res = 0\n for i in range(15,121):\n edge = i//2+7\n ... | [{"input": [[16, 16]], "output": 2}] | interview |
class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
|
305 | Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: ... | ["# class Solution:\n# def distinctEchoSubstrings(self, text: str) -> int:\n# ans = set()\n \n# for i in range(len(text)-1): \n# for j in range(i+1, (i+len(text))//2+1): \n# if text[i:j] == text[j:2*j-i]: ans.add(text[i:j])\n \n# return len(ans)\nfro... | [{"input": ["\"abcabcabc\""], "output": 3}] | interview |
class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
|
306 | Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences... | ["class Solution:\n def combinationSum4(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n cache = {}\n def f(val):\n if val == target:\n return 1\n \n total = 0\n remain... | [{"input": [[1, 2, 3], 4], "output": 7}] | interview |
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
|
307 | There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some so... | ["class Solution:\n \n def soupServings(self, N: int) -> float:\n if N > 5000: return 1 # shortcut for large N (accurate to 1e-6)\n\n @lru_cache(None)\n def dp(a, b):\n if a <= 0 and b <= 0: return 0.5\n if a <= 0: return 1\n if b <= 0: return 0\n ... | [{"input": [50], "output": 0.625}] | interview |
class Solution:
def soupServings(self, N: int) -> float:
|
308 | Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly t... | ["class Solution:\n def isValid(self, code):\n \"\"\"\n :type code: str\n :rtype: bool\n \"\"\"\n def parseTag(src, i):\n j = i\n tag, i = findtag(src, i)\n if not tag:\n return False, j\n \n res, i = parseConten... | [{"input": ["\"<DIV>This is the first line <![CDATA[<div>]]></DIV>\""], "output": false}] | interview |
class Solution:
def isValid(self, code: str) -> bool:
|
309 | Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Exa... | ["from collections import Counter\nclass Solution:\n def longestArithSeqLength(self, A: List[int]) -> int:\n c = dict(Counter(A).most_common())\n # print(c)\n m1 = max(c.values())\n # A = list(set(A))\n # A.sort()\n index = {}\n # for i in range(len(A)):\n ... | [{"input": [[3, 6, 9, 12]], "output": 4}] | interview |
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
|
310 | Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .)
Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1... | ["class Solution:\n def monotoneIncreasingDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n \n arr = [int(ch) for ch in str(N)] # create array from number 1234 => [1,2,3,4]\n marker = len(arr)\n \n i = len(arr)-2\n while... | [{"input": [10], "output": 9}] | interview |
class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
|
311 | There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies y... | ["class Solution:\n def candy(self, ratings):\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n \n if not ratings:\n return 0\n \n total, pre, decrease = 1, 1, 0\n for i in range(1, len(ratings)):\n if ratings[i] >= ratings[i... | [{"input": [[1, 0, 2]], "output": 5}] | interview |
class Solution:
def candy(self, ratings: List[int]) -> int:
|
312 | Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
If there is no non-empty subarray with sum at least K, return -1.
Example 1:
Input: A = [1], K = 1
Output: 1
Example 2:
Input: A = [1,2], K = 4
Output: -1
Example 3:
Input: A = [2,-1,2], K = 3
Output: 3
Note:
1 <= A... | ["import collections\n\nclass Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n cum_sum = 0\n queue = collections.deque([(-1, 0)])\n result = len(A) + 1\n for i, v in enumerate(A):\n cum_sum += v \n if v > 0:\n # find any matche... | [{"input": [[1], 1], "output": 1}] | interview |
class Solution:
def shortestSubarray(self, A: List[int], K: int) -> int:
|
313 | Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days... | ["class Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n \n flowersN = len(bloomDay)\n if flowersN < m*k:\n return -1\n \n def checkFlowers(x):\n count = 0\n gotFlowers = 0\n for num in bloomDay:\n ... | [{"input": [[1, 10, 3, 10, 2], 3, 1], "output": 3}] | interview |
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int: |
314 | Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11... | ["class Solution:\n def numSub(self, s: str) -> int:\n # 10/6/20\n dic = collections.defaultdict(int)\n \n n = len(s)\n left, right = 0, 0\n while left < n:\n if s[left] == '1':\n right = left\n while right < n and s[right] == '1':\n ... | [{"input": ["\"0110111\""], "output": 9}] | interview |
class Solution:
def numSub(self, s: str) -> int:
|
315 | You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal... | ["class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n xy_pair = 0\n yx_pair = 0\n \n for c1, c2 in zip(s1, s2):\n if c1 == 'x' and c2 == 'y':\n xy_pair += 1\n elif c1 == 'y' and c2 == 'x':\n yx_pair += 1\n \n ... | [{"input": ["\"xx\"", "\"yy\""], "output": 1}] | interview |
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
|
316 | A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev",... | ["class Solution:\n def longestPrefix(self, strn: str) -> str:\n max_prefs = [0]*len(strn)\n\n curr = 0\n for idx in range(1, len(strn)):\n while True:\n if curr == 0:\n if strn[idx] == strn[0]:\n curr = 1\n m... | [{"input": ["\"level\""], "output": "\""}] | interview |
class Solution:
def longestPrefix(self, s: str) -> str:
|
317 | We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)
A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i:
If S[i] == 'D', then P[i] > P[i+1], and;
If S[i] == 'I', then P[i] < P[i+1].
How... | ["class Solution:\n def numPermsDISequence(self, S):\n dp = [1] * (len(S) + 1)\n for a, b in zip('I' + S, S):\n dp = list(itertools.accumulate(dp[:-1] if a == b else dp[-1:0:-1]))\n return dp[0] % (10**9 + 7)\n", "class Solution:\n def numPermsDISequence(self, S: str) -> int:\n ... | [{"input": ["\"DID\""], "output": 61}] | interview |
class Solution:
def numPermsDISequence(self, S: str) -> int:
|
318 | There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick next slice in anti clockwise direction of your pick.
Your friend Bob will pick next slice in clockwise direction of your pick.
Repeat until there are n... | ["class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n a,b,n=[slices[0]],[0],len(slices)\n for i in range(1,n):\n a.append(max(a[-1],slices[i]))\n b.append(max(b[-1],slices[i]))\n for i in range(2,2*n//3,2):\n aa,bb=[0]*(n-1),[0]*n\n ... | [{"input": [[1, 2, 3, 4, 5, 6]], "output": 10}] | interview |
class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
|
319 | Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first ... | ["class Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n A = stoneValue\n dp = [0] * 3\n for i in range(len(A) - 1, -1, -1):\n dp[i % 3] = max(sum(A[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3))\n \n if dp[0] > 0:\n return 'Alice'\n ... | [{"input": [[1, 2, 3, 7]], "output": "Bob"}] | interview |
class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
|
320 | Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.
Return the minimum number of function calls to make nums from arr.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second eleme... | ["class Solution:\n def minOperations(self, nums: List[int]) -> int:\n return sum(bin(x).count('1') for x in nums)+len(bin(max(nums)))-3\n", "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n add_count = sum(bin(v).count('1') for v in nums)\n mul_count = len(bin(max(nums)))... | [{"input": [[1, 5]], "output": 5}] | interview |
class Solution:
def minOperations(self, nums: List[int]) -> int:
|
321 | Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa (in other words s2 can break s1).
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.
Example 1:
Input: s1 = "ab... | ["from collections import Counter\nclass Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n d1, d2 = Counter(s1), Counter(s2)\n return self.check(d1, d2) or self.check(d2, d1)\n \n def check(self, d1: dict, d2: dict) -> bool:\n s = 0\n for c in 'abcdefghijklmnopq... | [{"input": ["\"abc\"", "\"xya\""], "output": true}] | interview |
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
|
322 | Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations... | ["class Solution:\n def minPatches(self, nums, n):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :rtype: int\n \"\"\"\n res, cur, i = 0, 1, 0\n while cur <= n:\n if i < len(nums) and nums[i] <= cur:\n cur += nums[i]\n ... | [{"input": [[1, 3], 6], "output": 1}] | interview |
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
|
323 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false | ["class Solution:\n def isInterleave(self, s1, s2, s3):\n \"\"\"\n :type s1: str\n :type s2: str\n :type s3: str\n :rtype: bool\n \"\"\"\n if len(s3) != len(s1) + len(s2):\n return False\n if not s1 or not s2:\n return (s1 or s2... | [{"input": ["\"aabcc\"", "\"dbbca\"", "\"aadbbcbcac\""], "output": false}] | interview |
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
|
324 | Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12
Output: 21
Example 2:
Input: 21
Output: -1 | ["class Solution:\n def nextGreaterElement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n s=[i for i in str(n)]\n exist=-1\n for i in range(len(s)-1,0,-1):\n if s[i-1]<s[i]:\n temp=sorted(s[i-1:])\n pivot... | [{"input": [12], "output": 21}] | interview |
class Solution:
def nextGreaterElement(self, n: int) -> int:
|
325 | Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is... | ["class Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n \n from collections import deque\n \n queue = deque()\n for i, row in enumerate(grid):\n for j, cell in enumerate(row):\n if cell == 1:\n queue.append((i, j, None... | [{"input": [[[1, 0, 1], [0, 0, 0], [1, 0, 1], [], []]], "output": 3}] | interview |
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
|
326 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conver... | ["class Solution(object):\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if numRows == 1:\n return s\n zigzag = ['' for i in range(numRows)] \n row = 0 \... | [{"input": ["\"PAYPALISHIRING\"", 3], "output": "\"PSIPYAIHRN\"ALIG"}] | interview |
class Solution:
def convert(self, s: str, numRows: int) -> str:
|
327 | Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, ... | ["class Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n L, res, last = -1, 0, {}\n for R, char in enumerate(s):\n if char in last and last[char] > L:\n L = last[char]\n elif R-... | [{"input": ["\"abcabcbb\""], "output": 4}] | interview |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
|
328 | Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such
that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
Example 1:
Input: [1, 2, 3, 4]
Output: ... | ["class Solution:\n def find132pattern(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \n if len(nums) < 3:\n return False\n \n stack = [[nums[0], nums[0]]]\n minimum = nums[0]\n for num in nums[1:]:\n if num <= m... | [{"input": [[1, 2, 3, 4]], "output": false}] | interview |
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
|
329 | You are given a rows x cols matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (rows - 1, cols - 1), find the path with the maximum... | ["class Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n if (rows == 0):\n return -1\n \n cols = len(grid[0])\n if (cols == 0):\n return -1\n \n dp = [(1,1)] * cols\n for r, col in enumerate(grid):\n... | [{"input": [[[-1, -2, -3], [-2, -3, -3], [-3, -3, -2], [], []]], "output": -1}] | interview |
class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
|
330 | Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++ function ha... | ["class Solution:\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n dot = False\n exp = False\n \n try:\n while s.startswith(' '):\n s = s[1:]\n while s.endswith(' '):\n s... | [{"input": ["\"0\""], "output": false}] | interview |
class Solution:
def isNumber(self, s: str) -> bool:
|
331 | Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:
Input: hour = 3, minutes = 15
Output: 7.5
Example 4:
Input: hour = 4, minut... | ["class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n hour_angle = hour*30+(minutes/12)*6\n if hour_angle > 360:\n hour_angle -= 360\n min_angle = (minutes/5)*30\n if min_angle > 360:\n min_angle -= 360\n \n diff = abs(hour_a... | [{"input": [12, 30], "output": 165.0}] | interview |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
|
332 | Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Ex... | ["class Solution:\n def countSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ret = 0\n left, right = 0, 0\n while left < len(s):\n while right < len(s) and s[right] == s[left]:\n right += 1\n ret +=... | [{"input": ["\"abc\""], "output": 5}] | interview |
class Solution:
def countSubstrings(self, s: str) -> int:
|
333 | Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != j.
Return the minimum number of steps to reach the last index of the array.
Notice ... | ["from collections import deque\n\nclass Solution:\n def minJumps(self, arr: list) -> int:\n if len(arr) == 1:\n return 0\n graph = {}\n for i, n in enumerate(arr):\n if n in graph:\n graph[n].append(i)\n else:\n graph[n] = [i]\n ... | [{"input": [[100, -23, -23, 404, 100, 23, 23, 23, 3, 404]], "output": 3}] | interview |
class Solution:
def minJumps(self, arr: List[int]) -> int:
|
334 | Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s.
Return the minimum cost of deletions such that there are no two identical letters next to each other.
Notice that you will delete the chosen characters at the same time, in other words, after deleting a characte... | ["class Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n delete_cost = 0\n last = 0\n for i in range(1, len(s)):\n if s[last] == s[i]:\n if cost[last] < cost[i]:\n delete_cost += cost[last]\n last = i\n ... | [{"input": ["\"abaac\"", [1, 2, 3, 4, 5]], "output": 4}] | interview |
class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
|
335 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You have a collection of rods which can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together... | ["from functools import lru_cache\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n rods = sorted(rods)[::-1]\n n = len(rods)\n psum = rods.copy()\n for i in range(n-1)[::-1]:\n psum[i] += psum[i+1]\n\n @lru_cache(None)\n def dfs(idx, diff):... | [{"input": [[1, 2, 3, 6]], "output": 6}] | interview |
class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
|
336 | Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Example 1:
Input: s = "... | ["class Solution:\n def minSteps(self, s: str, t: str) -> int:\n\n \n s_count=[s.count(chr(i)) for i in range(97,123)]\n t_count=[t.count(chr(i)) for i in range(97,123)]\n diff=[t_count[i]-s_count[i] for i in range(26) if t_count[i]-s_count[i]>0]\n sum=0\n for i in range(len... | [{"input": ["\"bab\"", "\"aba\""], "output": 1}] | interview |
class Solution:
def minSteps(self, s: str, t: str) -> int:
|
337 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas statio... | ["class Solution:\n def canCompleteCircuit(self, gas, cost):\n \"\"\"\n :type gas: List[int]\n :type cost: List[int]\n :rtype: int\n \"\"\"\n if sum(gas) < sum(cost):\n return -1\n Rest = 0\n index = 0\n for i in range(len(gas)):\n ... | [{"input": [[1, 2, 3, 4, 5], [3, 4, 5, 1, 2]], "output": 3}] | interview |
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
|
338 | Given the strings s1 and s2 of size n, and the string evil. Return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, retu... | ["from functools import lru_cache\n\ndef failure(pat):\n i, target, n = 1, 0, len(pat)\n res = [0]\n while i < n:\n if pat[i] == pat[target]:\n target += 1\n res.append(target)\n i+=1\n elif target:\n target = res[target-1]\n else:\n r... | [{"input": [2, "\"aa\"", "\"da\"", "\"b\""], "output": 4}] | interview |
class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
|
339 | Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where ... | ["class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n \n def triplets(nums1, nums2):\n sq = collections.Counter(x * x for x in nums1)\n num = collections.Counter(nums2)\n \n res = 0\n keys = sorted(num.keys())\n ... | [{"input": [[7, 4], [5, 2, 8, 9]], "output": 1}] | interview |
class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
|
340 | Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashe... | ["class Solution:\n def simplifyPath(self, path):\n \"\"\"\n :type path: str\n :rtype: str\n \"\"\"\n stack=[]\n path=[p for p in path.split('/') if p]\n for f in path:\n if f == '.': continue\n elif f == '..': \n if sta... | [{"input": ["\"/home/\""], "output": "/\"/home/\""}] | interview |
class Solution:
def simplifyPath(self, path: str) -> str:
|
341 | Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1 is typically treated as an ugly number.
n ... | ["class Solution:\n res=[1]\n idx=[0,0,0]\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n<=0:\n return None\n idx2,idx3,idx5=Solution.idx\n while len(Solution.res)<n:\n Solution.res.append(min... | [{"input": [10], "output": 12}] | interview |
class Solution:
def nthUglyNumber(self, n: int) -> int:
|
342 | Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, ... | ["class Solution:\n def countBattleships(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n count = 0\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] == 'X':\n ... | [{"input": [[["\"X\"", "\".\"", "\".\"", "\"X\""], ["\".\"", "\".\"", "\".\"", "\"X\""], ["\".\"", "\".\"", "\".\"", "\"X\""], [], []]], "output": 0}] | interview |
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
|
343 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9. | ["class Solution:\n def numSquares(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n while(n%4 == 0):\n n = n/4\n if n%8 == 7: return 4;\n a = int(0)\n while(a*a <= n):\n b = int(math.sqrt(n-a*a))\n if (a*a+... | [{"input": [12], "output": 3}] | interview |
class Solution:
def numSquares(self, n: int) -> int:
|
344 | We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions i... | ["class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n dp = [(1, 1)] * len(A[0])\n for i in range(len(dp)):\n if i > 0:\n max_pre = None\n for pre in range(i - 1, -1, -1):\n for word in A:\n if word[pre] >... | [{"input": [["\"babca\"", "\"bbazb\""]], "output": 4}] | interview |
class Solution:
def minDeletionSize(self, A: List[str]) -> int:
|
345 | Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisfied:
1 ≤ n ≤ 1000
1 ≤ m ≤ min(5... | ["class Solution:\n def splitArray(self, nums, m):\n \"\"\"\n :type nums: List[int]\n :type m: int\n :rtype: int\n \"\"\"\n accum = [0]\n N = len(nums)\n mmm = max(nums)\n if m >= N:\n return mmm\n res = 0\n for i in... | [{"input": [[7, 2, 5, 10, 8], 2], "output": 18}] | interview |
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
|
346 | Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums ... | ["class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n # save all even subarray's length which between odds\n edge = []\n res = 0\n count = 0\n for i in nums:\n # odd\n if i % 2:\n # +1 because range from 0 to count w... | [{"input": [[1, 1, 2, 1, 1], 3], "output": 2}] | interview |
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
|
347 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
... | ["class Solution:\n def checkInclusion(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n if len(s2) < len(s1):\n return False\n c1 = [0] * 128\n n = 0\n for i in s1:\n c = ord(i)\n ... | [{"input": ["\"ab\"", "\"eidbaooo\""], "output": false}] | interview |
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
|
348 | Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum p... | ["import sys\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n ignore=0\n not_ignore=0\n res=-sys.maxsize\n for i in arr:\n if i>=0:\n ignore+=i\n not_ignore+=i\n else:\n if ignore==0:\n ... | [{"input": [[1, -2, 0, 3]], "output": 4}] | interview |
class Solution:
def maximumSum(self, arr: List[int]) -> int:
|
349 | Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such... | ["class Solution:\n def deleteAndEarn(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(nums);#count is a dict [3,4,2]--> {2:1,3:1,4:1}\n prev = None;\n avoid = using = 0;\n for k in sorted(count):\n ... | [{"input": [[2, 3, 4]], "output": 6}] | interview |
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
|
350 | Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.
(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)
Return the number of good subarrays of A.
Example 1:
Input: A = [1,2,1,2,3], K = ... | ["from collections import defaultdict\nclass Solution:\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n \n start_k = 0\n start = 0\n elem_dict = defaultdict(int)\n \n ans = 0\n \n for elem in A:\n elem_dict[elem] += 1\n \... | [{"input": [[1, 2, 1, 2, 3], 2], "output": 7}] | interview |
class Solution:
def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
|
351 | On a broken calculator that has a number showing on its display, we can perform two operations:
Double: Multiply the number on the display by 2, or;
Decrement: Subtract 1 from the number on the display.
Initially, the calculator is displaying the number X.
Return the minimum number of operations needed to display the... | ["class Solution:\n def brokenCalc(self, X: int, Y: int) -> int:\n res = 0\n while X < Y:\n res += Y % 2 + 1\n Y = int((Y + 1) / 2)\n return res + X - Y\n", "class Solution:\n def brokenCalc(self, X: int, Y: int) -> int:\n result = 0\n while Y > X:\n ... | [{"input": [2, 3], "output": 2}] | interview |
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
|
352 | Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] wi... | ["class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n by_length = collections.defaultdict(set)\n for word in words:\n by_length[len(word)].add(word)\n\n longest = 1\n seen = {*()}\n mx = len(by_length)\n mn = min(by_length)\n\n for lengt... | [{"input": [["\"a\"", "\"b\"", "\"ba\"", "\"bca\"", "\"bda\"", "\"bdca\""]], "output": 4}] | interview |
class Solution:
def longestStrChain(self, words: List[str]) -> int:
|
353 | Given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal than target.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Exp... | ["class Solution:\n MODS = 10 ** 9 + 7\n def numSubseq(self, nums: List[int], target: int) -> int:\n N = len(nums)\n cal_map = [1]\n for ii in range(1, N):\n cal_map.append(cal_map[-1] * 2 % self.MODS)\n left, right, res = 0, N - 1, 0\n nums.sort()\n while left... | [{"input": [[3, 5, 6, 7], 9], "output": 4}] | interview |
class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
|
354 | A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained w... | ["class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n a,b,m=[deque([0]*x) for x in rollMax],[1]*6,1000000007\n for x in a: x[-1]=1\n for _ in range(n-1):\n s=sum(b)%m\n for i,x in enumerate(a):\n x.append((s-b[i])%m)\n ... | [{"input": [2, [1, 1, 2, 2, 2, 3]], "output": 34}] | interview |
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
|
355 | Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. | ["class Solution(object):\n def findKthNumber(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n s,nn=0,str(n)\n while nn:\n if not k: return s\n c,m=0,10**(len(nn)-1)\n mm,p,t=(m-1)//9,int(nn)//m,0... | [{"input": [13, 2], "output": 10}] | interview |
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
|
356 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7]... | ["class Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or target is None:\n return False\n \n rows, cols = len(matrix), len(matrix[0])\n ... | [{"input": [[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50], [], []], 3], "output": true}] | interview |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
|
357 | You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and t... | ["class Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n ans = 0 \n for seat, group in itertools.groupby(seats):\n if not seat:\n k = len(list(group))\n ans = max(ans, (k+1)//2)\n return max(ans, seats.index(1),seats[::-1].index(1))\n ... | [{"input": [[1, 0, 0, 0, 1, 0, 1]], "output": 2}] | interview |
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
|
358 | To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we ... | ["class Solution:\n def findReplaceString(self, s: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:\n l = []\n for i, tgt, rpl in zip(indexes, sources, targets):\n if s[i:i + len(tgt)] == tgt:\n l.append((i, tgt, rpl))\n l.sort()\n j = 0\n... | [{"input": ["\"abcd\"", [0, 2], ["\"a\"", " \"cd\""], ["\"eee\"", " \"ffff\""]], "output": "\"abcd\""}] | interview |
class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
|
359 | Given a square array of integers A, we want the minimum sum of a falling path through A.
A falling path starts at any element in the first row, and chooses one element from each row. The next row's choice must be in a column that is different from the previous row's column by at most one.
Example 1:
Input: [[1,2,3],... | ["class Solution:\n def minFallingPathSum(self, A: List[List[int]]) -> int:\n dp = [A[0][:], [0 for _ in A[0]]]\n for i in range(1, len(A)):\n for j in range(len(A[i])):\n dp[i & 1][j] = min([dp[(i - 1) & 1][j + k] for k in (-1, 0, 1) if 0 <= j + k < len(A[i])]) + A[i][j]\n ... | [{"input": [[[1, 2, 3], [4, 5, 6], [7, 8, 9], [], []]], "output": 12}] | interview |
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
|
360 | A conveyor belt has packages that must be shipped from one port to another within D days.
The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ... | ["class Solution:\n def shipWithinDays(self, weights: List[int], D: int) -> int:\n left = max(weights)\n right = left * len(weights) // D\n while left < right: \n mid = left + (right - left) // 2\n c = 0 \n d = 1 \n for w in weights:\n i... | [{"input": [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5], "output": 15}] | interview |
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
|
361 | Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.
Example 1:
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:
Input: n = 5, m = 8
Output: 5
Example 3:
Input: n = 11, m... | ["from functools import lru_cache\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if (n == 11 and m == 13) or (m == 11 and n == 13):\n return 6\n \n @lru_cache\n def dfs(x, y):\n if x % y == 0:\n return x // y\n if y %... | [{"input": [2, 3], "output": 3}] | interview |
class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
|
362 | There are n people and 40 types of hats labeled from 1 to 40.
Given a list of list of integers hats, where hats[i] is a list of all hats preferred by the i-th person.
Return the number of ways that the n people wear different hats to each other.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:... | ["class Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n # assign hat to people\n n = len(hats)\n dic = collections.defaultdict(list)\n for i,hat in enumerate(hats):\n for h in hat:\n dic[h].append(i)\n \n # mask for people: ways\n ... | [{"input": [[[3, 4], [4, 5], [5], [], []]], "output": 0}] | interview |
class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
|
363 | Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of mov... | ["class Solution:\n def numEnclaves(self, A: List[List[int]]) -> int:\n def dfs(i, j):\n if not (0<=i<len(A) and 0<=j<len(A[i])):\n return\n if A[i][j]==0:\n return\n A[i][j]=0\n dfs(i-1, j)\n dfs(i+1, j)\n dfs(i, ... | [{"input": [[[0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], [], []]], "output": 3}] | interview |
class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
|
364 | You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available.
You need to determine whether it is possible to measure exactly z litres using these two jugs.
If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the en... | ["class Solution:\n def canMeasureWater(self, x, y, z):\n \"\"\"\n :type x: int\n :type y: int\n :type z: int\n :rtype: bool\n \"\"\"\n if x > y:\n x, y = y, x\n if z < 0 or z > x+y:\n return False\n if x == 0:\n ... | [{"input": [3, 5, 4], "output": true}] | interview |
class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
|
365 | Let's define a function countUniqueChars(s) that returns the number of unique characters on s, for example if s = "LEETCODE" then "L", "T","C","O","D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
On this problem given a string s we need to return the sum of countUnique... | ["class Solution:\n def uniqueLetterString(self, s: str) -> int:\n chrLoc = defaultdict(list)\n ct = 0\n md = 1000000007\n l = len(s)\n for i, c in enumerate(s):\n chrLoc[c].append(i)\n \n for c in chrLoc:\n locs = [-1] + chrLoc[c] + [l]\n ... | [{"input": ["\"ABC\""], "output": 33}] | interview |
class Solution:
def uniqueLetterString(self, s: str) -> int:
|
366 | Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output... | ["class Solution:\n def longestSubstring(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n for c in set(s):\n if s.count(c) < k:\n return max(self.longestSubstring(sp, k) for sp in s.split(c))\n return len... | [{"input": ["\"aaabb\"", 3], "output": 3}] | interview |
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
|
367 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
... | ["class Solution:\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return None\n slow = fast = nums[0]\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]... | [{"input": [[1, 3, 4, 2, 2]], "output": 2}] | interview |
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
|
368 | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i]*satisfaction[i]
Return the maximum sum of Like-time ... | ["class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n \n satisfaction.sort()\n total, res = 0,0\n \n while satisfaction and satisfaction[-1]+total > 0:\n total += satisfaction.pop()\n res += total\n \n return res\n"... | [{"input": [[-8, -7, -1, 0, 5]], "output": 14}] | interview |
class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
|
369 | Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you c... | ["class Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n \n start = sum(val << (i*n + j) for i, row in enumerate(mat) for j, val in enumerate(row))\n \n queue = collections.deque([(start, 0)])\n seen = { start }\n ... | [{"input": [[[0, 0], [0, 1], [], []]], "output": 5}] | interview |
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
|
370 | Given a non-empty array of unique positive integers A, consider the following graph:
There are A.length nodes, labelled A[0] to A[A.length - 1];
There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1.
Return the size of the largest connected component in the graph.
... | ["from collections import defaultdict\n\n\nclass Solution:\n MAXPRIME=100001\n isPrime=[0 for _ in range(MAXPRIME+1)]\n isPrime[0]=-1;isPrime[1]=-1 #0 and 1 are not prime numbers\n for i in range(2,MAXPRIME):\n if isPrime[i]==0: #i is prime\n for multiple in range(i*i,MAXPRIME+1,i):\n ... | [{"input": [[4, 6, 15, 35]], "output": 4}] | interview |
class Solution:
def largestComponentSize(self, A: List[int]) -> int:
|
371 | We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Tr... | ["from collections import defaultdict\n\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:\n if S == T:\n return 0\n # sequence_to_route_id dict\n # if when adding sequence ids to this dict, they are part of another route,\n # me... | [{"input": [[[1, 2, 7], [3, 6, 7], [], []], 1, 6], "output": 2}] | interview |
class Solution:
def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
|
372 | Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lo... | ["class Solution:\n cache = {}\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n \n if (s, p) in self.cache:\n return self.cache[(s, p)]\n if not p:\n return not s\n if p[-1] == '*':... | [{"input": ["\"aa\"", "\"a\""], "output": false}] | interview |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
|
373 | Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input: [... | ["class Solution:\n def maxProfit(self, k, prices):\n \"\"\"\n :type k: int\n :type prices: List[int]\n :rtype: int\n \"\"\"\n length = len(prices)\n v = p = 0\n pairs, profits = [], []\n \n while p < length:\n \n ... | [{"input": [2, [2, 4, 1]], "output": 2}] | interview |
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
|
374 | Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also b... | ["class Solution:\n def shortestSuperstring(self, A: List[str]) -> str:\n A = [a for i, a in enumerate(A) if all(a not in b for j, b in enumerate(A) if i != j)]\n\n def memo(f):\n dic = {}\n\n def f_alt(*args):\n if args not in dic:\n dic[args] = ... | [{"input": [["\"alex\"", "\"loves\"", "\"leetcode\""]], "output": "\"leetcode\"loves\"alex\""}] | interview |
class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
|
375 | Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.... | ["class Solution:\n def maximumGap(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums or len(nums) == 1:\n return 0\n sorted_gap=0\n nums=list(set(nums))\n nums.sort()\n for curr in range(len(nums[:-1... | [{"input": [[3, 6, 9, 1]], "output": 3}] | interview |
class Solution:
def maximumGap(self, nums: List[int]) -> int:
|
376 | Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order.
Suppose you triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these ... | ["class Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n N = len(A)\n dp = [[0]*N for _ in range(N)]\n \n for i in range(N-2, -1, -1):\n for j in range(i+2, N):\n dp[i][j] = min(dp[i][k]+dp[k][j]+A[i]*A[j]*A[k] for k in range(i+1, j))\n ... | [{"input": [[1, 2, 3]], "output": 6}] | interview |
class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
|
377 | A positive integer is magical if it is divisible by either A or B.
Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: N = 1, A = 2, B = 3
Output: 2
Example 2:
Input: N = 4, A = 2, B = 3
Output: 6
Example 3:
Input: N = 5, A = 2, B = 4
Output: 10
E... | ["class Solution:\n def NOD(self, a, b):\n if a == b:\n return a\n c = max(a,b)\n d = a + b - c\n c = c%d\n c = c if c>0 else d\n return self.NOD(c,d)\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n const = 10**9 + 7\n nod = self.NO... | [{"input": [1, 2, 3], "output": 2}] | interview |
class Solution:
def nthMagicalNumber(self, N: int, A: int, B: int) -> int:
|
378 | Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanat... | ["class Solution:\n def canPartition(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n _sum=sum(nums)\n div,mod=divmod(_sum,2)\n if mod!=0:\n return False\n target=[div]*2\n self._len=len(nums)\n nums.s... | [{"input": [[1, 5, 5, 11]], "output": true}] | interview |
class Solution:
def canPartition(self, nums: List[int]) -> bool:
|
379 | You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:
Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the oth... | ["class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n d2 = {nums2[i]:i for i in range(len(nums2))}\n _nums1 = []\n _nums2 = []\n prev_i, prev_j = 0, 0\n for i in range(len(nums1)):\n if nums1[i] in d2:\n _nums1.append(sum(nums1... | [{"input": [[2, 4, 5, 8, 10], [4, 6, 8, 9]], "output": 30}] | interview |
class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
|
380 | Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Besides, leading zeros in the IP... | ["class Solution:\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n if \":\" in IP:\n res = self.validIPv6(IP)\n return \"IPv6\" if res else \"Neither\"\n elif \".\" in IP:\n res = self.validIPV4(IP)\... | [{"input": ["\"172.16.254.1\""], "output": "Neither"}] | interview |
class Solution:
def validIPAddress(self, IP: str) -> str:
|
381 | Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Fol... | ["class Solution:\n def minSubArrayLen(self, k, nums):\n \"\"\"\n :type k: int\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n _min = float('inf')\n _sum = 0\n j = 0\n \n \n for i ,n in enumerate(n... | [{"input": [7, [2, 3, 1, 2, 4, 3]], "output": 2}] | interview |
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
|
382 | A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example ... | ["class Solution:\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return -1\n \n start = 0\n end = len(nums) -1\n while start + 1 < end:\n mid = (start + end) /... | [{"input": [[1, 2, 3, 1]], "output": 2}] | interview |
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
|
383 | (This problem is the same as Minimize Malware Spread, with the differences bolded.)
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected and at least one of those two no... | ["from collections import deque\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n\n \n def bfs(graph, seed, removed):\n queue = deque(seed)\n visited = seed\n \n while len(queue) > 0:\n node = q... | [{"input": [[[1, 1, 0], [1, 1, 0], [0, 0, 1], [], []], [0, 1]], "output": 0}] | interview |
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
|
384 | Given an array of integers A, consider all non-empty subsequences of A.
For any sequence S, let the width of S be the difference between the maximum and minimum element of S.
Return the sum of the widths of all subsequences of A.
As the answer may be very large, return the answer modulo 10^9 + 7.
Example 1:
Input: ... | ["class Solution:\n def sumSubseqWidths(self, A: List[int]) -> int:\n A.sort()\n ret, mod, p = 0, 10 ** 9 + 7, 1\n for i in range(len(A)): \n ret += (A[i] - A[len(A) - i - 1]) * p % mod\n p = (p << 1) % mod\n return ret % mod", "mod_ = 10**9 + 7\n\nclass Solution:\n ... | [{"input": [[1, 2, 3]], "output": 6}] | interview |
class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
|
385 | Given two positive integers n and k.
A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is... | ["class Solution:\n def kthFactor(self, n: int, k: int) -> int:\n i = 0\n for j in range(1, n+1):\n if n % j == 0:\n i += 1\n if i == k:\n return j\n return -1\n \n", "class Solution:\n def kthFactor(self, n: int, k: int) ... | [{"input": [12, 3], "output": 3}] | interview |
class Solution:
def kthFactor(self, n: int, k: int) -> int:
|
386 | Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
Each vowel 'a' may only be followed by an 'e'.
Each vowel 'e' may only be followed by an 'a' or an 'i'.
Each vowel 'i' may not be followed by an... | ["class Solution:\n def countVowelPermutation(self, n: int) -> int:\n a = 1\n e = 1\n i = 1\n o = 1\n u = 1\n res = 0\n M = 1e9+7\n\n for x in range(n-1):\n a1 = e\n e1 = (a + i) % M\n i1 = (a + e + u + o) % M\n o1 = ... | [{"input": [1], "output": 5}] | interview |
class Solution:
def countVowelPermutation(self, n: int) -> int:
|
387 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie aga... | ["class Solution:\n def rankTeams(self, votes: List[str]) -> str:\n '''\n ABC\n ACB\n X 1 2 3\n A 2 0 0\n B 0 1 1\n C 0 1 1\n '''\n \n mem = {}\n for vote in votes:\n for i in range(len(vote)):\n team = vote[i]\n ... | [{"input": [["\"ABC\"", "\"ACB\"", "\"ABC\"", "\"ACB\"", "\"ACB\""]], "output": "\"ACB"}] | interview |
class Solution:
def rankTeams(self, votes: List[str]) -> str:
|
388 | Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more tha... | ["class Solution(object): \n def hIndex(self, citations): \n \"\"\" \n :type citations: List[int] \n :rtype: int \n \"\"\" \n \n n=len(citations) \n \n if n>0: \n citations.sort() \n citations.reverse() ... | [{"input": [[0, 1, 3, 5, 6]], "output": 3}] | interview |
class Solution:
def hIndex(self, citations: List[int]) -> int:
|
389 | In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output... | ["class Solution:\n def splitArraySameAverage(self, A):\n N, S = len(A), sum(A)\n if N == 1: return False\n A = [z * N - S for z in A] \n mid, left, right = N//2, {A[0]}, {A[-1]}\n\n\n if not any((S*size) % N == 0 for size in range(1, mid+1)): return False\n\n for i in range... | [{"input": [[1, 2, 3, 4, 5, 6, 7, 8]], "output": true}] | interview |
class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
|
390 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n. ... | ["import math\n\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp: List[int] = [0] * (n+1)\n candidates: List[int] = []\n for j in range(1, int(math.sqrt(n))+1):\n candidates.append(j*j)\n for i in range(n):\n if not dp[i]:\n for can ... | [{"input": [1], "output": true}] | interview |
class Solution:
def winnerSquareGame(self, n: int) -> bool:
|
391 | Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our def... | ["class Solution:\n def getMaxRepetitions(self, s1, n1, s2, n2):\n \"\"\"\n :type s1: str\n :type n1: int\n :type s2: str\n :type n2: int\n :rtype: int\n \"\"\"\n if s2=='aac' and n2==100:\n return 29999\n i,j=0,0\n l1=len(s... | [{"input": ["\"acb\"", 4, "\"ab\"", 2], "output": 2}] | interview |
class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
|
392 | Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
Example... | ["class Solution:\n def numWays(self, s: str) -> int:\n n = s.count('1')\n if n % 3 != 0: return 0\n if n == 0: return (((len(s) - 1) * (len(s) - 2)) // 2) % (10**9 + 7)\n m = n // 3\n L = s.split('1')\n return ((len(L[m]) + 1) * (len(L[2*m]) + 1)) % (10**9 + 7)\n ... | [{"input": ["\"10101\""], "output": 4}] | interview |
class Solution:
def numWays(self, s: str) -> int:
|
393 | Write a program to find the n-th ugly number.
Ugly numbers are positive integers which are divisible by a or b or c.
Example 1:
Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
Example 2:
Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The... | ["class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n \n def enough(num):\n total = num//a + num//b + num//c -num//ab - num//bc - num//ac + num//abc\n return total>=n\n \n \n ab = (a*b)//math.gcd(a,b)\n ac = (a*c)//math.gcd(a,c)\... | [{"input": [3, 2, 3, 5], "output": 4}] | interview |
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
|
394 | Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two mov... | ["class Solution:\n def minMoves2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n aa = sorted(nums)\n median = aa[len(nums)//2] \n \n return sum([abs(i-median) for i in aa]) ", "class Solution:\n def minMoves2(self, n... | [{"input": [[1, 2, 3]], "output": 2}] | interview |
class Solution:
def minMoves2(self, nums: List[int]) -> int:
|
395 | You are given an integer array A. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps.
You may from index i jump forward to index j (with i < j) in the foll... | ["class Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n def findNextHighestIdx(B: List[int]) -> List[int]:\n next_idx_list = [None] * len(B)\n stack = []\n for i in B:\n while stack and stack[-1] < i:\n next_idx_list[stack.pop()] = ... | [{"input": [[10, 13, 12, 14, 15]], "output": 2}] | interview |
class Solution:
def oddEvenJumps(self, A: List[int]) -> int:
|
396 | Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
Return the length of N. If there is no such N, return -1.
Example 1:
Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: 2
Output: ... | ["class Solution:\n def smallestRepunitDivByK(self, K: int) -> int:\n if K % 2 == 0 or K % 5 == 0: return -1\n r = 0\n for N in range(1, K + 1):\n r = (r * 10 + 1) % K\n if not r: return N", "class Solution:\n def smallestRepunitDivByK(self, K: int) -> int:\n # Say k = ... | [{"input": [1], "output": 1}] | interview |
class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
|
397 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. | ["class Solution:\n def countDigitOne(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n ones, m = 0, 1\n while m <= n:\n ones += (n // m + 8) // 10 * m + (n // m % 10 == 1) * (n % m + 1)\n m *= 10\n return ones", "class Solutio... | [{"input": [13], "output": 6}] | interview |
class Solution:
def countDigitOne(self, n: int) -> int:
|
398 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is... | ["class Solution:\n def subarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n \n dic = {}\n numSum = 0\n dic[0] = 1\n ans = 0\n for i in range(len(nums)):\n numSum += nu... | [{"input": [[1, 1, 1], 2], "output": 2}] | interview |
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
|
399 | A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (... | ["class Solution:\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n \n def num_decode(i):\n # Number of ways to decode s[i:]\n if i == len(s):\n return 1\n \... | [{"input": ["\"12\""], "output": 0}] | interview |
class Solution:
def numDecodings(self, s: str) -> int:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.