task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
digit-count-in-range | def digitsCount(d: int, low: int, high: int) -> int:
"""
Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high].
Example 1:
>>> digitsCount(d = 1, low = 1, high = 13)
>>> 6
Exp... |
greatest-common-divisor-of-strings | def gcdOfStrings(str1: str, str2: str) -> str:
"""
For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
E... |
flip-columns-for-maximum-number-of-equal-rows | def maxEqualRowsAfterFlips(matrix: List[List[int]]) -> int:
"""
You are given an m x n binary matrix matrix.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).
Return the maximum number of rows that have a... |
adding-two-negabinary-numbers | def addNegabinary(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Given two numbers arr1 and arr2 in base -2, return the result of adding them together.
Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] repr... |
number-of-submatrices-that-sum-to-target | def numSubmatrixSumTarget(matrix: List[List[int]], target: int) -> int:
"""
Given a matrix and a target, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.
Two submatrices (x1, y1, x2, y2) a... |
occurrences-after-bigram | def findOcurrences(text: str, first: str, second: str) -> List[str]:
"""
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second.
Return an array of all the words third for ea... |
letter-tile-possibilities | def numTilePossibilities(tiles: str) -> int:
"""
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
>>> numTilePossibilities(tiles = "AAB")
... |
insufficient-nodes-in-root-to-leaf-paths | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sufficientSubset(root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:
"""
Given the root of a binary tree and an integer limit, del... |
smallest-subsequence-of-distinct-characters | def smallestSubsequence(s: str) -> str:
"""
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
>>> smallestSubsequence(s = "bcabc")
>>> "abc"
Example 2:
>>> smallestSubsequence(s... |
sum-of-digits-in-the-minimum-number | def sumOfDigits(nums: List[int]) -> int:
"""
Given an integer array nums, return 0 if the sum of the digits of the minimum integer in nums is odd, or 1 otherwise.
Example 1:
>>> sumOfDigits(nums = [34,23,1,24,75,33,54,8])
>>> 0
Explanation: The minimal element is 1, and the sum of thos... |
high-five | def highFive(items: List[List[int]]) -> List[List[int]]:
"""
Given a list of the scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, calculate each student's top five average.
Return the answer as an array of pairs result, where result[j] = [IDj,... |
brace-expansion | def expand(s: str) -> List[str]:
"""
You are given a string s representing a list of words. Each letter in the word has one or more options.
If there is one option, the letter is represented as is.
If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}" repre... |
confusing-number-ii | def confusingNumberII(n: int) -> int:
"""
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.
We can rotate digits of a number by 180 degrees to form new digits.
When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 ... |
duplicate-zeros | def duplicateZeros(arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
"""
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original a... |
largest-values-from-labels | def largestValsFromLabels(values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
"""
You are given n item's value and label as two integer arrays values and labels. You are also given two integers numWanted and useLimit.
Your task is to find a subset of items with the maximum sum of th... |
shortest-path-in-binary-matrix | def shortestPathBinaryMatrix(grid: List[List[int]]) -> int:
"""
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e.,... |
shortest-common-supersequence | def shortestCommonSupersequence(str1: str, str2: str) -> str:
"""
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.
A string s is a subsequence of string t if deleting some number of characters fr... |
statistics-from-a-large-sample | def sampleStats(count: List[int]) -> List[float]:
"""
You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.
Calculate the following statistics:
minimum: Th... |
car-pooling | def carPooling(trips: List[List[int]], capacity: int) -> bool:
"""
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith t... |
brace-expansion-ii | def braceExpansionII(expression: str) -> List[str]:
"""
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.
The grammar can best be understood through simple examples:
Single letters represent a singleton set ... |
two-sum-less-than-k | def twoSumLessThanK(nums: List[int], k: int) -> int:
"""
Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.
Example 1:
>>> twoSumLessThanK(nums = [34,... |
find-k-length-substrings-with-no-repeated-characters | def numKLenSubstrNoRepeats(s: str, k: int) -> int:
"""
Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.
Example 1:
>>> numKLenSubstrNoRepeats(s = "havefunonleetcode", k = 5)
>>> 6
Explanation: There are 6 substrings they a... |
the-earliest-moment-when-everyone-become-friends | def earliestAcq(logs: List[List[int]], n: int) -> int:
"""
There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with ... |
path-with-maximum-minimum-value | def maximumMinimumPath(grid: List[List[int]]) -> int:
"""
Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions.
The score of a path is the minimum value in that path.
For example, the score of the ... |
distribute-candies-to-people | def distributeCandies(candies: int, num_people: int) -> List[int]:
"""
We distribute some number of candies, to a row of n = num_people people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.
Then, we go... |
path-in-zigzag-labelled-binary-tree | def pathInZigZagTree(label: int) -> List[int]:
"""
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the ... |
filling-bookcase-shelves | def minHeightShelves(books: List[List[int]], shelfWidth: int) -> int:
"""
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.
We want to place these books in order onto bookcase shelves that have a ... |
parsing-a-boolean-expression | def parseBoolExpr(expression: str) -> bool:
"""
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:
't' that evaluates to true.
'f' that evaluates to false.
'!(subExpr)' that evaluates to the logical NOT of the inner expression... |
defanging-an-ip-address | def defangIPaddr(address: str) -> str:
"""
Given a valid (IPv4) IP address, return a defanged version of that IP address.\r
\r
A defanged IP address replaces every period "." with "[.]".\r
\r
\r
Example 1:\r
>>> defangIPaddr(address = "1.1.1.1"\r)
>>> "1[.]1[.]1[.]1"\r
Example 2... |
corporate-flight-bookings | def corpFlightBookings(bookings: List[List[int]], n: int) -> List[int]:
"""
There are n flights that are labeled from 1 to n.
You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats re... |
maximum-nesting-depth-of-two-valid-parentheses-strings | def maxDepthAfterSplit(seq: str) -> List[int]:
"""
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and:\r
\r
\r
It is the empty string, or\r
It can be written as AB (A concatenated with B), where A and B are VPS's, or\r
It ca... |
number-of-days-in-a-month | def numberOfDays(year: int, month: int) -> int:
"""
Given a year year and a month month, return the number of days of that month.
Example 1:
>>> numberOfDays(year = 1992, month = 7)
>>> 31
Example 2:
>>> numberOfDays(year = 2000, month = 2)
>>> 29
Example 3:
>>> numberOfDays... |
remove-vowels-from-a-string | def removeVowels(s: str) -> str:
"""
Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
>>> removeVowels(s = "leetcodeisacommunityforcoders")
>>> "ltcdscmmntyfrcdrs"
Example 2:
>>> removeVowels(s = "aeiou")
>... |
maximum-average-subtree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maximumAverageSubtree(root: Optional[TreeNode]) -> float:
"""
Given the root of a binary tree, return the maximum average value of a subtre... |
divide-array-into-increasing-sequences | def canDivideIntoSubsequences(nums: List[int], k: int) -> bool:
"""
Given an integer array nums sorted in non-decreasing order and an integer k, return true if this array can be divided into one or more disjoint increasing subsequences of length at least k, or false otherwise.
Example 1:
>>> c... |
relative-sort-array | def relativeSortArray(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not app... |
lowest-common-ancestor-of-deepest-leaves | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def lcaDeepestLeaves(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
Given the root of a binary tree, return the lowest common ancestor of... |
longest-well-performing-interval | def longestWPI(hours: List[int]) -> int:
"""
We are given hours, a list of the number of hours worked per day for a given employee.
A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.
A well-performing interval is an interval of days for which t... |
smallest-sufficient-team | def smallestSufficientTeam(req_skills: List[str], people: List[List[str]]) -> List[int]:
"""
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.
Consider a sufficient team: a set of people such that for ev... |
number-of-equivalent-domino-pairs | def numEquivDominoPairs(dominoes: List[List[int]]) -> int:
"""
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs... |
shortest-path-with-alternating-colors | def shortestAlternatingPaths(n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
"""
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.... |
minimum-cost-tree-from-leaf-values | def mctFromLeafValues(arr: List[int]) -> int:
"""
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.
The value of each non-leaf node is ... |
maximum-of-absolute-value-expression | def maxAbsValExpr(arr1: List[int], arr2: List[int]) -> int:
"""
Given two arrays of integers with equal lengths, return the maximum value of:\r
\r
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\r
\r
where the maximum is taken over all 0 <= i, j < arr1.length.\r
Example 1:
... |
largest-unique-number | def largestUniqueNumber(nums: List[int]) -> int:
"""
Given an integer array nums, return the largest integer that only occurs once. If no integer occurs once, return -1.
Example 1:
>>> largestUniqueNumber(nums = [5,7,3,9,4,9,8,3,1])
>>> 8
Explanation: The maximum integer in the array i... |
armstrong-number | def isArmstrong(n: int) -> bool:
"""
Given an integer n, return true if and only if it is an Armstrong number.
The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n.
Example 1:
>>> isArmstrong(n = 153)
>>> true
Explanation: 153 is a 3-digi... |
connecting-cities-with-minimum-cost | def minimumCost(n: int, connections: List[List[int]]) -> int:
"""
There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.
Return the mini... |
parallel-courses | def minimumSemesters(n: int, relations: List[List[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 course prevCourse... |
n-th-tribonacci-number | def tribonacci(n: int) -> int:
"""
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n, return the value of Tn.
Example 1:
>>> tribonacci(n = 4)
>>> 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 ... |
alphabet-board-path | def alphabetBoardPath(target: str) -> str:
"""
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].\r
\r
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.\r
\r
\r
\r
We may make the following moves:\r
... |
largest-1-bordered-square | def largest1BorderedSquare(grid: List[List[int]]) -> int:
"""
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.\r
\r
\r
Example 1:\r
\r
\r
>>> largest1BorderedSquare(... |
stone-game-ii | def stoneGameII(piles: List[int]) -> int:
"""
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice... |
longest-common-subsequence | def longestCommonSubsequence(text1: str, text2: str) -> int:
"""
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be no... |
decrease-elements-to-make-array-zigzag | def movesToMakeZigzag(nums: List[int]) -> int:
"""
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
An array A is a zigzag array if either:
Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
OR... |
binary-tree-coloring-game | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def btreeGameWinningMove(root: Optional[TreeNode], n: int, x: int) -> bool:
"""
Two players play a turn based game on a binary tree. We are giv... |
longest-chunked-palindrome-decomposition | def longestDecomposition(text: str) -> int:
"""
You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:
subtexti is a non-empty string.
The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == tex... |
check-if-a-number-is-majority-element-in-a-sorted-array | def isMajorityElement(nums: List[int], target: int) -> bool:
"""
Given an integer array nums sorted in non-decreasing order and an integer target, return true if target is a majority element, or false otherwise.
A majority element in an array nums is an element that appears more than nums.length / 2 times i... |
minimum-swaps-to-group-all-1s-together | def minSwaps(data: List[int]) -> int:
"""
Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.
Example 1:
>>> minSwaps(data = [1,0,1,0,1])
>>> 1
Explanation: There are 3 ways to group all 1's to... |
analyze-user-website-visit-pattern | def mostVisitedPattern(username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
"""
You are given two string arrays username and website and an integer array timestamp. All the given arrays are of the same length and the tuple [username[i], website[i], timestamp[i]] indicates that the user u... |
string-transforms-into-another-string | def canConvert(str1: str, str2: str) -> bool:
"""
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.
In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
... |
day-of-the-year | def dayOfYear(date: str) -> int:
"""
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
>>> dayOfYear(date = "2019-01-09")
>>> 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2... |
number-of-dice-rolls-with-target-sum | def numRollsToTarget(n: int, k: int, target: int) -> int:
"""
You have n dice, and each dice has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the ans... |
swap-for-longest-repeated-character-substring | def maxRepOpt1(text: str) -> int:
"""
You are given a string text. You can swap two of the characters in the text.
Return the length of the longest substring with repeated characters.
Example 1:
>>> maxRepOpt1(text = "ababa")
>>> 3
Explanation: We can swap the first 'b' with the la... |
find-words-that-can-be-formed-by-characters | def countCharacters(words: List[str], chars: str) -> int:
"""
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
... |
maximum-level-sum-of-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 maxLevelSum(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, the level of its root is 1, the level of its children is... |
as-far-from-land-as-possible | def maxDistance(grid: List[List[int]]) -> int:
"""
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
T... |
last-substring-in-lexicographical-order | def lastSubstring(s: str) -> str:
"""
Given a string s, return the last substring of s in lexicographical order.
Example 1:
>>> lastSubstring(s = "abab")
>>> "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "... |
single-row-keyboard | def calculateTime(keyboard: str, word: str) -> int:
"""
There is a special keyboard with all keys in a single row.
Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the... |
minimum-cost-to-connect-sticks | def connectSticks(sticks: List[int]) -> int:
"""
You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.
You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must conn... |
optimize-water-distribution-in-a-village | def minCostToSupplyWater(n: int, wells: List[int], pipes: List[List[int]]) -> int:
"""
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-... |
invalid-transactions | def invalidTransactions(transactions: List[str]) -> List[str]:
"""
A transaction is possibly invalid if:
the amount exceeds $1000, or;
if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
You are given an array of strings transaction... |
compare-strings-by-frequency-of-the-smallest-character | def numSmallerByFrequency(queries: List[str], words: List[str]) -> List[int]:
"""
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of... |
remove-zero-sum-consecutive-nodes-from-linked-list | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(head: Optional[ListNode]) -> Optional[ListNode]:
"""
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until ... |
prime-arrangements | def numPrimeArrangements(n: int) -> int:
"""
Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
Since ... |
diet-plan-performance | def dietPlanPerformance(calories: List[int], k: int, lower: int, upper: int) -> int:
"""
A dieter consumes calories[i] calories on the i-th day.
Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they look at T, the total ca... |
can-make-palindrome-from-substring | def canMakePaliQueries(s: str, queries: List[List[int]]) -> List[bool]:
"""
You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
If the... |
number-of-valid-words-for-each-puzzle | def findNumOfValidWords(words: List[str], puzzles: List[str]) -> List[int]:
"""
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:
word contains the first letter of puzzle.
For each letter in word, that letter is in puzzle.
For example, i... |
count-substrings-with-only-one-distinct-letter | def countLetters(s: str) -> int:
"""
Given a string s, return the number of substrings that have only one distinct letter.
Example 1:
>>> countLetters(s = "aaaba")
>>> 8
Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
"aaa" occurs 1 time.
"aa" oc... |
before-and-after-puzzle | def beforeAndAfterPuzzles(phrases: List[str]) -> List[str]:
"""
Given a list of phrases, generate a list of Before and After puzzles.
A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a ph... |
shortest-distance-to-target-color | def shortestDistanceColor(colors: List[int], queries: List[List[int]]) -> List[int]:
"""
You are given an array colors, in which there are three colors: 1, 2 and 3.
You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the ta... |
maximum-number-of-ones | def maximumNumberOfOnes(width: int, height: int, sideLength: int, maxOnes: int) -> int:
"""
Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.
Return the maximum possible number o... |
distance-between-bus-stops | def distanceBetweenBusStops(distance: List[int], start: int, destination: int) -> int:
"""
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.\r
\r
The bus... |
day-of-the-week | def dayOfTheWeek(day: int, month: int, year: int) -> str:
"""
Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "We... |
maximum-subarray-sum-with-one-deletion | def maximumSum(arr: List[int]) -> int:
"""
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left... |
make-array-strictly-increasing | def makeArrayIncreasing(arr1: List[int], arr2: List[int]) -> int:
"""
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the... |
maximum-number-of-balloons | def maxNumberOfBalloons(text: str) -> int:
"""
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
... |
reverse-substrings-between-each-pair-of-parentheses | def reverseParentheses(s: str) -> str:
"""
You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.
Example 1:
>>> reversePa... |
k-concatenation-maximum-sum | def kConcatenationMaxSum(arr: List[int], k: int) -> int:
"""
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... |
critical-connections-in-a-network | def criticalConnections(n: int, connections: List[List[int]]) -> List[List[int]]:
"""
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other ... |
how-many-apples-can-you-put-into-the-basket | def maxNumberOfApples(weight: List[int]) -> int:
"""
You have some apples and a basket that can carry up to 5000 units of weight.
Given an integer array weight where weight[i] is the weight of the ith apple, return the maximum number of apples you can put in the basket.
Example 1:
>>> maxN... |
minimum-knight-moves | def minKnightMoves(x: int, y: int) -> int:
"""
In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal dire... |
find-smallest-common-element-in-all-rows | def smallestCommonElement(mat: List[List[int]]) -> int:
"""
Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows.
If there is no common element, return -1.
Example 1:
>>> smallestCommonElement(mat = [[1,2,3,4,5],[2... |
minimum-time-to-build-blocks | def minBuildTime(blocks: List[int], split: int) -> int:
"""
You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.
A worker can either split into two workers (number of workers increases by one) or bui... |
minimum-absolute-difference | def minimumAbsDifference(arr: List[int]) -> List[List[int]]:
"""
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr... |
ugly-number-iii | def nthUglyNumber(n: int, a: int, b: int, c: int) -> int:
"""
An ugly number is a positive integer that is divisible by a, b, or c.
Given four integers n, a, b, and c, return the nth ugly number.
Example 1:
>>> nthUglyNumber(n = 3, a = 2, b = 3, c = 5)
>>> 4
Explanation: The ugly n... |
smallest-string-with-swaps | def smallestStringWithSwaps(s: str, pairs: List[List[int]]) -> str:
"""
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of tim... |
sort-items-by-groups-respecting-dependencies | def sortItems(n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
"""
There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero index... |
unique-number-of-occurrences | def uniqueOccurrences(arr: List[int]) -> bool:
"""
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
Example 1:
>>> uniqueOccurrences(arr = [1,2,2,1,1,3])
>>> true
Explanation: The value 1 has 3 occurrences... |
get-equal-substrings-within-budget | def equalSubstring(s: str, t: str, maxCost: int) -> int:
"""
You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the charac... |
remove-all-adjacent-duplicates-in-string-ii | def removeDuplicates(s: str, k: int) -> str:
"""
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate r... |
minimum-moves-to-reach-target-with-rotations | def minimumMoves(grid: List[List[int]]) -> int:
"""
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.