task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
the-k-weakest-rows-in-a-matrix
def kWeakestRows(mat: List[List[int]], k: int) -> List[int]: """ You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i i...
reduce-array-size-to-the-half
def minSetSize(arr: List[int]) -> int: """ You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. Example 1: >>> m...
maximum-product-of-splitted-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxProduct(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, split the binary tree into two subtrees by removing one e...
jump-game-v
def maxJumps(arr: List[int], d: int) -> int: """ Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j...
number-of-steps-to-reduce-a-number-to-zero
def numberOfSteps(num: int) -> int: """ Given an integer num, return the number of steps to reduce it to zero. In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. Example 1: >>> numberOfSteps(num = 14) >>> 6 Explanation...
number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold
def numOfSubarrays(arr: List[int], k: int, threshold: int) -> int: """ 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: >>> numOfSubarrays(arr = [2,2,2,2,5,5,5,8], k = 3, thresh...
angle-between-hands-of-a-clock
def angleClock(hour: int, minutes: int) -> float: """ Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct. Example 1: >>> angleClock(hour = 12, minut...
jump-game-iv
def minJumps(arr: List[int]) -> int: """ 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. Ret...
check-if-n-and-its-double-exist
def checkIfExist(arr: List[int]) -> bool: """ Given an array arr of integers, check if there exist two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: >>> checkIfExist(arr = [10,2,5,3]) >>> true Explanation: For i = 0 and ...
minimum-number-of-steps-to-make-two-strings-anagram
def minSteps(s: str, t: str) -> int: """ You are given two strings of the same length 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 char...
maximum-students-taking-exam
def maxStudents(seats: List[List[str]]) -> int: """ Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left...
count-negative-numbers-in-a-sorted-matrix
def countNegatives(grid: List[List[int]]) -> int: """ Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. Example 1: >>> countNegatives(grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]) >>> ...
maximum-number-of-events-that-can-be-attended
def maxEvents(events: List[List[int]]) -> int: """ You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return...
construct-target-array-with-multiple-sums
def isPossible(target: List[int]) -> bool: """ You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of ar...
sort-integers-by-the-number-of-1-bits
def sortByBits(arr: List[int]) -> List[int]: """ You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the arra...
number-of-substrings-containing-all-three-characters
def numberOfSubstrings(s: str) -> int: """ Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: >>> numberOfSubstrings(s = "abcabc") >>> 10 Explanation: The subst...
count-all-valid-pickup-and-delivery-options
def countOrders(n: int) -> int: """ Given n orders, each order consists of a pickup and a delivery service. 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: >>...
number-of-days-between-two-dates
def daysBetweenDates(date1: str, date2: str) -> int: """ Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. Example 1: >>> daysBetweenDates(date1 = "2019-06-29", date2 = "2019-06-30") >>> 1 ...
validate-binary-tree-nodes
def validateBinaryTreeNodes(n: int, leftChild: List[int], rightChild: List[int]) -> bool: """ 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 n...
closest-divisors
def closestDivisors(num: int) -> List[int]: """ Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order. Example 1: >>> closestDivisors(num = 8) >>> [3,3] Explanation: For num + 1 = 9, ...
largest-multiple-of-three
def largestMultipleOfThree(digits: List[int]) -> str: """ Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, retur...
how-many-numbers-are-smaller-than-the-current-number
def smallerNumbersThanCurrent(nums: List[int]) -> List[int]: """ Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array. ...
rank-teams-by-votes
def rankTeams(votes: List[str]) -> str: """ In a special ranking system, each voter gives a rank from highest to lowest to all teams participating 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...
linked-list-in-binary-tree
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def is...
minimum-cost-to-make-at-least-one-valid-path-in-a-grid
def minCost(grid: List[List[int]]) -> int: """ Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 w...
increasing-decreasing-string
def sortString(s: str) -> str: """ You are given a string s. Reorder the string using the following algorithm: Remove the smallest character from s and append it to the result. Remove the smallest character from s that is greater than the last appended character, and append it to the result. Re...
find-the-longest-substring-containing-vowels-in-even-counts
def findTheLongestSubstring(s: str) -> int: """ 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: >>> findTheLongestSubstring(s = "eleetminicoworoep") ...
longest-zigzag-path-in-a-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestZigZag(root: Optional[TreeNode]) -> int: """ You are given the root of a binary tree. A ZigZag path for a binary tree is defined...
maximum-sum-bst-in-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxSumBST(root: Optional[TreeNode]) -> int: """ Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also ...
generate-a-string-with-characters-that-have-odd-counts
def generateTheString(n: int) -> str: """ Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. Example 1...
number-of-times-binary-string-is-prefix-aligned
def numTimesAllBlue(flips: List[int]) -> int: """ You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at ...
time-needed-to-inform-all-employees
def numOfMinutes(n: int, headID: int, manager: List[int], informTime: List[int]) -> int: """ A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the d...
frog-position-after-t-seconds
def frogPosition(n: int, edges: List[List[int]], t: int, target: int) -> float: """ Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The f...
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
# class TreeNode: # def __init__(x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: """ Given two binary trees original and cloned and given a reference to a node target...
lucky-numbers-in-a-matrix
def luckyNumbers(matrix: List[List[int]]) -> List[int]: """ Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. Example 1: >>> lu...
balance-a-binary-search-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def balanceBST(root: Optional[TreeNode]) -> Optional[TreeNode]: """ Given the root of a binary search tree, return a balanced binary search tre...
maximum-performance-of-a-team
def maxPerformance(n: int, speed: List[int], efficiency: List[int], k: int) -> int: """ You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer r...
find-the-distance-value-between-two-arrays
def findTheDistanceValue(arr1: List[int], arr2: List[int], d: int) -> int: """ Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i...
cinema-seat-allocation
def maxNumberOfFamilies(n: int, reservedSeats: List[List[int]]) -> int: """ A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example,...
sort-integers-by-the-power-value
def getKth(lo: int, hi: int, k: int) -> int: """ 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 be...
pizza-with-3n-slices
def maxSizeSlices(slices: List[int]) -> int: """ 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 the next slice in the anti-clockwise direction of your pick. Your friend Bob wi...
create-target-array-in-the-given-order
def createTargetArray(nums: List[int], index: List[int]) -> List[int]: """ Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nu...
four-divisors
def sumFourDivisors(nums: List[int]) -> int: """ 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: >>> sumFourDivisors(nums = [21,4,7]) >>> 32 Explanation...
check-if-there-is-a-valid-path-in-a-grid
def hasValidPath(grid: List[List[int]]) -> bool: """ You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be: 1 which means a street connecting the left cell and the right cell. 2 which means a street connecting the upper cell and the lower cell. 3 wh...
longest-happy-prefix
def longestPrefix(s: str) -> str: """ 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: >>> longestPrefix(s = "level") ...
find-lucky-integer-in-an-array
def findLucky(arr: List[int]) -> int: """ Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1. Example 1: >>> findLucky(arr = [2,2,3,4]) ...
count-number-of-teams
def numTeams(rating: List[int]) -> int: """ 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]). ...
find-all-good-strings
def findGoodStrings(n: int, s1: str, s2: str, evil: str) -> int: """ 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 con...
count-largest-group
def countLargestGroup(n: int) -> int: """ You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. Example 1: >>> countLargestGroup(n = 13) >>> 4 Explanation: There are 9 groups in...
construct-k-palindrome-strings
def canConstruct(s: str, k: int) -> bool: """ Given a string s and an integer k, return true if you can use all the characters in s to construct non-empty k palindrome strings or false otherwise. Example 1: >>> canConstruct(s = "annabelle", k = 2) >>> true Explanation: You can construc...
circle-and-rectangle-overlapping
def checkOverlap(radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool: """ You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) ar...
reducing-dishes
def maxSatisfaction(satisfaction: List[int]) -> int: """ 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 leve...
minimum-subsequence-in-non-increasing-order
def minSubsequence(nums: List[int]) -> List[int]: """ Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still ...
number-of-steps-to-reduce-a-number-in-binary-representation-to-one
def numSteps(s: str) -> int: """ Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. ...
longest-happy-string
def longestDiverseString(a: int, b: int, c: int) -> str: """ A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. ...
stone-game-iii
def stoneGameIII(stoneValue: List[int]) -> str: """ 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 play...
string-matching-in-an-array
def stringMatching(words: List[str]) -> List[str]: """ Given an array of string words, return all strings in words that are a substring of another word. You can return the answer in any order. Example 1: >>> stringMatching(words = ["mass","as","hero","superhero"]) >>> ["as","hero"] Exp...
queries-on-a-permutation-with-key
def processQueries(queries: List[int], m: int) -> List[int]: """ Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the cu...
html-entity-parser
def entityParser(text: str) -> str: """ HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Quotation Mark: the entity is &quot; and symbol character i...
number-of-ways-to-paint-n-3-grid
def numOfWays(n: int) -> int: """ You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color...
minimum-value-to-get-positive-step-by-step-sum
def minStartValue(nums: List[int]) -> int: """ Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that t...
find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
def findMinFibonacciNumbers(k: int) -> int: """ Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is gu...
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n
def getHappyString(n: int, k: int) -> str: """ A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strin...
restore-the-array
def numberOfArrays(s: str, k: int) -> int: """ A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. ...
reformat-the-string
def reformat(s: str) -> str: """ You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two...
display-table-of-food-orders-in-a-restaurant
def displayTable(orders: List[List[str]]) -> List[List[str]]: """ Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer s...
minimum-number-of-frogs-croaking
def minNumberOfFrogs(croakOfFrogs: str) -> int: """ You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed. Return the minimum number of different frogs to finish all ...
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
def numOfArrays(n: int, m: int, k: int) -> int: """ You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers. 1 <= ar...
maximum-score-after-splitting-a-string
def maxScore(s: str) -> int: """ Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the rig...
maximum-points-you-can-obtain-from-cards
def maxScore(cardPoints: List[int], k: int) -> int: """ There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactl...
diagonal-traverse-ii
def findDiagonalOrder(nums: List[List[int]]) -> List[int]: """ Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. Example 1: >>> findDiagonalOrder(nums = [[1,2,3],[4,5,6],[7,8,9]]) >>> [1,4,2,7,5,3,8,6,9] Example 2: ...
constrained-subsequence-sum
def constrainedSubsetSum(nums: List[int], k: int) -> int: """ Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. ...
counting-elements
def countElements(arr: List[int]) -> int: """ Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately. Example 1: >>> countElements(arr = [1,2,3]) >>> 2 Explanation: 1 and 2 are counted cause...
perform-string-shifts
def stringShift(s: str, shift: List[List[int]]) -> str: """ You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [directioni, amounti]: directioni can be 0 (for left shift) or 1 (for right shift). amounti is the amount by which string s is to be shifte...
check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidSequence(root: Optional[TreeNode], arr: List[int]) -> bool: """ Given a binary tree where each path going from the root to any leaf ...
kids-with-the-greatest-number-of-candies
def kidsWithCandies(candies: List[int], extraCandies: int) -> List[bool]: """ There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return...
max-difference-you-can-get-from-changing-an-integer
def maxDiff(num: int) -> int: """ You are given an integer num. You will apply the following steps exactly two times: Pick a digit x (0 <= x <= 9). Pick another digit y (0 <= y <= 9). The digit y can be equal to x. Replace all the occurrences of x in the decimal representation of num by y. ...
check-if-a-string-can-break-another-string
def checkIfCanBreak(s1: str, s2: str) -> bool: """ 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 or vice-versa. A string x can break string y (both of size n) if x[i] >= y[i] (in a...
number-of-ways-to-wear-different-hats-to-each-other
def numberWays(hats: List[List[int]]) -> int: """ There are n people and 40 types of hats labeled from 1 to 40. Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. Return the number of ways that n people can wear different hats from each other. Since the a...
destination-city
def destCity(paths: List[List[str]]) -> str: """ You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths f...
check-if-all-1s-are-at-least-length-k-places-away
def kLengthApart(nums: List[int], k: int) -> bool: """ Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false. Example 1: >>> kLengthApart(nums = [1,0,0,0,1,0,0,1], k = 2) >>> true Explanation: Each of...
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit
def longestSubarray(nums: List[int], limit: int) -> int: """ Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit. Example 1: >>> longes...
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
def kthSmallest(mat: List[List[int]], k: int) -> int: """ You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k. You are allowed to choose exactly one element from each row to form an array. Return the kth smallest array sum among all possible arrays. ...
build-an-array-with-stack-operations
def buildArray(target: List[int], n: int) -> List[str]: """ You are given an integer array target and an integer n. You have an empty stack with the two following operations: "Push": pushes an integer to the top of the stack. "Pop": removes the integer on the top of the stack. You also...
count-triplets-that-can-form-two-arrays-of-equal-xor
def countTriplets(arr: List[int]) -> int: """ 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 tha...
number-of-ways-of-cutting-a-pizza
def ways(pizza: List[str], k: int) -> int: """ Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. For each cut you choose the direction: vertic...
consecutive-characters
def maxPower(s: str) -> int: """ The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return the power of s. Example 1: >>> maxPower(s = "leetcode") >>> 2 Explanation: The substring "ee" is of length 2 wit...
simplified-fractions
def simplifiedFractions(n: int) -> List[str]: """ Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. Example 1: >>> simplifiedFractions(n = 2) >>> ["1/2"] ...
count-good-nodes-in-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def goodNodes(root: Optional[TreeNode]) -> int: """ Given a binary tree root, a node X in the tree is named good if in the path from root to X ...
form-largest-integer-with-digits-that-add-up-to-target
def largestNumber(cost: List[int], target: int) -> str: """ Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. ...
number-of-students-doing-homework-at-a-given-time
def busyStudent(startTime: List[int], endTime: List[int], queryTime: int) -> int: """ Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doi...
rearrange-words-in-a-sentence
def arrangeWords(text: str) -> str: """ Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rea...
people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list
def peopleIndexes(favoriteCompanies: List[List[str]]) -> List[int]: """ Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favo...
maximum-number-of-darts-inside-of-a-circular-dartboard
def numPoints(darts: List[List[int]], r: int) -> int: """ Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of ...
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence
def isPrefixOfWord(sentence: str, searchWord: str) -> int: """ Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. ...
maximum-number-of-vowels-in-a-substring-of-given-length
def maxVowels(s: str, k: int) -> int: """ Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. Example 1: >>> maxVowels(s = "abciiidef", k = 3) >>> 3 Explanation:...
max-dot-product-of-two-subsequences
def maxDotProduct(nums1: List[int], nums2: List[int]) -> int: """ Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can...
make-two-arrays-equal-by-reversing-subarrays
def canBeEqual(target: List[int], arr: List[int]) -> bool: """ You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target or false othe...
check-if-a-string-contains-all-binary-codes-of-size-k
def hasAllCodes(s: str, k: int) -> bool: """ Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. Example 1: >>> hasAllCodes(s = "00110110", k = 2) >>> true Explanation: The binary codes of length 2 are "00...
course-schedule-iv
def checkIfPrerequisite(numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: """ There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take co...