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 |
|---|---|---|---|---|---|
400 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit... | ["class Solution:\n def largestRectangleArea(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: int\n \"\"\"\n \n if not heights:\n return 0\n stack = [0]\n heights.append(0)\n # print(heights)\n max_area = 0\n ... | [{"input": [[2, 1, 5, 6, 2, 3, -1]], "output": 10}] | interview |
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
|
401 | Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanat... | ["#5:09\n'''\nnums = [3,6,5,1,8]\nsum_nums = 23\nmod3_sum_nums = 2\nmod3_dict = {0:[3,6], 1:[1], 2:[5,8]}\nhelper([5,8], [1]) -> 5\n\n\n\n\n\n'''\n\nfrom collections import defaultdict\nclass Solution:\n def helper(self, l1, l2):\n if len(l1) < 1 and len(l2) <2:\n sum_remove = 0\n elif len(l... | [{"input": [[3, 6, 5, 1, 8]], "output": 18}] | interview |
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
|
402 | In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y < 10^6.
We start at the source square and want to reach the target square. Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of blocked squares.
Return true if and only if ... | ["import heapq\n\ndef solve(b,s,t):\n def create_priority_item(c, t):\n dx = c[0]-t[0]\n dy = c[1]-t[1]\n d2 = dx*dx + dy*dy\n return (d2, c)\n\n b = set(tuple(_b) for _b in b)\n s = tuple(s)\n t = tuple(t)\n # heap = [(-1,s)]\n heap = [s]\n visited = set()\n iter = -... | [{"input": [[[0, 1], [1, 0], [], []], [0, 0], [0, 2]], "output": false}] | interview |
class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
|
403 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1
else return false.
Your algorithm should run in O(n) time complexity and O(1) sp... | ["class Solution:\n def increasingTriplet(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n1 = n2 = float('inf')\n for n in nums:\n if n <= n1:\n n1 = n\n elif n <= n2:\n n2 = n\n ... | [{"input": [[1, 2, 3, 4, 5]], "output": true}] | interview |
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
|
404 | We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 2... | ["class Solution:\n def largestSumOfAverages(self, A: List[int], K: int) -> float:\n #if not A: return 0\n #if len(A)==1: return A[0]\n # Real Run Time is a little bit UNSTABLE\n N = len(A)\n P = [0] * (N+1)\n for i in range(1,N+1): P[i] = P[i-1] + A[i-1]\n \n ... | [{"input": [[9, 1, 2, 3, 9], 3], "output": 20.0}] | interview |
class Solution:
def largestSumOfAverages(self, A: List[int], K: int) -> float:
|
405 | Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal proba... | ["class Solution:\n def new21Game(self, N: int, K: int, W: int) -> float:\n dp = [0] * (N + W)\n for i in range(K, N + 1):\n dp[i] = 1\n \n S = min(W, N - K + 1)\n for i in range(K - 1, -1, -1):\n dp[i] = S / W\n S += dp[i] - dp[i + W]\n retu... | [{"input": [10, 1, 10], "output": 1.0}] | interview |
class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
|
406 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
N... | ["class Solution:\n def ladderLength(self, beginWord, endWord, wordList):\n \n wordDict = set(wordList)\n if not endWord in wordDict:\n return 0\n \n visited = set()\n \n beginSet = set()\n beginSet.add(beginWord)\n visited.add(beginWord)\n \n endS... | [{"input": ["\"hit\"", "\"cog\"", ["\"hot\"", "\"dot\"", "\"dog\"", "\"lot\"", "\"log\"", "\"cog\""]], "output": 5}] | interview |
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
|
407 | Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: "()"
Output: 1
Example 2:
Input: "(())"
Output: 2... | ["class Solution:\n def scoreOfParentheses(self, S: str) -> int:\n ans, val = 0, 1\n for i in range(len(S) - 1):\n if S[i: i+2] == '((': val *= 2\n if S[i: i+2] == '()': ans += val\n if S[i: i+2] == '))': val //= 2\n return ans", "class Solution:\n def scoreOf... | [{"input": ["\"()\""], "output": 1}] | interview |
class Solution:
def scoreOfParentheses(self, S: str) -> int:
|
408 | Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.
In case of a tie, return the minimum such integer.
Notice... | ["class Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort()\n n = len(arr)\n for i in range(n):\n sol = round(target / n)\n if arr[i] >= sol:\n return sol\n target -= arr[i]\n n -= 1\n return arr[... | [{"input": [[4, 9, 3], 10], "output": 3}] | interview |
class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
|
409 | Given an integer array arr and an integer k, modify the array by repeating it k times.
For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.
As the a... | ["class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n oneArrSum = sum(arr)\n twoArr = arr + arr\n \n def findMaxSub(array):\n if len(array) == 1:\n return array[0]\n \n cur = 0\n small = 0\n ... | [{"input": [[1, 2], 3], "output": 9}] | interview |
class Solution:
def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
|
410 | The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:
if x is even then x = x / 2
if x is odd then x = 3 * x + 1
For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers ... | ["class Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n return sorted(range(lo, hi + 1), key='\u5bd2\u5bd2\u5bd3\u5bd9\u5bd4\u5bd7\u5bda\u5be2\u5bd5\u5be5\u5bd8\u5be0\u5bdb\u5bdb\u5be3\u5be3\u5bd6\u5bde\u5be6\u5be6\u5bd9\u5bd9\u5be1\u5be1\u5bdc\u5be9\u5bdc\u5c41\u5be4\u5be4\u5be4\u5c3c\u5bd7\... | [{"input": [12, 15, 2], "output": 13}] | interview |
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
|
411 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictiona... | ["class Solution:\n def wordBreak(self, s, wordDict):\n n = len(s)\n dp = [False for i in range(n+1)]\n dp[0] = True\n for i in range(1,n+1):\n for w in wordDict:\n if dp[i-len(w)] and s[i-len(w):i]==w:\n dp[i]=True\n return dp[... | [{"input": ["\"leetcode\"", ["\"leet\"", "\"code\""]], "output": false}] | interview |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
412 | You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces. There is only... | ["from math import comb\nfrom math import pow\nclass Solution:\n\n \n \n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n if(target < d*1 or target > d*f ):\n return 0\n target = target - d\n sum = 0\n i = 0\n j=0\n while(i <= target):\n... | [{"input": [1, 6, 3], "output": 1}] | interview |
class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
|
413 | Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome.
After doing so, return the final string. If there is no way to do so, return the empty string.
Example 1:
Input: pali... | ["class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return ''\n for i, val in enumerate(palindrome):\n if val != 'a' and i != len(palindrome) // 2:\n return palindrome[:i] + 'a' + palindrome[i+1:]\n elif val... | [{"input": ["\"abccba\""], "output": "aabccba\""}] | interview |
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
|
414 | Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array.... | ["class Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n win=0\n \n curr = arr[0]\n mx=0\n \n \n for i in range(1,len(arr)): \n if arr[i] > curr:\n curr=arr[i]\n win=0\n \n wi... | [{"input": [[5, 1, 2, 3, 4, 6, 7], 2], "output": 5}] | interview |
class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
|
415 | We have two integer sequences A and B of the same non-zero length.
We are allowed to swap elements A[i] and B[i]. Note that both elements are in the same index position in their respective sequences.
At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and on... | ["class Solution:\n def minSwap(self, A: List[int], B: List[int]) -> int:\n \n n = len(A)\n \n if n == 1:\n return 0\n \n dp = [[float('inf'), float('inf')] for _ in range(n)]\n dp[0] = [0,1] #[natural, swapped]\n \n for i in range(1, n):\n ... | [{"input": [[1, 3, 5, 4], [1, 2, 3, 7]], "output": 1}] | interview |
class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
|
416 | A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During each playe... | ["class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n N = len(graph)\n\n # What nodes could play their turn to\n # arrive at node (mouse, cat, turn) ?\n def parents(mouse, cat, turn):\n prev_turn = 3 - turn\n if prev_turn == MOUSE: \n ... | [{"input": [[[2, 5], [3], [0, 4, 5], [1, 4, 5], [2, 3], [0, 2, 3], [], []]], "output": 0}] | interview |
class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
|
417 | There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5 | ["class Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n nums = nums1 + nums2\n nums.sort()\n if len(nums) % 2 == 1:\n return float(nums[len(nu... | [{"input": [[1, 3], [2]], "output": 2.0}] | interview |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
|
418 | Given a positive integer n and you can do operations as follow:
If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Inpu... | ["class Solution:\n def integerReplacement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n '''\n if n == 1:\n return 0\n if not (n & 1):\n return self.integerReplacement(n//2) + 1\n return min(self.integerReplacement(... | [{"input": [8], "output": 3}] | interview |
class Solution:
def integerReplacement(self, n: int) -> int:
|
419 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how ma... | ["class Solution:\n def bulbSwitch(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0:\n return 0\n else:\n return int(n**0.5)\n \n", "class Solution:\n def bulbSwitch(self, n):\n \"\"\"\n :type n: ... | [{"input": [3], "output": 1}] | interview |
class Solution:
def bulbSwitch(self, n: int) -> int:
|
420 | Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of th... | ["class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n s = s + 'a'\n bits, dp = {'a':0,'e':1,'i':2,'o':3,'u':4}, {0:-1}\n res = 0\n key = 0\n for i, char in enumerate(s): \n if char in bits:\n if key in dp:\n ... | [{"input": ["\"eleetminicoworoep\""], "output": 13}] | interview |
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
|
421 | Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: "leetcode"
Output: "tcode"
Note:
1 <= s.length <= 4 *... | ["class Solution:\n def lastSubstring(self, s: str) -> str:\n #mx = \\\"\\\"\n #for i in range(len(s)):\n # mx = max(mx,s[i:])\n #return mx\n index = {c: i for i, c in enumerate(sorted(set(s)))}\n cur, radix, max_val, max_i = 0, len(index), 0, 0\n for i in range(le... | [{"input": ["\"abab\""], "output": "bab\""}] | interview |
class Solution:
def lastSubstring(self, s: str) -> str:
|
422 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb" | ["class Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n size = len(s)\n if size <= 1 or s == s[::-1]:\n return s\n start, maxlen = 0, 1\n for idx in range(1, size):\n add2 = s... | [{"input": ["\"babad\""], "output": "bab"}] | interview |
class Solution:
def longestPalindrome(self, s: str) -> str:
|
423 | Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithm... | ["from collections import defaultdict\n\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n count_dict = defaultdict(int)\n for num in arr:\n count_dict[num] = count_dict[num-difference] + 1\n return max(count_dict.values())\n", "class Solution:\... | [{"input": [[1, 2, 3, 4], 1], "output": 4}] | interview |
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
|
424 | You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the over... | ["class Solution:\n def largestOverlap(self, A, B) -> int:\n leng = len(A[0])\n\n # convert A, B to binary\n a = 0\n b = 0\n for i in range(0, leng * leng):\n row = int(i % leng)\n col = int(i / leng)\n a = (a << 1) + A[col][row]\n b = (b... | [{"input": [[[1, 1, 0], [0, 1, 0], [0, 1, 0], [], []], [[0, 0, 0], [0, 1, 1], [0, 0, 1], [], []]], "output": 3}] | interview |
class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
|
425 | Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, d... | ["class Solution:\n def get_half(self,dividend,divisor):\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n num = divisor\n num_temp=0\n result=1\n result_temp=0\n while (num<=dividend):\n num_temp=num\n num+=num\n ... | [{"input": [10, 3], "output": 3}] | interview |
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
|
426 | Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this in a way such that the resulting number is a power of 2.
Example 1:
Input: 1
Output: true
Example 2:
Input: 10
Output: false
E... | ["class Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n \n n_len = len(str(n))\n n = Counter(str(n))\n \n p = 1\n while len(str(p)) <= n_len:\n if len(str(p)) == n_len and Counter(str(p)) == n:\n return True\n p *= 2\n \... | [{"input": [1], "output": true}] | interview |
class Solution:
def reorderedPowerOf2(self, N: int) -> bool:
|
427 | Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 al... | ["class Solution:\n def countOrders(self, n: int) -> int:\n \n if n == 1:\n return 1\n \n \n p = (n-1)*2+1\n \n dp = [0 for i in range(n+1)]\n dp[1] = 1\n M= 10**9+7\n for i in range(2,n+1):\n \n p = (i-1)*2+1\n ... | [{"input": [1], "output": 1}] | interview |
class Solution:
def countOrders(self, n: int) -> int:
|
428 | We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.
We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wal... | ["import heapq\nfrom collections import deque, defaultdict\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n m,n = len(grid),len(grid[0])\n key_lock_loc = {ch:(i,j) for i,row in enumerate(grid) for j,ch in enumerate(row) if ch not in {'.','#'}}\n key_cnt = sum(key_lock ... | [{"input": [["\"@.a.#\"", "\"###.#\"", "\"b.A.B\""]], "output": 8}] | interview |
class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
|
429 | You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") a... | ["class Solution:\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n :rtype: str\n \"\"\"\n s_count = collections.defaultdict(int)\n g_count = collections.defaultdict(int)\n bull_cnt = 0\n # first iteration ca... | [{"input": ["\"1807\"", "\"7810\""], "output": "3A3B"}] | interview |
class Solution:
def getHint(self, secret: str, guess: str) -> str:
|
430 | Given a string S, count the number of distinct, non-empty subsequences of S .
Since the result may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
Example 2:
Input: "aba"
Output: 6
Explanation: Th... | ["class Solution:\n def distinctSubseqII(self, s: str) -> int:\n n = len(s)\n MOD = 10**9 + 7\n seen = dict()\n \n a = 1\n for i in range(n):\n char = s[i]\n b = 2 * a\n if char in seen:\n b -= seen[char]\n \n ... | [{"input": ["\"abc\""], "output": 30}] | interview |
class Solution:
def distinctSubseqII(self, S: str) -> int:
|
431 | Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimum... | ["class Solution:\n def sumSubarrayMins(self, A: List[int]) -> int:\n stack = []\n result = 0\n A = [0] + A + [0]\n\n for i, x in enumerate(A):\n while stack and x < A[stack[-1]]:\n j = stack.pop()\n result += A[j] * (i - j) * (j - stack[-1])\n ... | [{"input": [[3, 1, 2, 4, 0]], "output": 17}] | interview |
class Solution:
def sumSubarrayMins(self, A: List[int]) -> int:
|
432 | Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
Return True if its possible otherwise return False.
Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]... | ["class Solution:\n def isPossibleDivide(self, s: List[int], k: int) -> bool:\n if len(s) % k != 0:\n return False\n \n ctr = collections.Counter(s)\n \n for _ in range(len(s) // k):\n mn = []\n for i in ctr:\n if mn == [] and ctr[i] ... | [{"input": [[1, 2, 3, 3, 4, 4, 5, 6], 4], "output": true}] | interview |
class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
|
433 | Given an array of integers arr and two integers k and threshold.
Return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively... | ["class Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n if len(arr) < k:\n return 0\n bar = k * threshold\n total = 0\n window = sum(arr[:k])\n if window >= bar:\n total += 1\n for i in range(k, len(arr)):\n ... | [{"input": [[2, 2, 2, 2, 5, 5, 5, 8], 3, 4], "output": 3}] | interview |
class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
|
434 | Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array.
Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 n... | ["class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n if not 0 in nums:\n return len(nums) - 1\n ans = 0\n tot = 0\n prev = 0\n \n for n in nums:\n if n == 1:\n tot += 1\n else:\n ans = max(tot... | [{"input": [[1, 1, 0, 1]], "output": 3}] | interview |
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
|
435 | Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
... | ["# Calculate the prefix sum and count it.\n# In c++ and java, a % K + K takes care of the cases where a < 0.\n# Python\n\nclass Solution: \n def subarraysDivByK(self, A, K):\n res = 0\n prefix = 0\n count = [1] + [0] * K\n for a in A:\n prefix = (prefix + a) % K\n r... | [{"input": [[4, 5, 0, -2, -3, 1], 5], "output": 7}] | interview |
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
|
436 | There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges (n) is divisible by 2 then you can eat n/2 oranges.
If the number of remaining oranges (n) is divisible by 3 then you can eat 2*(n/3) oranges.
You can only choose ... | ["import functools\nclass Solution:\n @functools.lru_cache()\n def minDays(self, n: int) -> int:\n if n <= 1:\n return n\n \n return 1 + min(n%2 + self.minDays(n//2), n%3 + self.minDays(n//3))\n \n", "memo={}; f=min\nclass Solution:\n def minDays(self, n: int) -> int:... | [{"input": [10], "output": 4}] | interview |
class Solution:
def minDays(self, n: int) -> int:
|
437 | An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d), the entire current tape is repeatedly w... | ["class Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n size = 0\n # Find size = length of decoded string\n for c in S:\n if c.isdigit():\n size *= int(c)\n else:\n size += 1\n for c in reversed(S):\n K %= size\n... | [{"input": ["\"leet2code3\"", 10], "output": "t"}] | interview |
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
|
438 | Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero.
At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are given an integer m and you need to ... | ["class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n A = arr\n if m == len(A): \n return m\n length = [0] * (len(A) + 2)\n res = -1\n for i, a in enumerate(A):\n left, right = length[a - 1], length[a + 1]\n if left == m or ... | [{"input": [[3, 5, 1, 2, 4], 1], "output": 4}] | interview |
class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
|
439 | A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
That is, the subarray is turbulent if the comparison sign flips between each... | ["class Solution:\n def maxTurbulenceSize(self, A: List[int]) -> int:\n if len(A) == 1: return 1\n prev = A[1]\n maxcount = count = 1 + int(A[0] != A[1])\n print(count)\n lastcomp = A[0] < A[1]\n \n for a in A[2:]:\n comp = prev < a\n if prev == ... | [{"input": [[9, 4, 2, 10, 7, 8, 8, 1, 9]], "output": 5}] | interview |
class Solution:
def maxTurbulenceSize(self, A: List[int]) -> int:
|
440 | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th rec... | ["class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n while p % 2 == 0 and q % 2 == 0:\n p = p // 2\n q = q // 2\n if p % 2 == 1 and q % 2 == 0:\n return 0\n elif p % 2 == 1 and q % 2 == 1:\n return 1\n else :\n ret... | [{"input": [2, 1], "output": 2}] | interview |
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
|
441 | Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?
Example 1:
Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3
Example 2:
Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
N... | ["class Solution:\n def consecutiveNumbersSum(self, N: int) -> int:\n res = 1\n \n # Remove all even factors\n while N % 2 == 0:\n N //= 2\n \n # Count all odd factors\n idx = 3 \n while idx * idx <= N:\n count = 0\n \n ... | [{"input": [5], "output": 2}] | interview |
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
|
442 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diago... | ["class Solution:\n def minSwaps(self, grid: List[List[int]]) -> int:\n start=1\n swap=0\n n=len(grid)\n zeros_ingrid=n-1\n while zeros_ingrid>0:\n swapped_grid=False\n for i in range(len(grid)):\n if sum(grid[i][start:])==0:\n ... | [{"input": [[[0, 0, 1], [1, 1, 0], [1, 0, 0], [], []]], "output": 3}] | interview |
class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
|
443 | There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if: (rating[i] < rating[j] < rating[k]) or (ratin... | ["class Solution:\n def increment_index(self, nums, index):\n index += 1\n while index < len(nums):\n nums[index] += 1\n index += (index & -index)\n\n def prefix_sum(self, nums, index):\n index += 1\n current_sum = 0\n while index > 0:\n current_... | [{"input": [[2, 5, 3, 4, 1]], "output": 3}] | interview |
class Solution:
def numTeams(self, rating: List[int]) -> int:
|
444 | n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:
Take their own seat if it is still available,
Pick other seats randomly when they find their seat occupied
What is the probability that the n-th person... | ["class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1 / min(n, 2.0) \n \n", "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n if n == 1:\n return float(1)\n return float(0.5)", "class Solution:\n def nthPersonGetsNthSeat(self,... | [{"input": [1], "output": 1.0}] | interview |
class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
|
445 | Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.
Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: Change the array [5,3,2,4] to [2,2,2,2].
Th... | ["class Solution:\n def minDifference(self, nums: List[int]) -> int:\n if len(nums) <= 4:\n return 0\n else:\n # nums = sorted(nums)\n nums.sort()\n threeZero = nums[-1] - nums[3]\n twoOne = nums[-2] - nums[2]\n oneTwo = nums[-3] - nums[... | [{"input": [[2, 3, 4, 5]], "output": 0}] | interview |
class Solution:
def minDifference(self, nums: List[int]) -> int:
|
446 | Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and eithe... | ["# O(n) time and space\n# Hashmap and array\n# Count number then count occurrence:\n# Count the occurrences of each number using HashMap;\n# Keep a count of different occurences\n# From small to big, for each unvisited least frequent element, deduct from k the multiplication with the number of elements of same occurre... | [{"input": [[5, 5, 4], 1], "output": 1}] | interview |
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: |
447 | Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input: "bcabc"
Output: "abc"
Example 2:
Input: "cbacdcbc"
Output: "a... | ["class Solution:\n def removeDuplicateLetters(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n rindex = {c: i for i, c in enumerate(s)}\n result = ''\n for i, c in enumerate(s):\n if c not in result:\n while c < result[-1... | [{"input": ["\"bcabc\""], "output": "\"abc"}] | interview |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
|
448 | Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.
Example 1:
Input: [23, 2, 4, 6, 7], k=6
Output: True
Explanation: Because [2, 4] is... | ["class Solution:\n def checkSubarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if k==0:\n j=0\n for i in range(0,len(nums)):\n if nums[i]==0:\n if j<i:\n ... | [{"input": [[23, 2, 4, 6, 7], 6], "output": true}] | interview |
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
|
449 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0 | ["class Solution:\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) <= 3:\n return min(nums)\n lo = 0\n hi = len(nums) - 1\n mid = (hi + lo) // 2\n if nums[mid] < nums[mid-1] and nums[... | [{"input": [[3, 4, 5, 1, 2]], "output": 1}] | interview |
class Solution:
def findMin(self, nums: List[int]) -> int:
|
450 | A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
For 1-byte character, the first bit is a 0, followed by its unicode code.
For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
This is how the UTF-8 enc... | ["class Solution:\n def validUtf8(self, data):\n \"\"\"\n :type data: List[int]\n :rtype: bool\n \"\"\"\n count=0\n for x in data:\n if count==0:\n if x>>5==0b110:\n count=1\n elif x>>4==0b1110:\n ... | [{"input": [[197, 130, 1]], "output": true}] | interview |
class Solution:
def validUtf8(self, data: List[int]) -> bool:
|
451 | Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
In general a rational number can be represented using up to three parts: an integer part, a ... | ["import math\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n if len(S) == 0 or len(T) == 0:\n return False\n def process(s):\n if s[-1] == '.':\n s = s[:-1]\n stack, repeat_9 = [], False\n for i, x in enumerate(s):\n ... | [{"input": ["\"0.(52)\"", "\"0.5(25)\""], "output": true}] | interview |
class Solution:
def isRationalEqual(self, S: str, T: str) -> bool:
|
452 | You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maxim... | ["class Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n N = len(jobDifficulty)\n if N < d: \n return -1\n \n dp = [jobDifficulty[0]]\n for j in jobDifficulty[1:]:\n dp.append(max(dp[-1], j))\n\n for i in range(1, d):\n ... | [{"input": [[6, 5, 4, 3, 2, 1], 2], "output": 7}] | interview |
class Solution:
def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
|
453 | There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that has been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color. (For example: houses = [1,2,2,3,3... | ["class Solution:\n def minCost(self, houses: List[int], Cost: List[List[int]], m: int, n: int, target: int) -> int:\n @lru_cache(None)\n def dfs(i, j, k):\n if i == len(houses):\n if j == target:\n return 0\n else:\n return... | [{"input": [[0, 0, 0, 0, 0], [[1, 10], [10, 1], [10, 1], [1, 10], [5, 1], [], []], 5, 2, 3], "output": 9}] | interview |
class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
|
454 | Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The give... | ["class Solution:\n def maximumSwap(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n s = str(num)\n nums = [int(_) for _ in s]\n dp = [-1]*len(nums)\n for i in range(len(nums)-1,-1,-1):\n if i==len(nums)-1:\n d... | [{"input": [2736], "output": 7236}] | interview |
class Solution:
def maximumSwap(self, num: int) -> int:
|
455 | There is a strange printer with the following two special requirements:
On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
Once the printer has used a color for the above operation, the same color cannot be used again... | ["from collections import deque\n\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n grids = targetGrid\n num_to_range = dict()\n for i, row in enumerate(targetGrid):\n for j, val in enumerate(row):\n if val not in num_to_range:\n ... | [{"input": [[[1, 1, 1, 1], [1, 2, 2, 1], [1, 2, 2, 1], [1, 1, 1, 1], [], []]], "output": true}] | interview |
class Solution:
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
|
456 | A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on th... | ["class Solution:\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n if stones == []: return False\n if len(stones) == 1: return True\n diff = [0]*len(stones)\n \n for i in range(1,len(stones)):\n ... | [{"input": [[0, 1, 3, 4, 5, 7, 9, 10, 12]], "output": true}] | interview |
class Solution:
def canCross(self, stones: List[int]) -> bool:
|
457 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each ki... | ["class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n n, res = len(coins), amount + 1\n\n def dfs(index, target, cnt):\n nonlocal res\n if cnt + (target + coins[index] - 1) // coins[index] >= res:\n retur... | [{"input": [[1, 2, 5], 11], "output": 3}] | interview |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
|
458 | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a con... | ["class Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n need = sum(nums) % p\n if need == 0:\n return 0\n pos = {0: -1}\n total = 0\n ans = float('inf')\n for i, num in enumerate(nums):\n total = (total + num) % p\n targe... | [{"input": [[3, 1, 4, 2], 6], "output": 1}] | interview |
class Solution:
def minSubarray(self, nums: List[int], p: int) -> int:
|
459 | Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 1... | ["class Solution:\n def characterReplacement(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n if s == \"\":\n return 0\n count = {}\n lo = 0\n hi = 0\n max_letter = 0\n for hi in range(len... | [{"input": ["\"ABAB\"", 2], "output": 4}] | interview |
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
|
460 | A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]]... | ["class Solution:\n def arrayNesting(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n best = 0\n n = len(nums)\n p = []\n for i in range(len(nums)):\n j = i\n current = 0\n while nums[j] != -1:\... | [{"input": [[5, 4, 0, 3, 1, 6, 2]], "output": 4}] | interview |
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
|
461 | A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company has is the one with headID.
Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed that the subordination... | ["class Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n def dfs(i):\n if manager[i] != -1:\n informTime[i] += dfs(manager[i])\n manager[i] = -1\n return informTime[i]\n return max(list(map(d... | [{"input": [1, 0, [-1], [0]], "output": 0}] | interview |
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
|
462 | You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any other ser... | ["#[Runtime: 452 ms, faster than 97.27%] Hash\n#O(MN)\n#1. traverse all cells and mark server as (x, y)\n#2. put each server (x, y) into serveral bucket named x1, x2, .., and y1, y2, ..\n# e.g. each xbucket[x1] maintains the number of servers on line x1\n#3. enumerate all server (x', y'), and see if there is at least 2... | [{"input": [[[1, 0], [0, 1], [], []]], "output": 0}] | interview |
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
|
463 | You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 <= i < nums.length-1.
You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.
Find maximum possible value of the final array.
Example 1:
Input... | ["class Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n n = len(nums)\n base = sum([abs(nums[i] - nums[i+1]) for i in range(n - 1)])\n if (n <= 2):\n return base\n \n #best = base\n #for i in range(n-1):\n # for j in range(i+1, n):\... | [{"input": [[2, 3, 1, 5, 4]], "output": 10}] | interview |
class Solution:
def maxValueAfterReverse(self, nums: List[int]) -> int:
|
464 | You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array e... | ["class Solution:\n def minOperations(self, n: int) -> int:\n return (n*n)>>2\n \n", "class Solution:\n def minOperations(self, n: int) -> int:\n if n % 2 == 0:\n return (n//2)*(n//2)\n else:\n return (n-1)*(1+(n-1)//2)//2", "class Solution:\n def minOp... | [{"input": [3], "output": 2}] | interview |
class Solution:
def minOperations(self, n: int) -> int:
|
465 | Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. | ["class Solution:\n def minCut(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # acceleration\n if s == s[::-1]: return 0\n if any(s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1] for i in range(1, len(s))): return 1\n # algorithm\n cut... | [{"input": ["\"aab\""], "output": 3}] | interview |
class Solution:
def minCut(self, s: str) -> int:
|
466 | We are given a personal information string S, which may represent either an email address or a phone number.
We would like to mask this personal information according to the following rules:
1. Email address:
We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-... | ["class Solution:\n def maskPII(self, S: str) -> str:\n if '@' in S:\n name, domain = S.split('@')\n return name[0].lower() + '*****' + name[-1].lower() + '@' + domain.lower()\n else:\n number = ''\n for c in S:\n if c.isdigit():\n ... | [{"input": ["\"LeetCode@LeetCode.com\""], "output": "\"*****e@leetcode.com\""}] | interview |
class Solution:
def maskPII(self, S: str) -> str:
|
467 | Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors.
If there is no such integer in the array, return 0.
Example 1:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answe... | ["# 1390. Four Divisors\n# version 2, with optimized prime-finding.\n\nimport math\n\ndef remove (lst, index):\n assert lst\n tail = len (lst) - 1\n lst[index], lst[tail] = lst[tail], lst[index]\n lst.pop ()\n\ndef swap_min (lst):\n if not lst: return\n argmin = min (range (len (lst)), key = lambda i:... | [{"input": [[21, 4, 7]], "output": 32}] | interview |
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
|
468 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Outpu... | ["class Solution:\n def fractionToDecimal(self, numerator, denominator):\n \"\"\"\n :type numerator: int\n :type denominator: int\n :rtype: str\n \"\"\"\n if numerator*denominator < 0:\n add_negative = True\n else:\n add_negative = Fals... | [{"input": [1, 2], "output": "0.5"}] | interview |
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
|
469 | You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no v... | ["class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \n leftset, rightset = set(leftChild), set(rightChild)\n roots = []\n for i in range(n):\n if i not in leftset and i not in rightset: \n roots.ap... | [{"input": [4, [1, -1, 3, -1], [2, -1, -1, -1]], "output": true}] | interview |
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
|
470 | Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.
As the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (A[i], A[j],... | ["class Solution:\n def threeSumMulti(self, A: List[int], target: int) -> int:\n counter = collections.Counter(A)\n i, res, l, ckey = 0, 0, len(counter), sorted(list(counter.keys()))\n if target % 3 == 0:\n res += math.comb(counter[target // 3], 3)\n for i in range(l):\n ... | [{"input": [[1, 1, 2, 2, 3, 3, 4, 4, 5, 5], 8], "output": 20}] | interview |
class Solution:
def threeSumMulti(self, A: List[int], target: int) -> int:
|
471 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Examp... | ["class Solution:\n def expandIsland(self, grid, i, j):\n edges = [(i, j)]\n while edges:\n next_edges = []\n for edge in edges:\n ei, ej = edge\n if ei >= 0 and ei < len(grid) and ej >= 0 and ej < len(grid[ei]) and grid[ei][ej] == '1':\n ... | [{"input": [[["\"1\"", "\"1\"", "\"1\"", "\"1\"", "\"0\""], ["\"1\"", "\"1\"", "\"0\"", "\"1\"", "\"0\""], ["\"1\"", "\"1\"", "\"0\"", "\"0\"", "\"0\""], ["\"0\"", "\"0\"", "\"0\"", "\"0\"", "\"0\""], [], []]], "output": 0}] | interview |
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
|
472 | Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,... | ["class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n \n dq = collections.deque([start])\n visited = set([start])\n \n while dq:\n \n curr = dq.pop()\n \n if arr[curr] == 0:\n return True\n ... | [{"input": [[4, 2, 3, 0, 3, 1, 2], 5], "output": true}] | interview |
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
|
473 | Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) ... | ["class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n n = len(arr)\n res = xors = 0\n freq = collections.defaultdict(int, {0:1})\n _sum = collections.defaultdict(int)\n for i in range(n):\n xors ^= arr[i]\n res += freq[xors] * i - _sum[xors]\n ... | [{"input": [[2, 3, 1, 6, 7]], "output": 4}] | interview |
class Solution:
def countTriplets(self, arr: List[int]) -> int:
|
474 | Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. ... | ["class Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n let=Counter(letters)\n sc={}\n for i in range(26):\n sc[chr(i+ord('a'))]=score[i]\n word={}\n for w in words:\n word[w]=Counter(w)\n self.ans=0... | [{"input": [["\"dog\"", "\"cat\"", "\"dad\"", "\"good\""], ["\"a\"", "\"a\"", "\"c\"", "\"d\"", "\"d\"", "\"d\"", "\"g\"", "\"o\"", "\"o\""], [1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "output": 0}] | interview |
class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
|
475 | Given the array nums consisting of n positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the n... | ["class Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n # B: partial sum of A\n # C: partial sum of B\n # Use prefix sum to precompute B and C\n A = nums\n B, C = [0] * (n + 1), [0] * (n + 1)\n for i in range(n):\n B[i + 1]... | [{"input": [[1, 2, 3, 4], 4, 1, 5], "output": 13}] | interview |
class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
|
476 | N cars are going to the same destination along a one lane road. The destination is target miles away.
Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.
A car can never pass another car ahead of it, but it can catch up to it, and driv... | ["class Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n if not position:\n return 0\n \n posToSpeed = {position[i]: speed[i] for i in range(len(position))}\n position.sort()\n \n leaderTime = (target - position[-1]) / p... | [{"input": [12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3]], "output": 3}] | interview |
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
|
477 | Given two positive integers n and k, the binary string Sn is formed as follows:
S1 = "0"
Si = Si-1 + "1" + reverse(invert(Si-1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
For example, t... | ["class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n i = n - 1\n invert = False\n while i > 0:\n half_len = (2**(i + 1) - 1) // 2 \n if k == half_len + 1:\n return '1' if not invert else '0'\n \n if k > half_len:\n ... | [{"input": [3, 1], "output": "0"}] | interview |
class Solution:
def findKthBit(self, n: int, k: int) -> str:
|
478 | Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,... | ["class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n a = set(nums)\n a = sum(a)*3 - sum(nums)\n return int(a/2)", "class Solution:\n def singleNumber(self, nums):\n return (3*sum(set(nums))-sum... | [{"input": [[2, 2, 3, 2]], "output": 3}] | interview |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
|
479 | There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is a list of integers r... | ["class Solution:\n def leastBricks(self, wall):\n \"\"\"\n :type wall: List[List[int]]\n :rtype: int\n \"\"\"\n d = {}\n for i in wall:\n suma = 0\n for j in range(len(i)-1):\n suma += i[j]\n if suma in d:\n ... | [{"input": [[[1, 2, 2, 1], [3, 1, 2], [1, 3, 2], [2, 4], [3, 1, 2], [1, 3, 1, 1], [], []]], "output": 4}] | interview |
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
|
480 | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your poi... | ["# https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/569521/7-python-approaches-with-Time-and-Space-analysis\nclass Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n r = min(arrLen, steps // 2 + 1)\n dp = [0, 1]\n for t in range(steps... | [{"input": [3, 2], "output": 4}] | interview |
class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
|
481 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to th... | ["class Solution(object):\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n size = len(nums)\n if size < 3:\n return 0\n nums.sort()\n i = 0 # fix the first inde... | [{"input": [[-4, -1, 1, 2], 1], "output": 2}] | interview |
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
|
482 | Given an array arr of positive integers, consider all binary trees such that:
Each node has either 0 or 2 children;
The values of arr correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.)
The value of each non-leaf node is equal to... | ["class Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n if not arr: return 0\n \n res = []\n\n while len(arr) > 1:\n temp_res = []\n temp_res = [arr[i]*arr[i+1] for i in range(len(arr)-1)]\n idx = temp_res.index(min(temp_res))\n\n ... | [{"input": [[6, 2, 4]], "output": 32}] | interview |
class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
|
483 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not... | ["class Solution:\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n # l = []\n # maxH = 0\n # for i in range(len(height)-1, -1, -1):\n # if height[i] > maxH:\n # maxH = height[i]\n # ... | [{"input": [[1, 8, 6, 2, 5, 4, 8, 3, 7]], "output": 49}] | interview |
class Solution:
def maxArea(self, height: List[int]) -> int:
|
484 | Find the smallest prime palindrome greater than or equal to N.
Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
For example, 2,3,5,7,11 and 13 are primes.
Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
For exam... | ["import bisect\n\n\nclass Solution:\n def primePalindrome(self, N: int) -> int:\n return primes[bisect.bisect_left(primes, N)]\n\n\nprimes = [\n 2,\n 3,\n 5,\n 7,\n 11,\n 101,\n 131,\n 151,\n 181,\n 191,\n 313,\n 353,\n 373,\n 383,\n 727,\n 757,\n 787,\n ... | [{"input": [6], "output": 7}] | interview |
class Solution:
def primePalindrome(self, N: int) -> int:
|
485 | In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of K-bit flips required so that there is no 0 in the array. If it is not possible, return ... | ["class Solution:\n def minKBitFlips(self, A: List[int], K: int) -> int:\n n = len(A)\n record = [0] * n\n flip = 0\n ans = 0\n for i in range(n):\n if i >= K: flip -= record[i-K]\n if A[i] == (flip % 2):\n if i > n - K: return -1\n ... | [{"input": [[0, 1, 0], 1], "output": 2}] | interview |
class Solution:
def minKBitFlips(self, A: List[int], K: int) -> int:
|
486 | Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.
Example 1:
Input: S = "0110", N = 3
Output: true
Example 2:
Input: S = "0110", N = 4
Output: false
Note:
1 <... | ["class Solution:\n def queryString(self, S: str, N: int) -> bool:\n for i in range(1,N+1):\n b = bin(i).replace('0b','')\n if b not in S:\n return False\n return True", "class Solution:\n def int_to_bin(self,x):\n ret=''\n if x==0:\n retu... | [{"input": ["\"0110\"", 3], "output": true}] | interview |
class Solution:
def queryString(self, S: str, N: int) -> bool:
|
487 | A string is called happy if it does not have any of the strings 'aaa', 'bbb' or 'ccc' as a substring.
Given three integers a, b and c, return any string s, which satisfies following conditions:
s is happy and longest possible.
s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' ... | ["class Solution:\n def longestDiverseString(self, a: int, b: int, c: int) -> str:\n if a == 0 and b == 0 and c == 0:\n return ''\n\n res = ''\n\n heap = [(-a, 'a'), (-b, 'b'), (-c, 'c')]\n heapq.heapify(heap)\n prev_val = 0\n prev_char = ''\n\n while heap:... | [{"input": [1, 1, 7], "output": "ccaccbcc"}] | interview |
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
|
488 | Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.... | ["class Solution:\n def kthSmallest(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n arr = []\n for i in matrix:\n for j in i:\n arr.append(j)\n arr.sort()\n print(ar... | [{"input": [[[1, 5, 9], [10, 11, 13], [12, 13, 15], [], []], 8], "output": 13}] | interview |
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
|
489 | Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. The width of such a ramp is j - i.
Find the maximum width of a ramp in A. If one doesn't exist, return 0.
Example 1:
Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 a... | ["class Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n width = 0\n icandidate = [0]\n for i in range(len(A)):\n if A[i] < A[icandidate[-1]]:\n icandidate.append(i)\n for j in range(len(A) - 1, -1, -1):\n while icandidate and A[icandidate[-1... | [{"input": [[6, 0, 8, 2, 1, 5]], "output": 4}] | interview |
class Solution:
def maxWidthRamp(self, A: List[int]) -> int:
|
490 | There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j] = v opens ... | ["class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n def dfs(node, visited):\n if node in visited:\n return\n visited.add(node)\n for nei in rooms[node]:\n if nei in visited:\n continue\n ... | [{"input": [[[1], [2], [3], [], [], []]], "output": false}] | interview |
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
|
491 | Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your... | ["class Solution:\n def findSubstringInWraproundString(self, p):\n \"\"\"\n :type p: str\n :rtype: int\n \"\"\"\n pc = None\n sl = 0\n ll = {}\n \n for c in p:\n if pc and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):\n ... | [{"input": ["\"a\""], "output": 2}] | interview |
class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
|
492 | Given two integers A and B, return any string S such that:
S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters;
The substring 'aaa' does not occur in S;
The substring 'bbb' does not occur in S.
Example 1:
Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all corr... | ["class Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n if A >= 2*B:\n return 'aab'* B + 'a'* (A-2*B)\n elif A >= B:\n return 'aab' * (A-B) + 'ab' * (2*B - A)\n elif B >= 2*A:\n return 'bba' * A + 'b' *(B-2*A)\n else:\n return 'bb... | [{"input": [1, 2], "output": "bba"}] | interview |
class Solution:
def strWithout3a3b(self, A: int, B: int) -> str:
|
493 | You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], ... | ["class Solution:\n def findTargetSumWays(self, nums, S):\n \"\"\"\n :type nums: List[int]\n :type S: int\n :rtype: int\n \"\"\"\n c = [0]*1001\n c[0] = 1\n T = sum(nums)\n A = T+S\n if T<S or A&1:\n return 0\n A>>=1... | [{"input": [[1, 1, 1, 1, 1], 3], "output": 5}] | interview |
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
|
494 | Return the largest possible k such that there exists a_1, a_2, ..., a_k such that:
Each a_i is a non-empty string;
Their concatenation a_1 + a_2 + ... + a_k is equal to text;
For all 1 <= i <= k, a_i = a_{k+1 - i}.
Example 1:
Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the ... | ["class Solution:\n def longestDecomposition(self, text: str) -> int:\n n = len(text)\n splits = 0\n leftstart, leftend = 0, 0\n rightstart, rightend = n-1, n-1\n while leftend<rightstart:\n if text[leftstart:leftend+1] == text[rightstart:rightend+1]:\n le... | [{"input": ["\"ghiabcdefhelloadamhelloabcdefghi\""], "output": 9}] | interview |
class Solution:
def longestDecomposition(self, text: str) -> int:
|
495 | We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, an... | ["class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n dp = {0}\n total = sum(stones)\n for stone in stones:\n dp |= {_sum + stone for _sum in dp}\n return min(abs(total - _sum - _sum) for _sum in dp)", "class Solution:\n def lastStoneWeightII(self, sto... | [{"input": [[2, 7, 4, 1, 8, 1]], "output": 1}] | interview |
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
|
496 | Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.
Return the least number of moves to make every value in A unique.
Example 1:
Input: [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: [3,2,1,2,1,7]
Output: 6
Explanation: After ... | ["class Solution:\n def minIncrementForUnique(self, A: List[int]) -> int:\n if not A:\n return 0\n \n A.sort()\n prev = A[0]\n res = 0\n for num in A[1:]:\n if num <= prev:\n prev += 1\n res += prev-num\n\n else:... | [{"input": [[1, 2, 2]], "output": 1}] | interview |
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
|
497 | We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime , endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range.
If you choose a jo... | ["class Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n \n # max profit ending at time t\n dp = [(0,0)]\n \n task = [(startTime[i], endTime[i], profit[i]) for i in range(len(startTime))]\n task = sorted(task, key = l... | [{"input": [[1, 2, 3, 3], [3, 4, 5, 6], [50, 10, 40, 70]], "output": 120}] | interview |
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
|
498 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contac... | ["class Solution:\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n return max(self.helper(nums[1:]), self.helper(nums[:-1]))\n \n ... | [{"input": [[2, 3, 2]], "output": 3}] | interview |
class Solution:
def rob(self, nums: List[int]) -> int:
|
499 | Given an array of positive integers target and an array initial of same size with all zeros.
Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation:
Choose any subarray from initial and increment each value by one.
The answer is guaranteed to fit w... | ["class Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n prev = -1\n ans = 0\n for num in target:\n if prev == -1:\n prev = num\n ans += num\n continue\n if num > prev:\n ans += (num - prev)\n... | [{"input": [[1, 2, 3, 2, 1]], "output": 3}] | interview |
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.