task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
cherry-pickup-ii
def cherryPickup(grid: List[List[int]]) -> int: """ You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Robot #1 is located at th...
maximum-product-of-two-elements-in-an-array
def maxProduct(nums: List[int]) -> int: """ Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: >>> maxProduct(nums = [3,4,5,2]) >>> 12 Explanation: If you choose the indices i=1 ...
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
def maxArea(h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: """ You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut a...
reorder-routes-to-make-all-paths-lead-to-the-city-zero
def minReorder(n: int, connections: List[List[int]]) -> int: """ There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction becaus...
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
def getProbability(balls: List[int]) -> float: """ Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the ...
find-all-the-lonely-nodes
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getLonelyNodes(root: Optional[TreeNode]) -> List[int]: """ In a binary tree, a lonely node is a node that is the only child of its parent n...
shuffle-the-array
def shuffle(nums: List[int], n: int) -> List[int]: """ Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\r \r Return the array in the form [x1,y1,x2,y2,...,xn,yn].\r \r  \r Example 1:\r \r \r >>> shuffle(nums = [2,5,1,3,4,7], n = 3\r) >>>...
the-k-strongest-values-in-an-array
def getStrongest(arr: List[int], k: int) -> List[int]: """ Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the centre of the array. If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger tha...
paint-house-iii
def minCost(houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: """ 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 have been painted last summer should not be painted again. A neighborhood is ...
delete-n-nodes-after-m-nodes-of-a-linked-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def deleteNodes(head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]: """ You are given the head of a linked list and two integers m and n. Traverse the linked list and ...
final-prices-with-a-special-discount-in-a-shop
def finalPrices(prices: List[int]) -> List[int]: """ You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index...
find-two-non-overlapping-sub-arrays-each-with-target-sum
def minSumOfLengths(arr: List[int], target: int) -> int: """ You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two ...
allocate-mailboxes
def minDistance(houses: List[int], k: int) -> int: """ Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated s...
running-sum-of-1d-array
def runningSum(nums: List[int]) -> List[int]: """ Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: >>> runningSum(nums = [1,2,3,4]) >>> [1,3,6,10] Explanation: Running sum is obtained as fol...
least-number-of-unique-integers-after-k-removals
def findLeastNumOfUniqueInts(arr: List[int], k: int) -> int: """ Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\r \r \r \r \r  \r Example 1:\r \r \r >>> findLeastNumOfUniqueInts(arr = [5,5,4], k = 1...
minimum-number-of-days-to-make-m-bouquets
def minDays(bloomDay: List[int], m: int, k: int) -> int: """ You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloo...
clone-binary-tree-with-random-pointer
# class Node: # def __init__(val=0, left=None, right=None, random=None): # self.val = val # self.left = left # self.right = right # self.random = random class Solution: def copyRandomBinaryTree(root: 'Optional[Node]') -> 'Optional[NodeCopy]': """ A binary tree is given s...
xor-operation-in-an-array
def xorOperation(n: int, start: int) -> int: """ You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. Example 1: >>> xorOperation(n = 5, start = 0) >>> 8...
making-file-names-unique
def getFolderNames(names: List[str]) -> List[str]: """ Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previo...
avoid-flood-in-the-city
def avoidFlood(rains: List[int]) -> List[int]: """ Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any ...
find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree
def findCriticalAndPseudoCriticalEdges(n: int, edges: List[List[int]]) -> List[List[int]]: """ Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minim...
average-salary-excluding-the-minimum-and-maximum-salary
def average(salary: List[int]) -> float: """ You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. Example 1: ...
the-kth-factor-of-n
def kthFactor(n: int, k: int) -> int: """ You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. E...
longest-subarray-of-1s-after-deleting-one-element
def longestSubarray(nums: List[int]) -> int: """ 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: >>> longestSubarray(nums = [1,1...
parallel-courses-ii
def minNumberOfSemesters(n: int, relations: List[List[int]], k: int) -> int: """ You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between cours...
path-crossing
def isPathCrossing(path: str) -> bool: """ Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at an...
check-if-array-pairs-are-divisible-by-k
def canArrange(arr: List[int], k: int) -> bool: """ Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true If you can find a way to do that or false otherwise. Example 1...
number-of-subsequences-that-satisfy-the-given-sum-condition
def numSubseq(nums: List[int], target: int) -> int: """ You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modul...
max-value-of-equation
def findMaxValueOfEquation(points: List[List[int]], k: int) -> int: """ You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maxi...
can-make-arithmetic-progression-from-sequence
def canMakeArithmeticProgression(arr: List[int]) -> bool: """ A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, ...
last-moment-before-all-ants-fall-out-of-a-plank
def getLastMoment(n: int, left: List[int], right: List[int]) -> int: """ We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different d...
count-submatrices-with-all-ones
def numSubmat(mat: List[List[int]]) -> int: """ Given an m x n binary matrix mat, return the number of submatrices that have all ones. Example 1: >>> numSubmat(mat = [[1,0,1],[1,1,0],[1,1,0]]) >>> 13 Explanation: There are 6 rectangles of side 1x1. There are 2 rectangles o...
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
def minInteger(num: str, k: int) -> str: """ You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string. Example 1: ...
reformat-date
def reformatDate(date: str) -> str: """ Given a date string in the form Day Month Year, where: Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. Year is in the range [190...
range-sum-of-sorted-subarray-sums
def rangeSum(nums: List[int], n: int, left: int, right: int) -> int: """ You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Re...
minimum-difference-between-largest-and-smallest-value-in-three-moves
def minDifference(nums: List[int]) -> int: """ You are given an integer array nums. In one move, you can choose one element of nums and change it to any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves. Example 1: ...
stone-game-iv
def winnerSquareGame(n: int) -> bool: """ Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a ...
number-of-good-pairs
def numIdenticalPairs(nums: List[int]) -> int: """ Given an array of integers nums, return the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j. Example 1: >>> numIdenticalPairs(nums = [1,2,3,1,1,3]) >>> 4 Explanation: There are 4 good pairs (0,3),...
number-of-substrings-with-only-1s
def numSub(s: str) -> int: """ Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. Example 1: >>> numSub(s = "0110111") >>> 9 Explanation: There are 9 substring in total with only 1's characters....
path-with-maximum-probability
def maxProbability(n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float: """ You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of ...
best-position-for-a-service-centre
def getMinDistSum(positions: List[List[int]]) -> float: """ A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all cust...
water-bottles
def numWaterBottles(numBottles: int, numExchange: int) -> int: """ There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. ...
number-of-nodes-in-the-sub-tree-with-the-same-label
def countSubTrees(n: int, edges: List[List[int]], labels: str) -> List[int]: """ You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is...
maximum-number-of-non-overlapping-substrings
def maxNumOfSubstrings(s: str) -> List[str]: """ Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true. ...
find-a-value-of-a-mysterious-function-closest-to-target
def closestToTarget(arr: List[int], target: int) -> int: """ Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |...
count-odd-numbers-in-an-interval-range
def countOdds(low: int, high: int) -> int: """ Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\r \r  \r Example 1:\r \r \r >>> countOdds(low = 3, high = 7\r) >>> 3\r Explanation: The odd numbers between 3 and 7 are [...
number-of-sub-arrays-with-odd-sum
def numOfSubarrays(arr: List[int]) -> int: """ Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. Example 1: >>> numOfSubarrays(arr = [1,3,5]) >>> 4 Explanation: All subarrays are [[1],[1,3],...
number-of-good-ways-to-split-a-string
def numSplits(s: str) -> int: """ You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of go...
minimum-number-of-increments-on-subarrays-to-form-a-target-array
def minNumberOperations(target: List[int]) -> int: """ You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum numb...
shuffle-string
def restoreString(s: str, indices: List[int]) -> str: """ You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Example 1: ...
minimum-suffix-flips
def minFlips(target: str) -> int: """ You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive...
number-of-good-leaf-nodes-pairs
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countPairs(root: Optional[TreeNode], distance: int) -> int: """ You are given the root of a binary tree and an integer distance. A pair of ...
string-compression-ii
def getLengthOfOptimalCompression(s: str, k: int) -> int: """ Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For...
count-good-triplets
def countGoodTriplets(arr: List[int], a: int, b: int, c: int) -> int: """ Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.\r \r A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:\r \r \r 0 <= i < j < k...
find-the-winner-of-an-array-game
def getWinner(arr: List[int], k: int) -> int: """ 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 pos...
minimum-swaps-to-arrange-a-binary-grid
def minSwaps(grid: List[List[int]]) -> int: """ 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 th...
get-the-maximum-score
def maxSum(nums1: List[int], nums2: List[int]) -> int: """ You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any ...
kth-missing-positive-number
def findKthPositive(arr: List[int], k: int) -> int: """ Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array. Example 1: >>> findKthPositive(arr = [2,3,4,7,11], k = 5) >>> 9 ...
can-convert-string-in-k-moves
def canConvertString(s: str, t: str, k: int) -> bool: """ Given two strings s and t, your goal is to convert s into t in k moves or less. During the ith (1 <= i <= k) move you can: Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, an...
minimum-insertions-to-balance-a-parentheses-string
def minInsertions(s: str) -> int: """ Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before the corresponding two co...
find-longest-awesome-substring
def longestAwesome(s: str) -> int: """ You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s. Example 1: >>> longestAwesome(s = ...
make-the-string-great
def makeGood(s: str) -> str: """ Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-v...
find-kth-bit-in-nth-binary-string
def findKthBit(n: int, k: int) -> str: """ 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) inv...
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
def maxNonOverlapping(nums: List[int], target: int) -> int: """ Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target. Example 1: >>> maxNonOverlapping(nums = [1,1,1,1,1], targ...
minimum-cost-to-cut-a-stick
def minCost(n: int, cuts: List[int]) -> int: """ Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts ...
the-most-similar-path-in-a-graph
def mostSimilar(n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]: """ We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai with city bi. Each city has a name consisting of exactly three upper-case English letters given in the string array na...
three-consecutive-odds
def threeConsecutiveOdds(arr: List[int]) -> bool: """ Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. Example 1: >>> threeConsecutiveOdds(arr = [2,6,4,1]) >>> false Explanation: There are no three consecutive odd...
minimum-operations-to-make-array-equal
def minOperations(n: int) -> int: """ 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)....
magnetic-force-between-two-balls
def maxDistance(position: List[int], m: int) -> int: """ In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls int...
minimum-number-of-days-to-eat-n-oranges
def minDays(n: int) -> int: """ 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 the...
strings-differ-by-one-character
def differByOne(dict: List[str]) -> bool: """ Given a list of strings dict where all the strings are of the same length. Return true if there are 2 strings that only differ by 1 character in the same index, otherwise return false. Example 1: >>> differByOne(dict = ["abcd","acbd", "aacd"]) ...
thousand-separator
def thousandSeparator(n: int) -> str: """ Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: >>> thousandSeparator(n = 987) >>> "987" Example 2: >>> thousandSeparator(n = 1234) >>> "1.234" """
minimum-number-of-vertices-to-reach-all-nodes
def findSmallestSetOfVertices(n: int, edges: List[List[int]]) -> List[int]: """ Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all no...
minimum-numbers-of-function-calls-to-make-target-array
def minOperations(nums: List[int]) -> int: """ You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to convert arr to nums using the minimum number of ca...
detect-cycles-in-2d-grid
def containsCycle(grid: List[List[str]]) -> bool: """ Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move t...
most-visited-sector-in-a-circular-track
def mostVisited(n: int, rounds: List[int]) -> List[int]: """ Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends a...
maximum-number-of-coins-you-can-get
def maxCoins(piles: List[int]) -> int: """ There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coi...
find-latest-group-of-size-m
def findLatestStep(arr: List[int], m: int) -> int: """ 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 posit...
stone-game-v
def stoneGameV(stoneValue: List[int]) -> int: """ There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates ...
put-boxes-into-the-warehouse-i
def maxBoxesInWarehouse(boxes: List[int], warehouse: List[int]) -> int: """ You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labelled from 0 to n - 1 from lef...
detect-pattern-of-length-m-repeated-k-or-more-times
def containsPattern(arr: List[int], m: int, k: int) -> bool: """ Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlap...
maximum-length-of-subarray-with-positive-product
def getMaxLen(nums: List[int]) -> int: """ Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray wi...
minimum-number-of-days-to-disconnect-island
def minDays(grid: List[List[int]]) -> int: """ You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said dis...
number-of-ways-to-reorder-array-to-get-same-bst
def numOfWays(nums: List[int]) -> int: """ Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constru...
matrix-diagonal-sum
def diagonalSum(mat: List[List[int]]) -> int: """ Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1:   ...
number-of-ways-to-split-a-string
def numWays(s: str) -> int: """ Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s. Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7. ...
shortest-subarray-to-be-removed-to-make-array-sorted
def findLengthOfShortestSubarray(arr: List[int]) -> int: """ Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. ...
count-all-possible-routes
def countRoutes(locations: List[int], start: int, finish: int, fuel: int) -> int: """ You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initi...
replace-all-s-to-avoid-consecutive-repeating-characters
def modifyString(s: str) -> str: """ Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guara...
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
def numTriplets(nums1: List[int], nums2: List[int]) -> int: """ Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules: Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nu...
minimum-time-to-make-rope-colorful
def minCost(colors: str, neededTime: List[int]) -> int: """ Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks B...
remove-max-number-of-edges-to-keep-graph-fully-traversable
def maxNumEdgesToRemove(n: int, edges: List[List[int]]) -> int: """ Alice and Bob have an undirected graph of n nodes and three types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both Alice and Bob. Given an array e...
put-boxes-into-the-warehouse-ii
def maxBoxesInWarehouse(boxes: List[int], warehouse: List[int]) -> int: """ You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labeled from 0 to n - 1 from left...
special-positions-in-a-binary-matrix
def numSpecial(mat: List[List[int]]) -> int: """ Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Example 1: >>> n...
count-unhappy-friends
def unhappyFriends(n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: """ You are given a list of preferences for n friends, where n is always even. For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list...
min-cost-to-connect-all-points
def minCostConnectPoints(points: List[List[int]]) -> int: """ You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where ...
check-if-string-is-transformable-with-substring-sort-operations
def isTransformable(s: str, t: str) -> bool: """ Given two strings s and t, transform string s into string t using the following operation any number of times: Choose a non-empty substring in s and sort it in place so the characters are in ascending order. For example, applying the operat...
sum-of-all-odd-length-subarrays
def sumOddLengthSubarrays(arr: List[int]) -> int: """ Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr. A subarray is a contiguous subsequence of the array. Example 1: >>> sumOddLengthSubarrays(arr = [1,4,2,5,3]) >>> 58 Explanation...
maximum-sum-obtained-of-any-permutation
def maxSumRangeQuery(nums: List[int], requests: List[List[int]]) -> int: """ We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexe...
make-sum-divisible-by-p
def minSubarray(nums: List[int], p: int) -> int: """ 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...