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
Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13.
Note that the digit d = 1 occurs twice in the number 11.
Example 2:
>>> digitsCount(d = 3, low = 100, high = 250)
>>> 35
Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243.
"""
|
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.
Example 1:
>>> gcdOfStrings(str1 = "ABCABC", str2 = "ABC")
>>> "ABC"
Example 2:
>>> gcdOfStrings(str1 = "ABABAB", str2 = "ABAB")
>>> "AB"
Example 3:
>>> gcdOfStrings(str1 = "LEET", str2 = "CODE")
>>> ""
"""
|
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 all values equal after some number of flips.
Example 1:
>>> maxEqualRowsAfterFlips(matrix = [[0,1],[1,1]])
>>> 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
>>> maxEqualRowsAfterFlips(matrix = [[0,1],[1,0]])
>>> 2
Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
>>> maxEqualRowsAfterFlips(matrix = [[0,0,0],[0,0,1],[1,1,0]])
>>> 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.
"""
|
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] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.
Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.
Example 1:
>>> addNegabinary(arr1 = [1,1,1,1,1], arr2 = [1,0,1])
>>> [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.
Example 2:
>>> addNegabinary(arr1 = [0], arr2 = [0])
>>> [0]
Example 3:
>>> addNegabinary(arr1 = [0], arr2 = [1])
>>> [1]
"""
|
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) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.
Example 1:
>>> numSubmatrixSumTarget(matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0)
>>> 4
Explanation: The four 1x1 submatrices that only contain 0.
Example 2:
>>> numSubmatrixSumTarget(matrix = [[1,-1],[-1,1]], target = 0)
>>> 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Example 3:
>>> numSubmatrixSumTarget(matrix = [[904]], target = 0)
>>> 0
"""
|
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 each occurrence of "first second third".
Example 1:
>>> findOcurrences(text = "alice is a good girl she is a good student", first = "a", second = "good")
>>> ["girl","student"]
Example 2:
>>> findOcurrences(text = "we will we will rock you", first = "we", second = "will")
>>> ["we","rock"]
"""
|
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")
>>> 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
>>> numTilePossibilities(tiles = "AAABBC")
>>> 188
Example 3:
>>> numTilePossibilities(tiles = "V")
>>> 1
"""
|
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, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
A leaf is a node with no children.
Example 1:
>>> __init__(root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1)
>>> [1,2,3,4,null,null,7,8,9,null,14]
Example 2:
>>> __init__(root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22)
>>> [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
>>> __init__(root = [1,2,-3,-5,null,4,null], limit = -1)
>>> [1,null,-3,4]
"""
|
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 = "cbacdcbc")
>>> "acdb"
"""
|
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 those digits is 1 which is odd, so the answer is 0.
Example 2:
>>> sumOfDigits(nums = [99,77,33,66,55])
>>> 1
Explanation: The minimal element is 33, and the sum of those digits is 3 + 3 = 6 which is even, so the answer is 1.
"""
|
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, topFiveAveragej] represents the student with IDj and their top five average. Sort result by IDj in increasing order.
A student's top five average is calculated by taking the sum of their top five scores and dividing it by 5 using integer division.
Example 1:
>>> highFive(items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]])
>>> [[1,87],[2,88]]
Explanation:
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
Example 2:
>>> highFive(items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]])
>>> [[1,100],[7,100]]
"""
|
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}" represents options ["a", "b", "c"].
For example, if s = "a{b,c}", the first character is always 'a', but the second character can be 'b' or 'c'. The original list is ["ab", "ac"].
Return all words that can be formed in this manner, sorted in lexicographical order.
Example 1:
>>> expand(s = "{a,b}c{d,e}f")
>>> ["acdf","acef","bcdf","bcef"]
Example 2:
>>> expand(s = "abcd")
>>> ["abcd"]
"""
|
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 respectively.
When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid.
Note that after rotating a number, we can ignore leading zeros.
For example, after rotating 8000, we have 0008 which is considered as just 8.
Given an integer n, return the number of confusing numbers in the inclusive range [1, n].
Example 1:
>>> confusingNumberII(n = 20)
>>> 6
Explanation: The confusing numbers are [6,9,10,16,18,19].
6 converts to 9.
9 converts to 6.
10 converts to 01 which is just 1.
16 converts to 91.
18 converts to 81.
19 converts to 61.
Example 2:
>>> confusingNumberII(n = 100)
>>> 19
Explanation: The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100].
"""
|
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 array are not written. Do the above modifications to the input array in place and do not return anything.
Example 1:
>>> duplicateZeros(arr = [1,0,2,3,0,4,5,0])
>>> [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
Example 2:
>>> duplicateZeros(arr = [1,2,3])
>>> [1,2,3]
Explanation: After calling your function, the input array is modified to: [1,2,3]
"""
|
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 their values such that:
The number of items is at most numWanted.
The number of items with the same label is at most useLimit.
Return the maximum sum.
Example 1:
>>> largestValsFromLabels(values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1)
>>> 9
Explanation:
The subset chosen is the first, third, and fifth items with the sum of values 5 + 3 + 1.
Example 2:
>>> largestValsFromLabels(values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2)
>>> 12
Explanation:
The subset chosen is the first, second, and third items with the sum of values 5 + 4 + 3.
Example 3:
>>> largestValsFromLabels(values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1)
>>> 16
Explanation:
The subset chosen is the first and fourth items with the sum of values 9 + 7.
"""
|
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., (n - 1, n - 1)) such that:
All the visited cells of the path are 0.
All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
Example 1:
>>> shortestPathBinaryMatrix(grid = [[0,1],[1,0]])
>>> 2
Example 2:
>>> shortestPathBinaryMatrix(grid = [[0,0,0],[1,1,0],[1,1,0]])
>>> 4
Example 3:
>>> shortestPathBinaryMatrix(grid = [[1,0,0],[1,1,0],[1,1,0]])
>>> -1
"""
|
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 from t (possibly 0) results in the string s.
Example 1:
>>> shortestCommonSupersequence(str1 = "abac", str2 = "cab")
>>> "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
Example 2:
>>> shortestCommonSupersequence(str1 = "aaaaaaaa", str2 = "aaaaaaaa")
>>> "aaaaaaaa"
"""
|
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: The minimum element in the sample.
maximum: The maximum element in the sample.
mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.
median:
If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.
If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.
mode: The number that appears the most in the sample. It is guaranteed to be unique.
Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.
Example 1:
>>> sampleStats(count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
>>> [1.00000,3.00000,2.37500,2.50000,3.00000]
Explanation: The sample represented by count is [1,2,2,2,3,3,3,3].
The minimum and maximum are 1 and 3 respectively.
The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.
Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.
The mode is 3 as it appears the most in the sample.
Example 2:
>>> sampleStats(count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
>>> [1.00000,4.00000,2.18182,2.00000,1.00000]
Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].
The minimum and maximum are 1 and 4 respectively.
The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).
Since the size of the sample is odd, the median is the middle element 2.
The mode is 1 as it appears the most in the sample.
"""
|
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 trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.
Example 1:
>>> carPooling(trips = [[2,1,5],[3,3,7]], capacity = 4)
>>> false
Example 2:
>>> carPooling(trips = [[2,1,5],[3,3,7]], capacity = 5)
>>> true
"""
|
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 containing that word.
R("a") = {"a"}
R("w") = {"w"}
When we take a comma-delimited list of two or more expressions, we take the union of possibilities.
R("{a,b,c}") = {"a","b","c"}
R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)
When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
Formally, the three rules for our grammar:
For every lowercase letter x, we have R(x) = {x}.
For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...
For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product.
Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.
Example 1:
>>> braceExpansionII(expression = "{a,b}{c,{d,e}}")
>>> ["ac","ad","ae","bc","bd","be"]
Example 2:
>>> braceExpansionII(expression = "{{a,z},a{b,c},{ab,z}}")
>>> ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.
"""
|
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,23,1,24,75,33,54,8], k = 60)
>>> 58
Explanation: We can use 34 and 24 to sum 58 which is less than 60.
Example 2:
>>> twoSumLessThanK(nums = [10,20,30], k = 15)
>>> -1
Explanation: In this case it is not possible to get a pair sum less that 15.
"""
|
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 are: 'havef','avefu','vefun','efuno','etcod','tcode'.
Example 2:
>>> numKLenSubstrNoRepeats(s = "home", k = 5)
>>> 0
Explanation: Notice k can be larger than the length of s. In this case, it is not possible to find any substring.
"""
|
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 b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Example 1:
>>> earliestAcq(logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6)
>>> 20190301
Explanation:
The first event occurs at timestamp = 20190101, and after 0 and 1 become friends, we have the following friendship groups [0,1], [2], [3], [4], [5].
The second event occurs at timestamp = 20190104, and after 3 and 4 become friends, we have the following friendship groups [0,1], [2], [3,4], [5].
The third event occurs at timestamp = 20190107, and after 2 and 3 become friends, we have the following friendship groups [0,1], [2,3,4], [5].
The fourth event occurs at timestamp = 20190211, and after 1 and 5 become friends, we have the following friendship groups [0,1,5], [2,3,4].
The fifth event occurs at timestamp = 20190224, and as 2 and 4 are already friends, nothing happens.
The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends, we all become friends.
Example 2:
>>> earliestAcq(logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4)
>>> 3
Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends.
"""
|
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 path 8 → 4 → 5 → 9 is 4.
Example 1:
>>> maximumMinimumPath(grid = [[5,4,5],[1,2,6],[7,4,6]])
>>> 4
Explanation: The path with the maximum score is highlighted in yellow.
Example 2:
>>> maximumMinimumPath(grid = [[2,2,1,2,2,2],[1,2,2,2,1,2]])
>>> 2
Example 3:
>>> maximumMinimumPath(grid = [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]])
>>> 3
"""
|
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 back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length num_people and sum candies) that represents the final distribution of candies.
Example 1:
>>> distributeCandies(candies = 7, num_people = 4)
>>> [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].
Example 2:
>>> distributeCandies(candies = 10, num_people = 3)
>>> [5,2,3]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].
"""
|
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 labelling is right to left.
Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.
Example 1:
>>> pathInZigZagTree(label = 14)
>>> [1,3,4,14]
Example 2:
>>> pathInZigZagTree(label = 26)
>>> [1,2,6,10,26]
"""
|
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 total width shelfWidth.
We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.
Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
Example 1:
>>> minHeightShelves(books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4)
>>> 6
Explanation:
The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.
Notice that book number 2 does not have to be on the first shelf.
Example 2:
>>> minHeightShelves(books = [[1,3],[2,4],[3,2]], shelfWidth = 6)
>>> 4
"""
|
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 subExpr.
'&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.
'|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.
Given a string expression that represents a boolean expression, return the evaluation of that expression.
It is guaranteed that the given expression is valid and follows the given rules.
Example 1:
>>> parseBoolExpr(expression = "&(|(f))")
>>> false
Explanation:
First, evaluate |(f) --> f. The expression is now "&(f)".
Then, evaluate &(f) --> f. The expression is now "f".
Finally, return false.
Example 2:
>>> parseBoolExpr(expression = "|(f,f,f,t)")
>>> true
Explanation: The evaluation of (false OR false OR false OR true) is true.
Example 3:
>>> parseBoolExpr(expression = "!(&(f,t))")
>>> true
Explanation:
First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)".
Then, evaluate !(f) --> NOT false --> true. We return true.
"""
|
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:\r
>>> defangIPaddr(address = "255.100.50.0"\r)
>>> "255[.]100[.]50[.]0"\r
\r
\r
"""
|
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 reserved for each flight in the range.
Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.
Example 1:
>>> corpFlightBookings(bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5)
>>> [10,55,45,25,25]
Explanation:
Flight labels: 1 2 3 4 5
Booking 1 reserved: 10 10
Booking 2 reserved: 20 20
Booking 3 reserved: 25 25 25 25
Total seats: 10 55 45 25 25
Hence, answer = [10,55,45,25,25]
Example 2:
>>> corpFlightBookings(bookings = [[1,2,10],[2,2,15]], n = 2)
>>> [10,25]
Explanation:
Flight labels: 1 2
Booking 1 reserved: 10 10
Booking 2 reserved: 15
Total seats: 10 25
Hence, answer = [10,25]
"""
|
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 can be written as (A), where A is a VPS.\r
\r
\r
We can similarly define the nesting depth depth(S) of any VPS S as follows:\r
\r
\r
depth("") = 0\r
depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's\r
depth("(" + A + ")") = 1 + depth(A), where A is a VPS.\r
\r
\r
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.\r
\r
\r
\r
Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).\r
\r
Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.\r
\r
Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.\r
Example 1:
>>> maxDepthAfterSplit(seq = "(()())")
>>> [0,1,1,1,1,0]
Example 2:
>>> maxDepthAfterSplit(seq = "()(())()")
>>> [0,0,0,1,1,0,1,1]
"""
|
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(year = 1900, month = 2)
>>> 28
"""
|
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 subtree of that tree. Answers within 10-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
The average value of a tree is the sum of its values, divided by the number of nodes.
Example 1:
>>> __init__(root = [5,6,1])
>>> 6.00000
Explanation:
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.
Example 2:
>>> __init__(root = [0,null,1])
>>> 1.00000
"""
|
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:
>>> canDivideIntoSubsequences(nums = [1,2,2,3,3,4,4], k = 3)
>>> true
Explanation: The array can be divided into two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
Example 2:
>>> canDivideIntoSubsequences(nums = [5,6,6,7,8], k = 3)
>>> false
Explanation: There is no way to divide the array using the conditions required.
"""
|
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 appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
>>> relativeSortArray(arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6])
>>> [2,2,2,1,4,3,3,9,6,7,19]
Example 2:
>>> relativeSortArray(arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6])
>>> [22,28,8,6,17,44]
"""
|
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 its deepest leaves.
Recall that:
The node of a binary tree is a leaf if and only if it has no children
The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.
The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.
Example 1:
>>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4])
>>> [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest leaf-nodes of the tree.
Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
Example 2:
>>> __init__(root = [1])
>>> [1]
Explanation: The root is the deepest node in the tree, and it's the lca of itself.
Example 3:
>>> __init__(root = [0,1,3,null,2])
>>> [2]
Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.
"""
|
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 the number of tiring days is strictly larger than the number of non-tiring days.
Return the length of the longest well-performing interval.
Example 1:
>>> longestWPI(hours = [9,9,6,0,6,6,9])
>>> 3
Explanation: The longest well-performing interval is [9,9,6].
Example 2:
>>> longestWPI(hours = [6,6,6])
>>> 0
"""
|
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 every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.
For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].
Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.
It is guaranteed an answer exists.
Example 1:
>>> smallestSufficientTeam(req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]])
>>> [0,2]
Example 2:
>>> smallestSufficientTeam(req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]])
>>> [1,2]
"""
|
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 (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].
Example 1:
>>> numEquivDominoPairs(dominoes = [[1,2],[2,1],[3,4],[5,6]])
>>> 1
Example 2:
>>> numEquivDominoPairs(dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]])
>>> 3
"""
|
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.
You are given two arrays redEdges and blueEdges where:
redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and
blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.
Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.
Example 1:
>>> shortestAlternatingPaths(n = 3, redEdges = [[0,1],[1,2]], blueEdges = [])
>>> [0,1,-1]
Example 2:
>>> shortestAlternatingPaths(n = 3, redEdges = [[0,1]], blueEdges = [[2,1]])
>>> [0,1,-1]
"""
|
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 equal to the product of the largest leaf value in its left and right subtree, respectively.
Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
A node is a leaf if and only if it has zero children.
Example 1:
>>> mctFromLeafValues(arr = [6,2,4])
>>> 32
Explanation: There are two possible trees shown.
The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.
Example 2:
>>> mctFromLeafValues(arr = [4,11])
>>> 44
"""
|
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:
>>> maxAbsValExpr(arr1 = [1,2,3,4], arr2 = [-1,4,5,6])
>>> 13
Example 2:
>>> maxAbsValExpr(arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4])
>>> 20
"""
|
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 is 9 but it is repeated. The number 8 occurs only once, so it is the answer.
Example 2:
>>> largestUniqueNumber(nums = [9,9,8,8])
>>> -1
Explanation: There is no number that occurs only once.
"""
|
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-digit number, and 153 = 13 + 53 + 33.
Example 2:
>>> isArmstrong(n = 123)
>>> false
Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.
"""
|
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 minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1,
The cost is the sum of the connections' costs used.
Example 1:
>>> minimumCost(n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]])
>>> 6
Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2.
Example 2:
>>> minimumCost(n = 4, connections = [[1,2,3],[3,4,4]])
>>> -1
Explanation: There is no way to connect all cities even if all edges are used.
"""
|
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 prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.
In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking.
Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.
Example 1:
>>> minimumSemesters(n = 3, relations = [[1,3],[2,3]])
>>> 2
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 1 and 2.
In the second semester, you can take course 3.
Example 2:
>>> minimumSemesters(n = 3, relations = [[1,2],[2,3],[3,1]])
>>> -1
Explanation: No course can be studied because they are prerequisites of each other.
"""
|
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 = 4
Example 2:
>>> tribonacci(n = 25)
>>> 1389537
"""
|
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
\r
\r
'U' moves our position up one row, if the position exists on the board;\r
'D' moves our position down one row, if the position exists on the board;\r
'L' moves our position left one column, if the position exists on the board;\r
'R' moves our position right one column, if the position exists on the board;\r
'!' adds the character board[r][c] at our current position (r, c) to the answer.\r
\r
\r
(Here, the only positions that exist on the board are positions with letters on them.)\r
\r
Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.\r
\r
\r
Example 1:\r
>>> alphabetBoardPath(target = "leet"\r)
>>> "DDR!UURRR!!DDD!"\r
Example 2:\r
>>> alphabetBoardPath(target = "code"\r)
>>> "RR!DDRR!UUL!R!"\r
\r
\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(grid = [[1,1,1],[1,0,1],[1,1,1]]\r)
>>> 9\r
\r
\r
Example 2:\r
\r
\r
>>> largest1BorderedSquare(grid = [[1,1,0,0]]\r)
>>> 1\r
\r
\r
\r
"""
|
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 starting first.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1.
The game continues until all the stones have been taken.
Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
Example 1:
>>> stoneGameII(piles = [2,7,9,4,4])
>>> 10
Explanation:
If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 stones in total.
If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 stones in total.
So we return 10 since it's larger.
Example 2:
>>> stoneGameII(piles = [1,2,3,4,5,100])
>>> 104
"""
|
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 none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
>>> longestCommonSubsequence(text1 = "abcde", text2 = "ace")
>>> 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
>>> longestCommonSubsequence(text1 = "abc", text2 = "abc")
>>> 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
>>> longestCommonSubsequence(text1 = "abc", text2 = "def")
>>> 0
Explanation: There is no such common subsequence, so the result is 0.
"""
|
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, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...
Return the minimum number of moves to transform the given array nums into a zigzag array.
Example 1:
>>> movesToMakeZigzag(nums = [1,2,3])
>>> 2
Explanation: We can decrease 2 to 0 or 3 to 1.
Example 2:
>>> movesToMakeZigzag(nums = [9,6,1,6,2])
>>> 4
"""
|
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 given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.
Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.
Example 1:
>>> __init__(root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3)
>>> true
Explanation: The second player can choose the node with value 2.
Example 2:
>>> __init__(root = [1,2,3], n = 3, x = 1)
>>> false
"""
|
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 == text).
subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).
Return the largest possible value of k.
Example 1:
>>> longestDecomposition(text = "ghiabcdefhelloadamhelloabcdefghi")
>>> 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
Example 2:
>>> longestDecomposition(text = "merchant")
>>> 1
Explanation: We can split the string on "(merchant)".
Example 3:
>>> longestDecomposition(text = "antaprezatepzapreanta")
>>> 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".
"""
|
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 in the array.
Example 1:
>>> isMajorityElement(nums = [2,4,5,5,5,5,5,6,6], target = 5)
>>> true
Explanation: The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.
Example 2:
>>> isMajorityElement(nums = [10,100,101,101], target = 101)
>>> false
Explanation: The value 101 appears 2 times and the length of the array is 4.
Thus, 101 is not a majority element because 2 > 4/2 is false.
"""
|
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 together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.
Example 2:
>>> minSwaps(data = [0,0,0,1,0])
>>> 0
Explanation: Since there is only one 1 in the array, no swaps are needed.
Example 3:
>>> minSwaps(data = [1,0,1,0,1,0,0,1,1,0,1])
>>> 3
Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
"""
|
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 username[i] visited the website website[i] at time timestamp[i].
A pattern is a list of three websites (not necessarily distinct).
For example, ["home", "away", "love"], ["leetcode", "love", "leetcode"], and ["luffy", "luffy", "luffy"] are all patterns.
The score of a pattern is the number of users that visited all the websites in the pattern in the same order they appeared in the pattern.
For example, if the pattern is ["home", "away", "love"], the score is the number of users x such that x visited "home" then visited "away" and visited "love" after that.
Similarly, if the pattern is ["leetcode", "love", "leetcode"], the score is the number of users x such that x visited "leetcode" then visited "love" and visited "leetcode" one more time after that.
Also, if the pattern is ["luffy", "luffy", "luffy"], the score is the number of users x such that x visited "luffy" three different times at different timestamps.
Return the pattern with the largest score. If there is more than one pattern with the same largest score, return the lexicographically smallest such pattern.
Note that the websites in a pattern do not need to be visited contiguously, they only need to be visited in the order they appeared in the pattern.
Example 1:
>>> mostVisitedPattern(username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"])
>>> ["home","about","career"]
Explanation: The tuples in this example are:
["joe","home",1],["joe","about",2],["joe","career",3],["james","home",4],["james","cart",5],["james","maps",6],["james","home",7],["mary","home",8],["mary","about",9], and ["mary","career",10].
The pattern ("home", "about", "career") has score 2 (joe and mary).
The pattern ("home", "cart", "maps") has score 1 (james).
The pattern ("home", "cart", "home") has score 1 (james).
The pattern ("home", "maps", "home") has score 1 (james).
The pattern ("cart", "maps", "home") has score 1 (james).
The pattern ("home", "home", "home") has score 0 (no user visited home 3 times).
Example 2:
>>> mostVisitedPattern(username = ["ua","ua","ua","ub","ub","ub"], timestamp = [1,2,3,4,5,6], website = ["a","b","a","a","b","c"])
>>> ["a","b","a"]
"""
|
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.
Return true if and only if you can transform str1 into str2.
Example 1:
>>> canConvert(str1 = "aabcc", str2 = "ccdee")
>>> true
Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
Example 2:
>>> canConvert(str1 = "leetcode", str2 = "codeleet")
>>> false
Explanation: There is no way to transform str1 to str2.
"""
|
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:
>>> dayOfYear(date = "2019-02-10")
>>> 41
"""
|
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 answer may be too large, return it modulo 109 + 7.
Example 1:
>>> numRollsToTarget(n = 1, k = 6, target = 3)
>>> 1
Explanation: You throw one die with 6 faces.
There is only one way to get a sum of 3.
Example 2:
>>> numRollsToTarget(n = 2, k = 6, target = 7)
>>> 6
Explanation: You throw two dice, each with 6 faces.
There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
Example 3:
>>> numRollsToTarget(n = 30, k = 30, target = 500)
>>> 222616187
Explanation: The answer must be returned modulo 109 + 7.
"""
|
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 last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.
Example 2:
>>> maxRepOpt1(text = "aaabaaa")
>>> 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.
Example 3:
>>> maxRepOpt1(text = "aaaaa")
>>> 5
Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
"""
|
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:
>>> countCharacters(words = ["cat","bt","hat","tree"], chars = "atach")
>>> 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
>>> countCharacters(words = ["hello","world","leetcode"], chars = "welldonehoneyr")
>>> 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
"""
|
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 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Example 1:
>>> __init__(root = [1,7,0,7,-8,null,null])
>>> 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Example 2:
>>> __init__(root = [989,null,10250,98693,-89388,null,null,null,-32127])
>>> 2
"""
|
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.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
Example 1:
>>> maxDistance(grid = [[1,0,1],[0,0,0],[1,0,1]])
>>> 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
>>> maxDistance(grid = [[1,0,0],[0,0,0],[0,0,0]])
>>> 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
"""
|
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 "bab".
Example 2:
>>> lastSubstring(s = "leetcode")
>>> "tcode"
"""
|
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 index of the desired character. The time taken to move your finger from index i to index j is |i - j|.
You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
Example 1:
>>> calculateTime(keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba")
>>> 4
Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
Total time = 2 + 1 + 1 = 4.
Example 2:
>>> calculateTime(keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode")
>>> 73
"""
|
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 connect all the sticks until there is only one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
Example 1:
>>> connectSticks(sticks = [2,4,3])
>>> 14
Explanation: You start with sticks = [2,4,3].
1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4].
2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9].
There is only one stick left, so you are done. The total cost is 5 + 9 = 14.
Example 2:
>>> connectSticks(sticks = [1,8,3,5])
>>> 30
Explanation: You start with sticks = [1,8,3,5].
1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5].
2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8].
3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17].
There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.
Example 3:
>>> connectSticks(sticks = [5])
>>> 0
Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.
"""
|
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-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs.
Return the minimum total cost to supply water to all houses.
Example 1:
>>> minCostToSupplyWater(n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]])
>>> 3
Explanation: The image shows the costs of connecting houses using pipes.
The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.
Example 2:
>>> minCostToSupplyWater(n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]])
>>> 2
Explanation: We can supply water with cost two using one of the three options:
Option 1:
- Build a well inside house 1 with cost 1.
- Build a well inside house 2 with cost 1.
The total cost will be 2.
Option 2:
- Build a well inside house 1 with cost 1.
- Connect house 2 with house 1 with cost 1.
The total cost will be 2.
Option 3:
- Build a well inside house 2 with cost 1.
- Connect house 1 with house 2 with cost 1.
The total cost will be 2.
Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose the cheapest option.
"""
|
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 where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
Return a list of transactions that are possibly invalid. You may return the answer in any order.
Example 1:
>>> invalidTransactions(transactions = ["alice,20,800,mtv","alice,50,100,beijing"])
>>> ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
Example 2:
>>> invalidTransactions(transactions = ["alice,20,800,mtv","alice,50,1200,mtv"])
>>> ["alice,50,1200,mtv"]
Example 3:
>>> invalidTransactions(transactions = ["alice,20,800,mtv","bob,50,1200,mtv"])
>>> ["bob,50,1200,mtv"]
"""
|
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 2.
You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.
Return an integer array answer, where each answer[i] is the answer to the ith query.
Example 1:
>>> numSmallerByFrequency(queries = ["cbd"], words = ["zaaaz"])
>>> [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
>>> numSmallerByFrequency(queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"])
>>> [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
"""
|
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 there are no such sequences.\r
\r
After doing so, return the head of the final linked list. You may return any such answer.\r
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
>>> __init__(head = [1,2,-3,3,1])
>>> [3,1]
Note: The answer [1,2,1] would also be accepted.
Example 2:
>>> __init__(head = [1,2,3,-3,4])
>>> [1,2,4]
Example 3:
>>> __init__(head = [1,2,3,-3,-2])
>>> [1]
"""
|
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 the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
>>> numPrimeArrangements(n = 5)
>>> 12
Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
Example 2:
>>> numPrimeArrangements(n = 100)
>>> 682289015
"""
|
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 calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]):
If T < lower, they performed poorly on their diet and lose 1 point;
If T > upper, they performed well on their diet and gain 1 point;
Otherwise, they performed normally and there is no change in points.
Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days.
Note that the total points can be negative.
Example 1:
>>> dietPlanPerformance(calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3)
>>> 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.
Example 2:
>>> dietPlanPerformance(calories = [3,2], k = 2, lower = 0, upper = 1)
>>> 1
Explanation: Since k = 2, we consider subarrays of length 2.
calories[0] + calories[1] > upper so 1 point is gained.
Example 3:
>>> dietPlanPerformance(calories = [6,5,0,0], k = 2, lower = 1, upper = 5)
>>> 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost.
"""
|
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 substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.
Return a boolean array answer where answer[i] is the result of the ith query queries[i].
Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.
Example :
>>> canMakePaliQueries(s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]])
>>> [true,false,false,true,true]
Explanation:
queries[0]: substring = "d", is palidrome.
queries[1]: substring = "bc", is not palidrome.
queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.
Example 2:
>>> canMakePaliQueries(s = "lyb", queries = [[0,1,0],[2,2,1]])
>>> [false,true]
"""
|
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, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while
invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle).
Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].
Example 1:
>>> findNumOfValidWords(words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"])
>>> [1,1,3,2,4,0]
Explanation:
1 valid word for "aboveyz" : "aaaa"
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
Example 2:
>>> findNumOfValidWords(words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"])
>>> [0,1,3,2,0]
"""
|
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" occurs 2 times.
"a" occurs 4 times.
"b" occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.
Example 2:
>>> countLetters(s = "aaaaaaaaaa")
>>> 55
"""
|
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 phrase.
Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.
Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.
You should return a list of distinct strings sorted lexicographically.
Example 1:
>>> beforeAndAfterPuzzles(phrases = ["writing code","code rocks"])
>>> ["writing code rocks"]
Example 2:
"a quick bite to eat",
"a chip off the old block",
"chocolate bar",
"mission impossible",
"a man on a mission",
"block party",
"eat my words",
"bar of soap"]
>>> beforeAndAfterPuzzles(phrases = ["mission statement",)
>>> ["a chip off the old block party",
"a man on a mission impossible",
"a man on a mission statement",
"a quick bite to eat my words",
"chocolate bar of soap"]
Example 3:
>>> beforeAndAfterPuzzles(phrases = ["a","b","a"])
>>> ["a"]
"""
|
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 target color c. If there is no solution return -1.
Example 1:
>>> shortestDistanceColor(colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]])
>>> [3,0,3]
Explanation:
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
>>> shortestDistanceColor(colors = [1,2], queries = [[0,3]])
>>> [-1]
Explanation: There is no 3 in the array.
"""
|
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 of ones that the matrix M can have.
Example 1:
>>> maximumNumberOfOnes(width = 3, height = 3, sideLength = 2, maxOnes = 1)
>>> 4
Explanation:
In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one.
The best solution that has 4 ones is:
[1,0,1]
[0,0,0]
[1,0,1]
Example 2:
>>> maximumNumberOfOnes(width = 3, height = 3, sideLength = 2, maxOnes = 2)
>>> 6
Explanation:
[1,0,1]
[1,0,1]
[1,0,1]
"""
|
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 goes along both directions i.e. clockwise and counterclockwise.\r
\r
Return the shortest distance between the given start and destination stops.\r
\r
\r
Example 1:\r
\r
\r
\r
\r
>>> distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 1\r)
>>> 1\r
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\r
\r
\r
\r
Example 2:\r
\r
\r
\r
\r
>>> distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 2\r)
>>> 3\r
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\r
\r
\r
\r
\r
Example 3:\r
\r
\r
\r
\r
>>> distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 3\r)
>>> 4\r
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\r
\r
\r
\r
"""
|
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", "Wednesday", "Thursday", "Friday", "Saturday"}.
Example 1:
>>> dayOfTheWeek(day = 31, month = 8, year = 2019)
>>> "Saturday"
Example 2:
>>> dayOfTheWeek(day = 18, month = 7, year = 1999)
>>> "Sunday"
Example 3:
>>> dayOfTheWeek(day = 15, month = 8, year = 1993)
>>> "Sunday"
"""
|
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 and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
>>> maximumSum(arr = [1,-2,0,3])
>>> 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
>>> maximumSum(arr = [1,-2,-2,3])
>>> 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
>>> maximumSum(arr = [-1,-1,-1,-1])
>>> -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
"""
|
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 assignment arr1[i] = arr2[j].
If there is no way to make arr1 strictly increasing, return -1.
Example 1:
>>> makeArrayIncreasing(arr1 = [1,5,3,6,7], arr2 = [1,3,2,4])
>>> 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].
Example 2:
>>> makeArrayIncreasing(arr1 = [1,5,3,6,7], arr2 = [4,3,1])
>>> 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].
Example 3:
>>> makeArrayIncreasing(arr1 = [1,5,3,6,7], arr2 = [1,6,3,3])
>>> -1
Explanation: You can't make arr1 strictly increasing.
"""
|
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:
>>> maxNumberOfBalloons(text = "nlaebolko")
>>> 1
Example 2:
>>> maxNumberOfBalloons(text = "loonbalxballpoon")
>>> 2
Example 3:
>>> maxNumberOfBalloons(text = "leetcode")
>>> 0
"""
|
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:
>>> reverseParentheses(s = "(abcd)")
>>> "dcba"
Example 2:
>>> reverseParentheses(s = "(u(love)i)")
>>> "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.
Example 3:
>>> reverseParentheses(s = "(ed(et(oc))el)")
>>> "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
"""
|
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 the length of the sub-array can be 0 and its sum in that case is 0.
As the answer can be very large, return the answer modulo 109 + 7.
Example 1:
>>> kConcatenationMaxSum(arr = [1,2], k = 3)
>>> 9
Example 2:
>>> kConcatenationMaxSum(arr = [1,-2,1], k = 5)
>>> 2
Example 3:
>>> kConcatenationMaxSum(arr = [-1,-2], k = 7)
>>> 0
"""
|
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 servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:
>>> criticalConnections(n = 4, connections = [[0,1],[1,2],[2,0],[1,3]])
>>> [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2:
>>> criticalConnections(n = 2, connections = [[0,1]])
>>> [[0,1]]
"""
|
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:
>>> maxNumberOfApples(weight = [100,200,150,1000])
>>> 4
Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.
Example 2:
>>> maxNumberOfApples(weight = [900,950,800,1000,700,800])
>>> 5
Explanation: The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.
"""
|
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 direction.
Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.
Example 1:
>>> minKnightMoves(x = 2, y = 1)
>>> 1
Explanation: [0, 0] → [2, 1]
Example 2:
>>> minKnightMoves(x = 5, y = 5)
>>> 4
Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
"""
|
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,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]])
>>> 5
Example 2:
>>> smallestCommonElement(mat = [[1,2,3],[2,3,4],[2,3,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 build a block then go home. Both decisions cost some time.
The time cost of spliting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.
Output the minimum time needed to build all blocks.
Initially, there is only one worker.
Example 1:
>>> minBuildTime(blocks = [1], split = 1)
>>> 1
Explanation: We use 1 worker to build 1 block in 1 time unit.
Example 2:
>>> minBuildTime(blocks = [1,2], split = 5)
>>> 7
Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.
Example 3:
>>> minBuildTime(blocks = [1,2,3], split = 1)
>>> 4
Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
Then, use the two unassigned workers to build the first two blocks.
The cost is 1 + max(3, 1 + max(1, 2)) = 4.
"""
|
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
a < b
b - a equals to the minimum absolute difference of any two elements in arr
Example 1:
>>> minimumAbsDifference(arr = [4,2,1,3])
>>> [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
>>> minimumAbsDifference(arr = [1,3,6,10,15])
>>> [[1,3]]
Example 3:
>>> minimumAbsDifference(arr = [3,8,-10,23,19,-4,-14,27])
>>> [[-14,-10],[19,23],[23,27]]
"""
|
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 numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
Example 2:
>>> nthUglyNumber(n = 4, a = 2, b = 3, c = 4)
>>> 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.
Example 3:
>>> nthUglyNumber(n = 5, a = 2, b = 11, c = 13)
>>> 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
"""
|
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 times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
>>> smallestStringWithSwaps(s = "dcab", pairs = [[0,3],[1,2]])
>>> "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
>>> smallestStringWithSwaps(s = "dcab", pairs = [[0,3],[1,2],[0,2]])
>>> "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
>>> smallestStringWithSwaps(s = "cba", pairs = [[0,1],[1,2]])
>>> "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
"""
|
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 indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
The items that belong to the same group are next to each other in the sorted list.
There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
Return any solution if there is more than one solution and return an empty list if there is no solution.
Example 1:
>>> sortItems(n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]])
>>> [6,3,4,1,5,2,0,7]
Example 2:
>>> sortItems(n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]])
>>> []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
"""
|
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, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
>>> uniqueOccurrences(arr = [1,2])
>>> false
Example 3:
>>> uniqueOccurrences(arr = [-3,0,1,-3,1,1,1,-3,10,0])
>>> true
"""
|
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 characters).
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.
Example 1:
>>> equalSubstring(s = "abcd", t = "bcdf", maxCost = 3)
>>> 3
Explanation: "abc" of s can change to "bcd".
That costs 3, so the maximum length is 3.
Example 2:
>>> equalSubstring(s = "abcd", t = "cdef", maxCost = 3)
>>> 1
Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.
Example 3:
>>> equalSubstring(s = "abcd", t = "acde", maxCost = 0)
>>> 1
Explanation: You cannot make any change, so the maximum length is 1.
"""
|
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 removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Example 1:
>>> removeDuplicates(s = "abcd", k = 2)
>>> "abcd"
Explanation: There's nothing to delete.
Example 2:
>>> removeDuplicates(s = "deeedbbcccbdaa", k = 3)
>>> "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
>>> removeDuplicates(s = "pbbcggttciiippooaais", k = 2)
>>> "ps"
"""
|
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-2) and (n-1, n-1).
In one move the snake can:
Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).
Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).
Return the minimum number of moves to reach the target.
If there is no way to reach the target, return -1.
Example 1:
[1,1,0,0,1,0],
[0,0,0,0,1,1],
[0,0,1,0,1,0],
[0,1,1,0,0,0],
[0,1,1,0,0,0]]
>>> minimumMoves(grid = [[0,0,0,0,0,1],)
>>> 11
Explanation:
One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].
Example 2:
[0,0,0,0,1,1],
[1,1,0,0,0,1],
[1,1,1,0,0,1],
[1,1,1,0,0,1],
[1,1,1,0,0,0]]
>>> minimumMoves(grid = [[0,0,1,1,1,1],)
>>> 9
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.