task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
number-of-corner-rectangles | def countCornerRectangles(grid: List[List[int]]) -> int:
"""
Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles.
A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1's used must be distinct.
Example 1:
>>> countCornerRectangles(grid = [[1,0,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[1,0,1,0,1]])
>>> 1
Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
Example 2:
>>> countCornerRectangles(grid = [[1,1,1],[1,1,1],[1,1,1]])
>>> 9
Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
Example 3:
>>> countCornerRectangles(grid = [[1,1,1,1]])
>>> 0
Explanation: Rectangles must have four distinct corners.
"""
|
ip-to-cidr | def ipToCIDR(ip: str, n: int) -> List[str]:
"""
An IP address is a formatted 32-bit unsigned integer where each group of 8 bits is printed as a decimal number and the dot character '.' splits the groups.
For example, the binary number 00001111 10001000 11111111 01101011 (spaces added for clarity) formatted as an IP address would be "15.136.255.107".
A CIDR block is a format used to denote a specific set of IP addresses. It is a string consisting of a base IP address, followed by a slash, followed by a prefix length k. The addresses it covers are all the IPs whose first k bits are the same as the base IP address.
For example, "123.45.67.89/20" is a CIDR block with a prefix length of 20. Any IP address whose binary representation matches 01111011 00101101 0100xxxx xxxxxxxx, where x can be either 0 or 1, is in the set covered by the CIDR block.
You are given a start IP address ip and the number of IP addresses we need to cover n. Your goal is to use as few CIDR blocks as possible to cover all the IP addresses in the inclusive range [ip, ip + n - 1] exactly. No other IP addresses outside of the range should be covered.
Return the shortest list of CIDR blocks that covers the range of IP addresses. If there are multiple answers, return any of them.
Example 1:
>>> ipToCIDR(ip = "255.0.0.7", n = 10)
>>> ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
Explanation:
The IP addresses that need to be covered are:
- 255.0.0.7 -> 11111111 00000000 00000000 00000111
- 255.0.0.8 -> 11111111 00000000 00000000 00001000
- 255.0.0.9 -> 11111111 00000000 00000000 00001001
- 255.0.0.10 -> 11111111 00000000 00000000 00001010
- 255.0.0.11 -> 11111111 00000000 00000000 00001011
- 255.0.0.12 -> 11111111 00000000 00000000 00001100
- 255.0.0.13 -> 11111111 00000000 00000000 00001101
- 255.0.0.14 -> 11111111 00000000 00000000 00001110
- 255.0.0.15 -> 11111111 00000000 00000000 00001111
- 255.0.0.16 -> 11111111 00000000 00000000 00010000
The CIDR block "255.0.0.7/32" covers the first address.
The CIDR block "255.0.0.8/29" covers the middle 8 addresses (binary format of 11111111 00000000 00000000 00001xxx).
The CIDR block "255.0.0.16/32" covers the last address.
Note that while the CIDR block "255.0.0.0/28" does cover all the addresses, it also includes addresses outside of the range, so we cannot use it.
Example 2:
>>> ipToCIDR(ip = "117.145.102.62", n = 8)
>>> ["117.145.102.62/31","117.145.102.64/30","117.145.102.68/31"]
"""
|
open-the-lock | def openLock(deadends: List[str], target: str) -> int:
"""
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
Example 1:
>>> openLock(deadends = ["0201","0101","0102","1212","2002"], target = "0202")
>>> 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".
Example 2:
>>> openLock(deadends = ["8888"], target = "0009")
>>> 1
Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
Example 3:
>>> openLock(deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888")
>>> -1
Explanation: We cannot reach the target without getting stuck.
"""
|
cracking-the-safe | def crackSafe(n: int, k: int) -> str:
"""
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.
For example, the correct password is "345" and you enter in "012345":
After typing 0, the most recent 3 digits is "0", which is incorrect.
After typing 1, the most recent 3 digits is "01", which is incorrect.
After typing 2, the most recent 3 digits is "012", which is incorrect.
After typing 3, the most recent 3 digits is "123", which is incorrect.
After typing 4, the most recent 3 digits is "234", which is incorrect.
After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks.
Return any string of minimum length that will unlock the safe at some point of entering it.
Example 1:
>>> crackSafe(n = 1, k = 2)
>>> "10"
Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.
Example 2:
>>> crackSafe(n = 2, k = 2)
>>> "01100"
Explanation: For each possible password:
- "00" is typed in starting from the 4th digit.
- "01" is typed in starting from the 1st digit.
- "10" is typed in starting from the 3rd digit.
- "11" is typed in starting from the 2nd digit.
Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.
"""
|
reach-a-number | def reachNumber(target: int) -> int:
"""
You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
On each move, you can either go left or right.
During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.
Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.
Example 1:
>>> reachNumber(target = 2)
>>> 3
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
Example 2:
>>> reachNumber(target = 3)
>>> 2
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
"""
|
pour-water | def pourWater(heights: List[int], volume: int, k: int) -> List[int]:
"""
You are given an elevation map represents as an integer array heights where heights[i] representing the height of the terrain at index i. The width at each index is 1. You are also given two integers volume and k. volume units of water will fall at index k.
Water first drops at the index k and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules:
If the droplet would eventually fall by moving left, then move left.
Otherwise, if the droplet would eventually fall by moving right, then move right.
Otherwise, rise to its current position.
Here, "eventually fall" means that the droplet will eventually be at a lower level if it moves in that direction. Also, level means the height of the terrain plus any water in that column.
We can assume there is infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than one grid block, and each unit of water has to be in exactly one block.
Example 1:
>>> pourWater(heights = [2,1,1,2,1,2,2], volume = 4, k = 3)
>>> [2,2,2,3,2,2,2]
Explanation:
The first drop of water lands at index k = 3. When moving left or right, the water can only move to the same level or a lower level. (By level, we mean the total height of the terrain plus any water in that column.)
Since moving left will eventually make it fall, it moves left. (A droplet "made to fall" means go to a lower height than it was at previously.) Since moving left will not make it fall, it stays in place.
The next droplet falls at index k = 3. Since the new droplet moving left will eventually make it fall, it moves left. Notice that the droplet still preferred to move left, even though it could move right (and moving right makes it fall quicker.)
The third droplet falls at index k = 3. Since moving left would not eventually make it fall, it tries to move right. Since moving right would eventually make it fall, it moves right.
Finally, the fourth droplet falls at index k = 3. Since moving left would not eventually make it fall, it tries to move right. Since moving right would not eventually make it fall, it stays in place.
Example 2:
>>> pourWater(heights = [1,2,3,4], volume = 2, k = 2)
>>> [2,3,3,4]
Explanation: The last droplet settles at index 1, since moving further left would not cause it to eventually fall to a lower height.
Example 3:
>>> pourWater(heights = [3,1,3], volume = 5, k = 1)
>>> [4,4,4]
"""
|
pyramid-transition-matrix | def pyramidTransition(bottom: str, allowed: List[str]) -> bool:
"""
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom.
You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.
Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.
Example 1:
>>> pyramidTransition(bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"])
>>> true
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.
There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed.
Example 2:
>>> pyramidTransition(bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"])
>>> false
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
"""
|
set-intersection-size-at-least-two | def intersectionSizeTwo(intervals: List[List[int]]) -> int:
"""
You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets.
Return the minimum possible size of a containing set.
Example 1:
>>> intersectionSizeTwo(intervals = [[1,3],[3,7],[8,9]])
>>> 5
Explanation: let nums = [2, 3, 4, 8, 9].
It can be shown that there cannot be any containing array of size 4.
Example 2:
>>> intersectionSizeTwo(intervals = [[1,3],[1,4],[2,5],[3,5]])
>>> 3
Explanation: let nums = [2, 3, 4].
It can be shown that there cannot be any containing array of size 2.
Example 3:
>>> intersectionSizeTwo(intervals = [[1,2],[2,3],[2,4],[4,5]])
>>> 5
Explanation: let nums = [1, 2, 3, 4, 5].
It can be shown that there cannot be any containing array of size 4.
"""
|
bold-words-in-string | def boldWords(words: List[str], s: str) -> str:
"""
Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between and tags become bold.
Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should form a valid combination.
Example 1:
>>> boldWords(words = ["ab","bc"], s = "aabcd")
>>> "aabcd"
Explanation: Note that returning "aabcd" would use more tags, so it is incorrect.
Example 2:
>>> boldWords(words = ["ab","cb"], s = "aabcd")
>>> "aabcd"
"""
|
find-anagram-mappings | def anagramMappings(nums1: List[int], nums2: List[int]) -> List[int]:
"""
You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both arrays may contain duplicates.
Return an index mapping array mapping from nums1 to nums2 where mapping[i] = j means the ith element in nums1 appears in nums2 at index j. If there are multiple answers, return any of them.
An array a is an anagram of an array b means b is made by randomizing the order of the elements in a.
Example 1:
>>> anagramMappings(nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28])
>>> [1,4,3,2,0]
Explanation: As mapping[0] = 1 because the 0th element of nums1 appears at nums2[1], and mapping[1] = 4 because the 1st element of nums1 appears at nums2[4], and so on.
Example 2:
>>> anagramMappings(nums1 = [84,46], nums2 = [84,46])
>>> [0,1]
"""
|
special-binary-string | def makeLargestSpecial(s: str) -> str:
"""
Special binary strings are binary strings with the following two properties:
The number of 0's is equal to the number of 1's.
Every prefix of the binary string has at least as many 1's as 0's.
You are given a special binary string s.
A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
Example 1:
>>> makeLargestSpecial(s = "11011000")
>>> "11100100"
Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped.
This is the lexicographically largest string possible after some number of swaps.
Example 2:
>>> makeLargestSpecial(s = "10")
>>> "10"
"""
|
prime-number-of-set-bits-in-binary-representation | def countPrimeSetBits(left: int, right: int) -> int:
"""
Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1's present when written in binary.
For example, 21 written in binary is 10101, which has 3 set bits.
Example 1:
>>> countPrimeSetBits(left = 6, right = 10)
>>> 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
8 -> 1000 (1 set bit, 1 is not prime)
9 -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.
Example 2:
>>> countPrimeSetBits(left = 10, right = 15)
>>> 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.
"""
|
partition-labels | def partitionLabels(s: str) -> List[int]:
"""
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc" can be partitioned into ["abab", "cc"], but partitions such as ["aba", "bcc"] or ["ab", "ab", "cc"] are invalid.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
Example 1:
>>> partitionLabels(s = "ababcbacadefegdehijhklij")
>>> [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
>>> partitionLabels(s = "eccbbbbdec")
>>> [10]
"""
|
largest-plus-sign | def orderOfLargestPlusSign(n: int, mines: List[List[int]]) -> int:
"""
You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.
An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.
Example 1:
>>> orderOfLargestPlusSign(n = 5, mines = [[4,2]])
>>> 2
Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.
Example 2:
>>> orderOfLargestPlusSign(n = 1, mines = [[0,0]])
>>> 0
Explanation: There is no plus sign, so return 0.
"""
|
couples-holding-hands | def minSwapsCouples(row: List[int]) -> int:
"""
There are n couples sitting in 2n seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).
Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
Example 1:
>>> minSwapsCouples(row = [0,2,1,3])
>>> 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:
>>> minSwapsCouples(row = [3,2,0,1])
>>> 0
Explanation: All couples are already seated side by side.
"""
|
toeplitz-matrix | def isToeplitzMatrix(matrix: List[List[int]]) -> bool:
"""
Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
>>> isToeplitzMatrix(matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]])
>>> true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
>>> isToeplitzMatrix(matrix = [[1,2],[2,2]])
>>> false
Explanation:
The diagonal "[1, 2]" has different elements.
"""
|
reorganize-string | def reorganizeString(s: str) -> str:
"""
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
>>> reorganizeString(s = "aab")
>>> "aba"
Example 2:
>>> reorganizeString(s = "aaab")
>>> ""
"""
|
max-chunks-to-make-sorted-ii | def maxChunksToSorted(arr: List[int]) -> int:
"""
You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
>>> maxChunksToSorted(arr = [5,4,3,2,1])
>>> 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
>>> maxChunksToSorted(arr = [2,1,3,4,4])
>>> 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
"""
|
max-chunks-to-make-sorted | def maxChunksToSorted(arr: List[int]) -> int:
"""
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
>>> maxChunksToSorted(arr = [4,3,2,1,0])
>>> 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2:
>>> maxChunksToSorted(arr = [1,0,2,3,4])
>>> 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
"""
|
basic-calculator-iv | def basicCalculatorIV(expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:
"""
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
An expression alternates chunks and symbols, with a space separating each chunk and symbol.
A chunk is either an expression in parentheses, a variable, or a non-negative integer.
A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
For example, expression = "1 + 2 * 3" has an answer of ["7"].
The format of the output is as follows:
For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
For example, we would never write a term like "b*a*c", only "a*b*c".
Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
For example, "a*a*b*c" has degree 4.
The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
Terms (including constant terms) with coefficient 0 are not included.
For example, an expression of "0" has an output of [].
Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Example 1:
>>> basicCalculatorIV(expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1])
>>> ["-1*a","14"]
Example 2:
>>> basicCalculatorIV(expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12])
>>> ["-1*pressure","5"]
Example 3:
>>> basicCalculatorIV(expression = "(e + 8) * (e - 8)", evalvars = [], evalints = [])
>>> ["1*e*e","-64"]
"""
|
jewels-and-stones | def numJewelsInStones(jewels: str, stones: str) -> int:
"""
You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
>>> numJewelsInStones(jewels = "aA", stones = "aAAbbbb")
>>> 3
Example 2:
>>> numJewelsInStones(jewels = "z", stones = "ZZ")
>>> 0
"""
|
basic-calculator-iii | def calculate(s: str) -> int:
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
>>> calculate(s = "1+1")
>>> 2
Example 2:
>>> calculate(s = "6-4/2")
>>> 4
Example 3:
>>> calculate(s = "2*(5+5*2)/3+(6/2+8)")
>>> 21
"""
|
sliding-puzzle | def slidingPuzzle(board: List[List[int]]) -> int:
"""
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Example 1:
>>> slidingPuzzle(board = [[1,2,3],[4,0,5]])
>>> 1
Explanation: Swap the 0 and the 5 in one move.
Example 2:
>>> slidingPuzzle(board = [[1,2,3],[5,4,0]])
>>> -1
Explanation: No number of moves will make the board solved.
Example 3:
>>> slidingPuzzle(board = [[4,1,2],[5,0,3]])
>>> 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
"""
|
minimize-max-distance-to-gas-station | def minmaxGasDist(stations: List[int], k: int) -> float:
"""
You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.
You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.
Let penalty() be the maximum distance between adjacent gas stations after adding the k new stations.
Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer will be accepted.
Example 1:
>>> minmaxGasDist(stations = [1,2,3,4,5,6,7,8,9,10], k = 9)
>>> 0.50000
Example 2:
>>> minmaxGasDist(stations = [23,24,36,39,46,56,57,65,84,98], k = 1)
>>> 14.00000
"""
|
global-and-local-inversions | def isIdealPermutation(nums: List[int]) -> bool:
"""
You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i where:
0 <= i < n - 1
nums[i] > nums[i + 1]
Return true if the number of global inversions is equal to the number of local inversions.
Example 1:
>>> isIdealPermutation(nums = [1,0,2])
>>> true
Explanation: There is 1 global inversion and 1 local inversion.
Example 2:
>>> isIdealPermutation(nums = [1,2,0])
>>> false
Explanation: There are 2 global inversions and 1 local inversion.
"""
|
swap-adjacent-in-lr-string | def canTransform(start: str, result: str) -> bool:
"""
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string result, return True if and only if there exists a sequence of moves to transform start to result.
Example 1:
>>> canTransform(start = "RXXLRXRXL", result = "XRLXXRRLX")
>>> true
Explanation: We can transform start to result following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Example 2:
>>> canTransform(start = "X", result = "L")
>>> false
"""
|
swim-in-rising-water | def swimInWater(grid: List[List[int]]) -> int:
"""
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).
Example 1:
>>> swimInWater(grid = [[0,2],[1,3]])
>>> 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
Example 2:
>>> swimInWater(grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]])
>>> 16
Explanation: The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
"""
|
k-th-symbol-in-grammar | def kthGrammar(n: int, k: int) -> int:
"""
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Example 1:
>>> kthGrammar(n = 1, k = 1)
>>> 0
Explanation: row 1: 0
Example 2:
>>> kthGrammar(n = 2, k = 1)
>>> 0
Explanation:
row 1: 0
row 2: 01
Example 3:
>>> kthGrammar(n = 2, k = 2)
>>> 1
Explanation:
row 1: 0
row 2: 01
"""
|
reaching-points | def reachingPoints(sx: int, sy: int, tx: int, ty: int) -> bool:
"""
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.
The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example 1:
>>> reachingPoints(sx = 1, sy = 1, tx = 3, ty = 5)
>>> true
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Example 2:
>>> reachingPoints(sx = 1, sy = 1, tx = 2, ty = 2)
>>> false
Example 3:
>>> reachingPoints(sx = 1, sy = 1, tx = 1, ty = 1)
>>> true
"""
|
rabbits-in-forest | def numRabbits(answers: List[int]) -> int:
"""
There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
>>> numRabbits(answers = [1,1,2])
>>> 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
>>> numRabbits(answers = [10,10,10])
>>> 11
"""
|
transform-to-chessboard | def movesToChessboard(board: List[List[int]]) -> int:
"""
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
>>> movesToChessboard(board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]])
>>> 2
Explanation: One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
Example 2:
>>> movesToChessboard(board = [[0,1],[1,0]])
>>> 0
Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
>>> movesToChessboard(board = [[1,0],[1,0]])
>>> -1
Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
"""
|
minimum-distance-between-bst-nodes | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(root: Optional[TreeNode]) -> int:
"""
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
>>> __init__(root = [4,2,6,1,3])
>>> 1
Example 2:
>>> __init__(root = [1,0,48,null,null,12,49])
>>> 1
"""
|
letter-case-permutation | def letterCasePermutation(s: str) -> List[str]:
"""
Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example 1:
>>> letterCasePermutation(s = "a1b2")
>>> ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
>>> letterCasePermutation(s = "3z4")
>>> ["3z4","3Z4"]
"""
|
is-graph-bipartite | def isBipartite(graph: List[List[int]]) -> bool:
"""
There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Example 1:
>>> isBipartite(graph = [[1,2,3],[0,2],[0,1,3],[0,2]])
>>> false
Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
>>> isBipartite(graph = [[1,3],[0,2],[1,3],[0,2]])
>>> true
Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
"""
|
k-th-smallest-prime-fraction | def kthSmallestPrimeFraction(arr: List[int], k: int) -> List[int]:
"""
You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
Example 1:
>>> kthSmallestPrimeFraction(arr = [1,2,3,5], k = 3)
>>> [2,5]
Explanation: The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
The third fraction is 2/5.
Example 2:
>>> kthSmallestPrimeFraction(arr = [1,7], k = 1)
>>> [1,7]
"""
|
cheapest-flights-within-k-stops | def findCheapestPrice(n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
"""
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
>>> findCheapestPrice(n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1)
>>> 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
>>> findCheapestPrice(n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1)
>>> 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
>>> findCheapestPrice(n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0)
>>> 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
"""
|
rotated-digits | def rotatedDigits(n: int) -> int:
"""
An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
0, 1, and 8 rotate to themselves,
2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),
6 and 9 rotate to each other, and
the rest of the numbers do not rotate to any other number and become invalid.
Given an integer n, return the number of good integers in the range [1, n].
Example 1:
>>> rotatedDigits(n = 10)
>>> 4
Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
Example 2:
>>> rotatedDigits(n = 1)
>>> 0
Example 3:
>>> rotatedDigits(n = 2)
>>> 1
"""
|
escape-the-ghosts | def escapeGhosts(ghosts: List[List[int]], target: List[int]) -> bool:
"""
You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.
Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.
You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.
Return true if it is possible to escape regardless of how the ghosts move, otherwise return false.
Example 1:
>>> escapeGhosts(ghosts = [[1,0],[0,3]], target = [0,1])
>>> true
Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.
Example 2:
>>> escapeGhosts(ghosts = [[1,0]], target = [2,0])
>>> false
Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
Example 3:
>>> escapeGhosts(ghosts = [[2,0]], target = [1,0])
>>> false
Explanation: The ghost can reach the target at the same time as you.
"""
|
domino-and-tromino-tiling | def numTilings(n: int) -> int:
"""
You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
>>> numTilings(n = 3)
>>> 5
Explanation: The five different ways are show above.
Example 2:
>>> numTilings(n = 1)
>>> 1
"""
|
custom-sort-string | def customSortString(order: str, s: str) -> str:
"""
You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
>>> customSortString(order = "cba", s = "abcd")
>>> "cbad"
Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
>>> customSortString(order = "bcafg", s = "abcd")
>>> "bcad"
Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "dbca" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.
"""
|
number-of-matching-subsequences | def numMatchingSubseq(s: str, words: List[str]) -> int:
"""
Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
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".
Example 1:
>>> numMatchingSubseq(s = "abcde", words = ["a","bb","acd","ace"])
>>> 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Example 2:
>>> numMatchingSubseq(s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"])
>>> 2
"""
|
preimage-size-of-factorial-zeroes-function | def preimageSizeFZF(k: int) -> int:
"""
Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
Example 1:
>>> preimageSizeFZF(k = 0)
>>> 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
Example 2:
>>> preimageSizeFZF(k = 5)
>>> 0
Explanation: There is no x such that x! ends in k = 5 zeroes.
Example 3:
>>> preimageSizeFZF(k = 3)
>>> 5
"""
|
valid-tic-tac-toe-state | def validTicTacToe(board: List[str]) -> bool:
"""
Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares ' '.
The first player always places 'X' characters, while the second player always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
>>> validTicTacToe(board = ["O "," "," "])
>>> false
Explanation: The first player always plays "X".
Example 2:
>>> validTicTacToe(board = ["XOX"," X "," "])
>>> false
Explanation: Players take turns making moves.
Example 3:
>>> validTicTacToe(board = ["XOX","O O","XOX"])
>>> true
"""
|
number-of-subarrays-with-bounded-maximum | def numSubarrayBoundedMax(nums: List[int], left: int, right: int) -> int:
"""
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
>>> numSubarrayBoundedMax(nums = [2,1,4,3], left = 2, right = 3)
>>> 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Example 2:
>>> numSubarrayBoundedMax(nums = [2,9,2,5,6], left = 2, right = 8)
>>> 7
"""
|
rotate-string | def rotateString(s: str, goal: str) -> bool:
"""
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:
>>> rotateString(s = "abcde", goal = "cdeab")
>>> true
Example 2:
>>> rotateString(s = "abcde", goal = "abced")
>>> false
"""
|
all-paths-from-source-to-target | def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]:
"""
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:
>>> allPathsSourceTarget(graph = [[1,2],[3],[3],[]])
>>> [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Example 2:
>>> allPathsSourceTarget(graph = [[4,3,1],[3,2,4],[3],[4],[]])
>>> [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
"""
|
smallest-rotation-with-highest-score | def bestRotation(nums: List[int]) -> int:
"""
You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Example 1:
>>> bestRotation(nums = [2,3,1,4,0])
>>> 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
>>> bestRotation(nums = [1,3,0,2,4])
>>> 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
"""
|
champagne-tower | def champagneTower(poured: int, query_row: int, query_glass: int) -> float:
"""
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.\r
\r
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)\r
\r
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\r
\r
\r
\r
Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)\r
\r
\r
Example 1:\r
\r
\r
>>> champagneTower(poured = 1, query_row = 1, query_glass = 1\r)
>>> 0.00000\r
Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\r
\r
\r
Example 2:\r
\r
\r
>>> champagneTower(poured = 2, query_row = 1, query_glass = 1\r)
>>> 0.50000\r
Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\r
\r
\r
Example 3:\r
\r
\r
>>> champagneTower(poured = 100000009, query_row = 33, query_glass = 17\r)
>>> 1.00000\r
\r
\r
\r
"""
|
similar-rgb-color | def similarRGB(color: str) -> str:
"""
The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.
For example, "#15c" is shorthand for the color "#1155cc".
The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2.
Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given color and has a shorthand (i.e., it can be represented as some "#XYZ").
Any answer which has the same highest similarity as the best answer will be accepted.
Example 1:
>>> similarRGB(color = "#09f166")
>>> "#11ee66"
Explanation:
The similarity is -(0x09 - 0x11)2 -(0xf1 - 0xee)2 - (0x66 - 0x66)2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.
Example 2:
>>> similarRGB(color = "#4e3fe1")
>>> "#5544dd"
"""
|
minimum-swaps-to-make-sequences-increasing | def minSwap(nums1: List[int], nums2: List[int]) -> int:
"""
You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].
For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.
An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
Example 1:
>>> minSwap(nums1 = [1,3,5,4], nums2 = [1,2,3,7])
>>> 1
Explanation:
Swap nums1[3] and nums2[3]. Then the sequences are:
nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
which are both strictly increasing.
Example 2:
>>> minSwap(nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9])
>>> 1
"""
|
find-eventual-safe-states | def eventualSafeNodes(graph: List[List[int]]) -> List[int]:
"""
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
>>> eventualSafeNodes(graph = [[1,2],[2,3],[5],[0],[5],[],[]])
>>> [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2:
>>> eventualSafeNodes(graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]])
>>> [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
"""
|
bricks-falling-when-hit | def hitBricks(grid: List[List[int]], hits: List[List[int]]) -> List[int]:
"""
You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:
It is directly connected to the top of the grid, or
At least one other brick in its four adjacent cells is stable.
You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).
Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
Example 1:
>>> hitBricks(grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]])
>>> [2]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,1,0]]
We erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,1,1,0]]
The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
[[1,0,0,0],
[0,0,0,0]]
Hence the result is [2].
Example 2:
>>> hitBricks(grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]])
>>> [0,0]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,0,0]]
We erase the underlined brick at (1,1), resulting in the grid:
[[1,0,0,0],
[1,0,0,0]]
All remaining bricks are still stable, so no bricks fall. The grid remains the same:
[[1,0,0,0],
[1,0,0,0]]
Next, we erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,0,0,0]]
Once again, all remaining bricks are still stable, so no bricks fall.
Hence the result is [0,0].
"""
|
unique-morse-code-words | def uniqueMorseRepresentations(words: List[str]) -> int:
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.
For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
>>> uniqueMorseRepresentations(words = ["gin","zen","gig","msg"])
>>> 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".
Example 2:
>>> uniqueMorseRepresentations(words = ["a"])
>>> 1
"""
|
split-array-with-same-average | def splitArraySameAverage(nums: List[int]) -> bool:
"""
You are given an integer array nums.
You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).
Return true if it is possible to achieve that and false otherwise.
Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.
Example 1:
>>> splitArraySameAverage(nums = [1,2,3,4,5,6,7,8])
>>> true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
Example 2:
>>> splitArraySameAverage(nums = [3,1])
>>> false
"""
|
number-of-lines-to-write-string | def numberOfLines(widths: List[int], s: str) -> List[int]:
"""
You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.
You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.
Return an array result of length 2 where:
result[0] is the total number of lines.
result[1] is the width of the last line in pixels.
Example 1:
>>> numberOfLines(widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz")
>>> [3,60]
Explanation: You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
Example 2:
>>> numberOfLines(widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa")
>>> [2,4]
Explanation: You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
"""
|
max-increase-to-keep-city-skyline | def maxIncreaseKeepingSkyline(grid: List[List[int]]) -> int:
"""
There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
Example 1:
>>> maxIncreaseKeepingSkyline(grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]])
>>> 35
Explanation: The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Example 2:
>>> maxIncreaseKeepingSkyline(grid = [[0,0,0],[0,0,0],[0,0,0]])
>>> 0
Explanation: Increasing the height of any building will result in the skyline changing.
"""
|
soup-servings | def soupServings(n: int) -> float:
"""
There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B,
Serve 75 ml of soup A and 25 ml of soup B,
Serve 50 ml of soup A and 50 ml of soup B, and
Serve 25 ml of soup A and 75 ml of soup B.
When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
Note that we do not have an operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.
Example 1:
>>> soupServings(n = 50)
>>> 0.62500
Explanation: If we choose the first two operations, A will become empty first.
For the third operation, A and B will become empty at the same time.
For the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Example 2:
>>> soupServings(n = 100)
>>> 0.71875
"""
|
expressive-words | def expressiveWords(s: str, words: List[str]) -> int:
"""
Sometimes people repeat letters to represent extra feeling. For example:
"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.
For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s.
Return the number of query strings that are stretchy.
Example 1:
>>> expressiveWords(s = "heeellooo", words = ["hello", "hi", "helo"])
>>> 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.
Example 2:
>>> expressiveWords(s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"])
>>> 3
"""
|
chalkboard-xor-game | def xorGame(nums: List[int]) -> bool:
"""
You are given an array of integers nums represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.
Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.
Return true if and only if Alice wins the game, assuming both players play optimally.
Example 1:
>>> xorGame(nums = [1,1,2])
>>> false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Example 2:
>>> xorGame(nums = [0,1])
>>> true
Example 3:
>>> xorGame(nums = [1,2,3])
>>> true
"""
|
subdomain-visit-count | def subdomainVisits(cpdomains: List[str]) -> List[str]:
"""
A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.
For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.
Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
Example 1:
>>> subdomainVisits(cpdomains = ["9001 discuss.leetcode.com"])
>>> ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation: We only have one website domain: "discuss.leetcode.com".
As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
>>> subdomainVisits(cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"])
>>> ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.
For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
"""
|
largest-triangle-area | def largestTriangleArea(points: List[List[int]]) -> float:
"""
Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Example 1:
>>> largestTriangleArea(points = [[0,0],[0,1],[1,0],[0,2],[2,0]])
>>> 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.
Example 2:
>>> largestTriangleArea(points = [[1,0],[0,0],[0,1]])
>>> 0.50000
"""
|
largest-sum-of-averages | def largestSumOfAverages(nums: List[int], k: int) -> float:
"""
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
>>> largestSumOfAverages(nums = [9,1,2,3,9], k = 3)
>>> 20.00000
Explanation:
The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Example 2:
>>> largestSumOfAverages(nums = [1,2,3,4,5,6,7], k = 4)
>>> 20.50000
"""
|
binary-tree-pruning | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pruneTree(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
>>> __init__(root = [1,null,0,0,1])
>>> [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.
Example 2:
>>> __init__(root = [1,0,1,0,0,0,1])
>>> [1,null,1,null,1]
Example 3:
>>> __init__(root = [1,1,0,1,1,0,1,0])
>>> [1,1,0,1,1,null,1]
"""
|
bus-routes | def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int:
"""
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.
Example 1:
>>> numBusesToDestination(routes = [[1,2,7],[3,6,7]], source = 1, target = 6)
>>> 2
Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Example 2:
>>> numBusesToDestination(routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12)
>>> -1
"""
|
ambiguous-coordinates | def ambiguousCoordinates(s: str) -> List[str]:
"""
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s.
For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)".
Return a list of strings representing all possibilities for what our original coordinates could have been.
Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1".
The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
Example 1:
>>> ambiguousCoordinates(s = "(123)")
>>> ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]
Example 2:
>>> ambiguousCoordinates(s = "(0123)")
>>> ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"]
Explanation: 0.0, 00, 0001 or 00.01 are not allowed.
Example 3:
>>> ambiguousCoordinates(s = "(00011)")
>>> ["(0, 0.011)","(0.001, 1)"]
"""
|
linked-list-components | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def numComponents(head: Optional[ListNode], nums: List[int]) -> int:
"""
You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
Example 1:
>>> __init__(head = [0,1,2,3], nums = [0,1,3])
>>> 2
Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
Example 2:
>>> __init__(head = [0,1,2,3,4], nums = [0,3,1,4])
>>> 2
Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
"""
|
race-car | def racecar(target: int) -> int:
"""
Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When you get an instruction 'R', your car does the following:
If your speed is positive then speed = -1
otherwise speed = 1
Your position stays the same.
For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.
Given a target position target, return the length of the shortest sequence of instructions to get there.
Example 1:
>>> racecar(target = 3)
>>> 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0 --> 1 --> 3.
Example 2:
>>> racecar(target = 6)
>>> 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
"""
|
short-encoding-of-words | def minimumLengthEncoding(words: List[str]) -> int:
"""
A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Example 1:
>>> minimumLengthEncoding(words = ["time", "me", "bell"])
>>> 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
Example 2:
>>> minimumLengthEncoding(words = ["t"])
>>> 2
Explanation: A valid encoding would be s = "t#" and indices = [0].
"""
|
shortest-distance-to-a-character | def shortestToChar(s: str, c: str) -> List[int]:
"""
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
Example 1:
>>> shortestToChar(s = "loveleetcode", c = "e")
>>> [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
Example 2:
>>> shortestToChar(s = "aaab", c = "b")
>>> [3,2,1,0]
"""
|
card-flipping-game | def flipgame(fronts: List[int], backs: List[int]) -> int:
"""
You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).
After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.
Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0.
Example 1:
>>> flipgame(fronts = [1,2,4,4,7], backs = [1,3,4,1,3])
>>> 2
Explanation:
If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].
2 is the minimum good integer as it appears facing down but not facing up.
It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.
Example 2:
>>> flipgame(fronts = [1], backs = [1])
>>> 0
Explanation:
There are no good integers no matter how we flip the cards, so we return 0.
"""
|
binary-trees-with-factors | def numFactoredBinaryTrees(arr: List[int]) -> int:
"""
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.
Example 1:
>>> numFactoredBinaryTrees(arr = [2,4])
>>> 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
>>> numFactoredBinaryTrees(arr = [2,4,5,10])
>>> 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
"""
|
goat-latin | def toGoatLatin(sentence: str) -> str:
"""
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
For example, the word "apple" becomes "applema".
If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on.
Return the final sentence representing the conversion from sentence to Goat Latin.
Example 1:
>>> toGoatLatin(sentence = "I speak Goat Latin")
>>> "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:
>>> toGoatLatin(sentence = "The quick brown fox jumped over the lazy dog")
>>> "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
"""
|
friends-of-appropriate-ages | def numFriendRequests(ages: List[int]) -> int:
"""
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.
A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
Otherwise, x will send a friend request to y.
Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.
Return the total number of friend requests made.
Example 1:
>>> numFriendRequests(ages = [16,16])
>>> 2
Explanation: 2 people friend request each other.
Example 2:
>>> numFriendRequests(ages = [16,17,18])
>>> 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
>>> numFriendRequests(ages = [20,30,100,110,120])
>>> 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
"""
|
most-profit-assigning-work | def maxProfitAssignment(difficulty: List[int], profit: List[int], worker: List[int]) -> int:
"""
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
>>> maxProfitAssignment(difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7])
>>> 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
Example 2:
>>> maxProfitAssignment(difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25])
>>> 0
"""
|
making-a-large-island | def largestIsland(grid: List[List[int]]) -> int:
"""
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
>>> largestIsland(grid = [[1,0],[0,1]])
>>> 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
>>> largestIsland(grid = [[1,1],[1,0]])
>>> 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
>>> largestIsland(grid = [[1,1],[1,1]])
>>> 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
"""
|
count-unique-characters-of-all-substrings-of-a-given-string | def uniqueLetterString(s: str) -> int:
"""
Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Example 1:
>>> uniqueLetterString(s = "ABC")
>>> 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
>>> uniqueLetterString(s = "ABA")
>>> 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.
Example 3:
>>> uniqueLetterString(s = "LEETCODE")
>>> 92
"""
|
consecutive-numbers-sum | def consecutiveNumbersSum(n: int) -> int:
"""
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Example 1:
>>> consecutiveNumbersSum(n = 5)
>>> 2
Explanation: 5 = 2 + 3
Example 2:
>>> consecutiveNumbersSum(n = 9)
>>> 3
Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
>>> consecutiveNumbersSum(n = 15)
>>> 4
Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
"""
|
positions-of-large-groups | def largeGroupPositions(s: str) -> List[List[int]]:
"""
In a string s of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of every large group sorted in increasing order by start index.
Example 1:
>>> largeGroupPositions(s = "abbxxxxzzy")
>>> [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Example 2:
>>> largeGroupPositions(s = "abc")
>>> []
Explanation: We have groups "a", "b", and "c", none of which are large groups.
Example 3:
>>> largeGroupPositions(s = "abcdddeeeeaabbbcd")
>>> [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".
"""
|
masking-personal-information | def maskPII(s: str) -> str:
"""
You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.
Email address:
An email address is:
A name consisting of uppercase and lowercase English letters, followed by
The '@' symbol, followed by
The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character).
To mask an email:
The uppercase letters in the name and domain must be converted to lowercase letters.
The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks "*****".
Phone number:
A phone number is formatted as follows:
The phone number contains 10-13 digits.
The last 10 digits make up the local number.
The remaining 0-3 digits, in the beginning, make up the country code.
Separation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way.
To mask a phone number:
Remove all separation characters.
The masked phone number should have the form:
"***-***-XXXX" if the country code has 0 digits.
"+*-***-***-XXXX" if the country code has 1 digit.
"+**-***-***-XXXX" if the country code has 2 digits.
"+***-***-***-XXXX" if the country code has 3 digits.
"XXXX" is the last 4 digits of the local number.
Example 1:
>>> maskPII(s = "LeetCode@LeetCode.com")
>>> "l*****e@leetcode.com"
Explanation: s is an email address.
The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.
Example 2:
>>> maskPII(s = "AB@qq.com")
>>> "a*****b@qq.com"
Explanation: s is an email address.
The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.
Note that even though "ab" is 2 characters, it still must have 5 asterisks in the middle.
Example 3:
>>> maskPII(s = "1(234)567-890")
>>> "***-***-7890"
Explanation: s is a phone number.
There are 10 digits, so the local number is 10 digits and the country code is 0 digits.
Thus, the resulting masked number is "***-***-7890".
"""
|
flipping-an-image | def flipAndInvertImage(image: List[List[int]]) -> List[List[int]]:
"""
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1,1,0] horizontally results in [0,1,1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
For example, inverting [0,1,1] results in [1,0,0].
Example 1:
>>> flipAndInvertImage(image = [[1,1,0],[1,0,1],[0,0,0]])
>>> [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
>>> flipAndInvertImage(image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]])
>>> [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
"""
|
find-and-replace-in-string | def findReplaceString(s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
"""
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
Check if the substring sources[i] occurs at index indices[i] in the original string s.
If it does not occur, do nothing.
Otherwise if it does occur, replace that substring with targets[i].
For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd".
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.
For example, a testcase with s = "abc", indices = [0, 1], and sources = ["ab","bc"] will not be generated because the "ab" and "bc" replacements overlap.
Return the resulting string after performing all replacement operations on s.
A substring is a contiguous sequence of characters in a string.
Example 1:
>>> findReplaceString(s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"])
>>> "eeebffff"
Explanation:
"a" occurs at index 0 in s, so we replace it with "eee".
"cd" occurs at index 2 in s, so we replace it with "ffff".
Example 2:
>>> findReplaceString(s = "abcd", indices = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"])
>>> "eeecd"
Explanation:
"ab" occurs at index 0 in s, so we replace it with "eee".
"ec" does not occur at index 2 in s, so we do nothing.
"""
|
sum-of-distances-in-tree | def sumOfDistancesInTree(n: int, edges: List[List[int]]) -> List[int]:
"""
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Example 1:
>>> sumOfDistancesInTree(n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]])
>>> [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:
>>> sumOfDistancesInTree(n = 1, edges = [])
>>> [0]
Example 3:
>>> sumOfDistancesInTree(n = 2, edges = [[1,0]])
>>> [1,1]
"""
|
image-overlap | def largestOverlap(img1: List[List[int]], img2: List[List[int]]) -> int:
"""
You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.
Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
Example 1:
>>> largestOverlap(img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]])
>>> 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
Example 2:
>>> largestOverlap(img1 = [[1]], img2 = [[1]])
>>> 1
Example 3:
>>> largestOverlap(img1 = [[0]], img2 = [[0]])
>>> 0
"""
|
rectangle-overlap | def isRectangleOverlap(rec1: List[int], rec2: List[int]) -> bool:
"""
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Example 1:
>>> isRectangleOverlap(rec1 = [0,0,2,2], rec2 = [1,1,3,3])
>>> true
Example 2:
>>> isRectangleOverlap(rec1 = [0,0,1,1], rec2 = [1,0,2,1])
>>> false
Example 3:
>>> isRectangleOverlap(rec1 = [0,0,1,1], rec2 = [2,2,3,3])
>>> false
"""
|
new-21-game | def new21Game(n: int, k: int, maxPts: int) -> float:
"""
Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets k or more points.
Return the probability that Alice has n or fewer points.
Answers within 10-5 of the actual answer are considered accepted.
Example 1:
>>> new21Game(n = 10, k = 1, maxPts = 10)
>>> 1.00000
Explanation: Alice gets a single card, then stops.
Example 2:
>>> new21Game(n = 6, k = 1, maxPts = 10)
>>> 0.60000
Explanation: Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.
Example 3:
>>> new21Game(n = 21, k = 17, maxPts = 10)
>>> 0.73278
"""
|
push-dominoes | def pushDominoes(dominoes: str) -> str:
"""
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
You are given a string dominoes representing the initial state where:
dominoes[i] = 'L', if the ith domino has been pushed to the left,
dominoes[i] = 'R', if the ith domino has been pushed to the right, and
dominoes[i] = '.', if the ith domino has not been pushed.
Return a string representing the final state.
Example 1:
>>> pushDominoes(dominoes = "RR.L")
>>> "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Example 2:
>>> pushDominoes(dominoes = ".L.R...LR..L..")
>>> "LL.RR.LLRRLL.."
"""
|
similar-string-groups | def numSimilarGroups(strs: List[str]) -> int:
"""
Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".
Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?
Example 1:
>>> numSimilarGroups(strs = ["tars","rats","arts","star"])
>>> 2
Example 2:
>>> numSimilarGroups(strs = ["omv","ovm"])
>>> 1
"""
|
magic-squares-in-grid | def numMagicSquaresInside(grid: List[List[int]]) -> int:
"""
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 magic square subgrids are there?
Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.
Example 1:
>>> numMagicSquaresInside(grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]])
>>> 1
Explanation:
The following subgrid is a 3 x 3 magic square:
while this one is not:
In total, there is only one magic square inside the given grid.
Example 2:
>>> numMagicSquaresInside(grid = [[8]])
>>> 0
"""
|
keys-and-rooms | def canVisitAllRooms(rooms: List[List[int]]) -> bool:
"""
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
Example 1:
>>> canVisitAllRooms(rooms = [[1],[2],[3],[]])
>>> true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Example 2:
>>> canVisitAllRooms(rooms = [[1,3],[3,0,1],[2],[0]])
>>> false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
"""
|
split-array-into-fibonacci-sequence | def splitIntoFibonacci(num: str) -> List[int]:
"""
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:
0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
f.length >= 3, and
f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.
Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Example 1:
>>> splitIntoFibonacci(num = "1101111")
>>> [11,0,11,11]
Explanation: The output [110, 1, 111] would also be accepted.
Example 2:
>>> splitIntoFibonacci(num = "112358130")
>>> []
Explanation: The task is impossible.
Example 3:
>>> splitIntoFibonacci(num = "0123")
>>> []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
"""
|
backspace-string-compare | def backspaceCompare(s: str, t: str) -> bool:
"""
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
>>> backspaceCompare(s = "ab#c", t = "ad#c")
>>> true
Explanation: Both s and t become "ac".
Example 2:
>>> backspaceCompare(s = "ab##", t = "c#d#")
>>> true
Explanation: Both s and t become "".
Example 3:
>>> backspaceCompare(s = "a#c", t = "b")
>>> false
Explanation: s becomes "c" while t becomes "b".
"""
|
longest-mountain-in-array | def longestMountain(arr: List[int]) -> int:
"""
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
Example 1:
>>> longestMountain(arr = [2,1,4,7,3,2,5])
>>> 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
>>> longestMountain(arr = [2,2,2])
>>> 0
Explanation: There is no mountain.
"""
|
hand-of-straights | def isNStraightHand(hand: List[int], groupSize: int) -> bool:
"""
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
>>> isNStraightHand(hand = [1,2,3,6,2,3,4,7,8], groupSize = 3)
>>> true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
>>> isNStraightHand(hand = [1,2,3,4,5], groupSize = 4)
>>> false
Explanation: Alice's hand can not be rearranged into groups of 4.
"""
|
shortest-path-visiting-all-nodes | def shortestPathLength(graph: List[List[int]]) -> int:
"""
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Example 1:
>>> shortestPathLength(graph = [[1,2,3],[0],[0],[0]])
>>> 4
Explanation: One possible path is [1,0,2,0,3]
Example 2:
>>> shortestPathLength(graph = [[1],[0,2,4],[1,3,4],[2],[1,2]])
>>> 4
Explanation: One possible path is [0,1,4,2,3]
"""
|
shifting-letters | def shiftingLetters(s: str, shifts: List[int]) -> str:
"""
You are given a string s of lowercase English letters and an integer array shifts of the same length.
Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.
Return the final string after all such shifts to s are applied.
Example 1:
>>> shiftingLetters(s = "abc", shifts = [3,5,9])
>>> "rpl"
Explanation: We start with "abc".
After shifting the first 1 letters of s by 3, we have "dbc".
After shifting the first 2 letters of s by 5, we have "igc".
After shifting the first 3 letters of s by 9, we have "rpl", the answer.
Example 2:
>>> shiftingLetters(s = "aaa", shifts = [1,2,3])
>>> "gfd"
"""
|
maximize-distance-to-closest-person | def maxDistToClosest(seats: List[int]) -> int:
"""
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.
Example 1:
>>> maxDistToClosest(seats = [1,0,0,0,1,0,1])
>>> 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
>>> maxDistToClosest(seats = [1,0,0,0])
>>> 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Example 3:
>>> maxDistToClosest(seats = [0,1])
>>> 1
"""
|
rectangle-area-ii | def rectangleArea(rectangles: List[List[int]]) -> int:
"""
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.
Return the total area. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
>>> rectangleArea(rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]])
>>> 6
Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.
Example 2:
>>> rectangleArea(rectangles = [[0,0,1000000000,1000000000]])
>>> 49
Explanation: The answer is 1018 modulo (109 + 7), which is 49.
"""
|
loud-and-rich | def loudAndRich(richer: List[List[int]], quiet: List[int]) -> List[int]:
"""
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.
You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).
Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.
Example 1:
>>> loudAndRich(richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0])
>>> [5,5,2,5,4,5,6,7]
Explanation:
answer[0] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.
answer[7] = 7.
Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.
The other answers can be filled out with similar reasoning.
Example 2:
>>> loudAndRich(richer = [], quiet = [0])
>>> [0]
"""
|
peak-index-in-a-mountain-array | def peakIndexInMountainArray(arr: List[int]) -> int:
"""
You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.
Return the index of the peak element.
Your task is to solve it in O(log(n)) time complexity.
Example 1:
>>> peakIndexInMountainArray(arr = [0,1,0])
>>> 1
Example 2:
>>> peakIndexInMountainArray(arr = [0,2,1,0])
>>> 1
Example 3:
>>> peakIndexInMountainArray(arr = [0,10,5,2])
>>> 1
"""
|
car-fleet | def carFleet(target: int, position: List[int], speed: List[int]) -> int:
"""
There are n cars at given miles away from the starting mile 0, traveling to reach the mile target.
You are given two integer array position and speed, both of length n, where position[i] is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour.
A car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car.
A car fleet is a car or cars driving next to each other. The speed of the car fleet is the minimum speed of any car in the fleet.
If a car catches up to a car fleet at the mile target, it will still be considered as part of the car fleet.
Return the number of car fleets that will arrive at the destination.
Example 1:
>>> carFleet(target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3])
>>> 3
Explanation:
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The fleet forms at target.
The car starting at 0 (speed 1) does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Example 2:
>>> carFleet(target = 10, position = [3], speed = [3])
>>> 1
Explanation:
There is only one car, hence there is only one fleet.
Example 3:
>>> carFleet(target = 100, position = [0,2,4], speed = [4,2,1])
>>> 1
Explanation:
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The car starting at 4 (speed 1) travels to 5.
Then, the fleet at 4 (speed 2) and the car at position 5 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.