task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
mark-elements-on-array-by-performing-queries | def unmarkedSumArray(nums: List[int], queries: List[List[int]]) -> List[int]:
"""
You are given a 0-indexed array nums of size n consisting of positive integers.
You are also given a 2D array queries of size m where queries[i] = [indexi, ki].
Initially all elements of the array are unmarked.
You need to apply m queries on the array in order, where on the ith query you do the following:
Mark the element at index indexi if it is not already marked.
Then mark ki unmarked elements in the array with the smallest values. If multiple such elements exist, mark the ones with the smallest indices. And if less than ki unmarked elements exist, then mark all of them.
Return an array answer of size m where answer[i] is the sum of unmarked elements in the array after the ith query.
Example 1:
>>> unmarkedSumArray(nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]])
>>> [8,3,0]
Explanation:
We do the following queries on the array:
Mark the element at index 1, and 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 2 + 2 + 3 + 1 = 8.
Mark the element at index 3, since it is already marked we skip it. Then we mark 3 of the smallest unmarked elements with the smallest indices, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 3.
Mark the element at index 4, since it is already marked we skip it. Then we mark 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 0.
Example 2:
>>> unmarkedSumArray(nums = [1,4,2,3], queries = [[0,1]])
>>> [7]
Explanation: We do one query which is mark the element at index 0 and mark the smallest element among unmarked elements. The marked elements will be nums = [1,4,2,3], and the sum of unmarked elements is 4 + 3 = 7.
"""
|
replace-question-marks-in-string-to-minimize-its-value | def minimizeStringValue(s: str) -> str:
"""
You are given a string s. s[i] is either a lowercase English letter or '?'.
For a string t having length m containing only lowercase English letters, we define the function cost(i) for an index i as the number of characters equal to t[i] that appeared before it, i.e. in the range [0, i - 1].
The value of t is the sum of cost(i) for all indices i.
For example, for the string t = "aab":
cost(0) = 0
cost(1) = 1
cost(2) = 0
Hence, the value of "aab" is 0 + 1 + 0 = 1.
Your task is to replace all occurrences of '?' in s with any lowercase English letter so that the value of s is minimized.
Return a string denoting the modified string with replaced occurrences of '?'. If there are multiple strings resulting in the minimum value, return the lexicographically smallest one.
Example 1:
>>> minimizeStringValue(s = "???")
>>> "abc"
Explanation: In this example, we can replace the occurrences of '?' to make s equal to "abc".
For "abc", cost(0) = 0, cost(1) = 0, and cost(2) = 0.
The value of "abc" is 0.
Some other modifications of s that have a value of 0 are "cba", "abz", and, "hey".
Among all of them, we choose the lexicographically smallest.
Example 2:
>>> minimizeStringValue(s = "a?a?")
>>> "abac"
Explanation: In this example, the occurrences of '?' can be replaced to make s equal to "abac".
For "abac", cost(0) = 0, cost(1) = 0, cost(2) = 1, and cost(3) = 0.
The value of "abac" is 1.
"""
|
find-the-sum-of-the-power-of-all-subsequences | def sumOfPower(nums: List[int], k: int) -> int:
"""
You are given an integer array nums of length n and a positive integer k.
The power of an array of integers is defined as the number of subsequences with their sum equal to k.
Return the sum of power of all subsequences of nums.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> sumOfPower(nums = [1,2,3], k = 3)
>>> 6
Explanation:
There are 5 subsequences of nums with non-zero power:
The subsequence [1,2,3] has 2 subsequences with sum == 3: [1,2,3] and [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
Hence the answer is 2 + 1 + 1 + 1 + 1 = 6.
Example 2:
>>> sumOfPower(nums = [2,3,3], k = 5)
>>> 4
Explanation:
There are 3 subsequences of nums with non-zero power:
The subsequence [2,3,3] has 2 subsequences with sum == 5: [2,3,3] and [2,3,3].
The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
Hence the answer is 2 + 1 + 1 = 4.
Example 3:
>>> sumOfPower(nums = [1,2,3], k = 7)
>>> 0
Explanation: There exists no subsequence with sum 7. Hence all subsequences of nums have power = 0.
"""
|
existence-of-a-substring-in-a-string-and-its-reverse | def isSubstringPresent(s: str) -> bool:
"""
Given a string s, find any substring of length 2 which is also present in the reverse of s.
Return true if such a substring exists, and false otherwise.
Example 1:
>>> isSubstringPresent(s = "leetcode")
>>> true
Explanation: Substring "ee" is of length 2 which is also present in reverse(s) == "edocteel".
Example 2:
>>> isSubstringPresent(s = "abcba")
>>> true
Explanation: All of the substrings of length 2 "ab", "bc", "cb", "ba" are also present in reverse(s) == "abcba".
Example 3:
>>> isSubstringPresent(s = "abcd")
>>> false
Explanation: There is no substring of length 2 in s, which is also present in the reverse of s.
"""
|
count-substrings-starting-and-ending-with-given-character | def countSubstrings(s: str, c: str) -> int:
"""
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
Example 1:
>>> countSubstrings(s = "abada", c = "a")
>>> 6
Explanation: Substrings starting and ending with "a" are: "abada", "abada", "abada", "abada", "abada", "abada".
Example 2:
>>> countSubstrings(s = "zzz", c = "z")
>>> 6
Explanation: There are a total of 6 substrings in s and all start and end with "z".
"""
|
minimum-deletions-to-make-string-k-special | def minimumDeletions(word: str, k: int) -> int:
"""
You are given a string word and an integer k.
We consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i and j in the string.
Here, freq(x) denotes the frequency of the character x in word, and |y| denotes the absolute value of y.
Return the minimum number of characters you need to delete to make word k-special.
Example 1:
>>> minimumDeletions(word = "aabcaba", k = 0)
>>> 3
Explanation: We can make word 0-special by deleting 2 occurrences of "a" and 1 occurrence of "c". Therefore, word becomes equal to "baba" where freq('a') == freq('b') == 2.
Example 2:
>>> minimumDeletions(word = "dabdcbdcdcd", k = 2)
>>> 2
Explanation: We can make word 2-special by deleting 1 occurrence of "a" and 1 occurrence of "d". Therefore, word becomes equal to "bdcbdcdcd" where freq('b') == 2, freq('c') == 3, and freq('d') == 4.
Example 3:
>>> minimumDeletions(word = "aaabaaa", k = 2)
>>> 1
Explanation: We can make word 2-special by deleting 1 occurrence of "b". Therefore, word becomes equal to "aaaaaa" where each letter's frequency is now uniformly 6.
"""
|
minimum-moves-to-pick-k-ones | def minimumMoves(nums: List[int], k: int, maxChanges: int) -> int:
"""
You are given a binary array nums of length n, a positive integer k and a non-negative integer maxChanges.
Alice plays a game, where the goal is for Alice to pick up k ones from nums using the minimum number of moves. When the game starts, Alice picks up any index aliceIndex in the range [0, n - 1] and stands there. If nums[aliceIndex] == 1 , Alice picks up the one and nums[aliceIndex] becomes 0(this does not count as a move). After this, Alice can make any number of moves (including zero) where in each move Alice must perform exactly one of the following actions:
Select any index j != aliceIndex such that nums[j] == 0 and set nums[j] = 1. This action can be performed at most maxChanges times.
Select any two adjacent indices x and y (|x - y| == 1) such that nums[x] == 1, nums[y] == 0, then swap their values (set nums[y] = 1 and nums[x] = 0). If y == aliceIndex, Alice picks up the one after this move and nums[y] becomes 0.
Return the minimum number of moves required by Alice to pick exactly k ones.
Example 1:
>>> minimumMoves(nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1)
>>> 3
Explanation: Alice can pick up 3 ones in 3 moves, if Alice performs the following actions in each move when standing at aliceIndex == 1:
At the start of the game Alice picks up the one and nums[1] becomes 0. nums becomes [1,0,0,0,0,1,1,0,0,1].
Select j == 2 and perform an action of the first type. nums becomes [1,0,1,0,0,1,1,0,0,1]
Select x == 2 and y == 1, and perform an action of the second type. nums becomes [1,1,0,0,0,1,1,0,0,1]. As y == aliceIndex, Alice picks up the one and nums becomes [1,0,0,0,0,1,1,0,0,1].
Select x == 0 and y == 1, and perform an action of the second type. nums becomes [0,1,0,0,0,1,1,0,0,1]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0,0,1,1,0,0,1].
Note that it may be possible for Alice to pick up 3 ones using some other sequence of 3 moves.
Example 2:
>>> minimumMoves(nums = [0,0,0,0], k = 2, maxChanges = 3)
>>> 4
Explanation: Alice can pick up 2 ones in 4 moves, if Alice performs the following actions in each move when standing at aliceIndex == 0:
Select j == 1 and perform an action of the first type. nums becomes [0,1,0,0].
Select x == 1 and y == 0, and perform an action of the second type. nums becomes [1,0,0,0]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0].
Select j == 1 again and perform an action of the first type. nums becomes [0,1,0,0].
Select x == 1 and y == 0 again, and perform an action of the second type. nums becomes [1,0,0,0]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0].
"""
|
make-string-anti-palindrome | def makeAntiPalindrome(s: str) -> str:
"""
We call a string s of even length n an anti-palindrome if for each index 0 <= i < n, s[i] != s[n - i - 1].
Given a string s, your task is to make s an anti-palindrome by doing any number of operations (including zero).
In one operation, you can select two characters from s and swap them.
Return the resulting string. If multiple strings meet the conditions, return the lexicographically smallest one. If it can't be made into an anti-palindrome, return "-1".
Example 1:
>>> makeAntiPalindrome(s = "abca")
>>> "aabc"
Explanation:
"aabc" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abca".
Example 2:
>>> makeAntiPalindrome(s = "abba")
>>> "aabb"
Explanation:
"aabb" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abba".
Example 3:
>>> makeAntiPalindrome(s = "cccd")
>>> "-1"
Explanation:
You can see that no matter how you rearrange the characters of "cccd", either s[0] == s[3] or s[1] == s[2]. So it can not form an anti-palindrome string.
"""
|
maximum-length-substring-with-two-occurrences | def maximumLengthSubstring(s: str) -> int:
"""
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Example 1:
>>> maximumLengthSubstring(s = "bcbbbcba")
>>> 4
Explanation:
The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".
Example 2:
>>> maximumLengthSubstring(s = "aaaa")
>>> 2
Explanation:
The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".
"""
|
apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k | def minOperations(k: int) -> int:
"""
You are given a positive integer k. Initially, you have an array nums = [1].
You can perform any of the following operations on the array any number of times (possibly zero):
Choose any element in the array and increase its value by 1.
Duplicate any element in the array and add it to the end of the array.
Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k.
Example 1:
>>> minOperations(k = 11)
>>> 5
Explanation:
We can do the following operations on the array nums = [1]:
Increase the element by 1 three times. The resulting array is nums = [4].
Duplicate the element two times. The resulting array is nums = [4,4,4].
The sum of the final array is 4 + 4 + 4 = 12 which is greater than or equal to k = 11.
The total number of operations performed is 3 + 2 = 5.
Example 2:
>>> minOperations(k = 1)
>>> 0
Explanation:
The sum of the original array is already greater than or equal to 1, so no operations are needed.
"""
|
most-frequent-ids | def mostFrequentIDs(nums: List[int], freq: List[int]) -> List[int]:
"""
The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, nums and freq, of equal length n. Each element in nums represents an ID, and the corresponding element in freq indicates how many times that ID should be added to or removed from the collection at each step.
Addition of IDs: If freq[i] is positive, it means freq[i] IDs with the value nums[i] are added to the collection at step i.
Removal of IDs: If freq[i] is negative, it means -freq[i] IDs with the value nums[i] are removed from the collection at step i.
Return an array ans of length n, where ans[i] represents the count of the most frequent ID in the collection after the ith step. If the collection is empty at any step, ans[i] should be 0 for that step.
Example 1:
>>> mostFrequentIDs(nums = [2,3,2,1], freq = [3,2,-3,1])
>>> [3,3,2,2]
Explanation:
After step 0, we have 3 IDs with the value of 2. So ans[0] = 3.
After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So ans[1] = 3.
After step 2, we have 2 IDs with the value of 3. So ans[2] = 2.
After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So ans[3] = 2.
Example 2:
>>> mostFrequentIDs(nums = [5,5,3], freq = [2,-2,1])
>>> [2,0,1]
Explanation:
After step 0, we have 2 IDs with the value of 5. So ans[0] = 2.
After step 1, there are no IDs. So ans[1] = 0.
After step 2, we have 1 ID with the value of 3. So ans[2] = 1.
"""
|
longest-common-suffix-queries | def stringIndices(wordsContainer: List[str], wordsQuery: List[str]) -> List[int]:
"""
You are given two arrays of strings wordsContainer and wordsQuery.
For each wordsQuery[i], you need to find a string from wordsContainer that has the longest common suffix with wordsQuery[i]. If there are two or more strings in wordsContainer that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer.
Return an array of integers ans, where ans[i] is the index of the string in wordsContainer that has the longest common suffix with wordsQuery[i].
Example 1:
>>> stringIndices(wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"])
>>> [1,1,1]
Explanation:
Let's look at each wordsQuery[i] separately:
For wordsQuery[0] = "cd", strings from wordsContainer that share the longest common suffix "cd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
For wordsQuery[1] = "bcd", strings from wordsContainer that share the longest common suffix "bcd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
For wordsQuery[2] = "xyz", there is no string from wordsContainer that shares a common suffix. Hence the longest common suffix is "", that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
Example 2:
>>> stringIndices(wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"])
>>> [2,0,2]
Explanation:
Let's look at each wordsQuery[i] separately:
For wordsQuery[0] = "gh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.
For wordsQuery[1] = "acbfgh", only the string at index 0 shares the longest common suffix "fgh". Hence it is the answer, even though the string at index 2 is shorter.
For wordsQuery[2] = "acbfegh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.
"""
|
shortest-subarray-with-or-at-least-k-i | def minimumSubarrayLength(nums: List[int], k: int) -> int:
"""
You are given an array nums of non-negative integers and an integer k.
An array is called special if the bitwise OR of all of its elements is at least k.
Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists.
Example 1:
>>> minimumSubarrayLength(nums = [1,2,3], k = 2)
>>> 1
Explanation:
The subarray [3] has OR value of 3. Hence, we return 1.
Note that [2] is also a special subarray.
Example 2:
>>> minimumSubarrayLength(nums = [2,1,8], k = 10)
>>> 3
Explanation:
The subarray [2,1,8] has OR value of 11. Hence, we return 3.
Example 3:
>>> minimumSubarrayLength(nums = [1,2], k = 0)
>>> 1
Explanation:
The subarray [1] has OR value of 1. Hence, we return 1.
"""
|
minimum-levels-to-gain-more-points | def minimumLevels(possible: List[int]) -> int:
"""
You are given a binary array possible of length n.
Alice and Bob are playing a game that consists of n levels. Some of the levels in the game are impossible to clear while others can always be cleared. In particular, if possible[i] == 0, then the ith level is impossible to clear for both the players. A player gains 1 point on clearing a level and loses 1 point if the player fails to clear it.
At the start of the game, Alice will play some levels in the given order starting from the 0th level, after which Bob will play for the rest of the levels.
Alice wants to know the minimum number of levels she should play to gain more points than Bob, if both players play optimally to maximize their points.
Return the minimum number of levels Alice should play to gain more points. If this is not possible, return -1.
Note that each player must play at least 1 level.
Example 1:
>>> minimumLevels(possible = [1,0,1,0])
>>> 1
Explanation:
Let's look at all the levels that Alice can play up to:
If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.
If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.
If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.
Alice must play a minimum of 1 level to gain more points.
Example 2:
>>> minimumLevels(possible = [1,1,1,1,1])
>>> 3
Explanation:
Let's look at all the levels that Alice can play up to:
If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.
If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.
If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.
If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.
Alice must play a minimum of 3 levels to gain more points.
Example 3:
>>> minimumLevels(possible = [0,0])
>>> -1
Explanation:
The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.
"""
|
shortest-subarray-with-or-at-least-k-ii | def minimumSubarrayLength(nums: List[int], k: int) -> int:
"""
You are given an array nums of non-negative integers and an integer k.
An array is called special if the bitwise OR of all of its elements is at least k.
Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists.
Example 1:
>>> minimumSubarrayLength(nums = [1,2,3], k = 2)
>>> 1
Explanation:
The subarray [3] has OR value of 3. Hence, we return 1.
Example 2:
>>> minimumSubarrayLength(nums = [2,1,8], k = 10)
>>> 3
Explanation:
The subarray [2,1,8] has OR value of 11. Hence, we return 3.
Example 3:
>>> minimumSubarrayLength(nums = [1,2], k = 0)
>>> 1
Explanation:
The subarray [1] has OR value of 1. Hence, we return 1.
"""
|
find-the-sum-of-subsequence-powers | def sumOfPowers(nums: List[int], k: int) -> int:
"""
You are given an integer array nums of length n, and a positive integer k.
The power of a subsequence is defined as the minimum absolute difference between any two elements in the subsequence.
Return the sum of powers of all subsequences of nums which have length equal to k.
Since the answer may be large, return it modulo 109 + 7.
Example 1:
>>> sumOfPowers(nums = [1,2,3,4], k = 3)
>>> 4
Explanation:
There are 4 subsequences in nums which have length 3: [1,2,3], [1,3,4], [1,2,4], and [2,3,4]. The sum of powers is |2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4.
Example 2:
>>> sumOfPowers(nums = [2,2], k = 2)
>>> 0
Explanation:
The only subsequence in nums which has length 2 is [2,2]. The sum of powers is |2 - 2| = 0.
Example 3:
>>> sumOfPowers(nums = [4,3,-1], k = 2)
>>> 10
Explanation:
There are 3 subsequences in nums which have length 2: [4,3], [4,-1], and [3,-1]. The sum of powers is |4 - 3| + |4 - (-1)| + |3 - (-1)| = 10.
"""
|
harshad-number | def sumOfTheDigitsOfHarshadNumber(x: int) -> int:
"""
An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1.
Example 1:
>>> sumOfTheDigitsOfHarshadNumber(x = 18)
>>> 9
Explanation:
The sum of digits of x is 9. 18 is divisible by 9. So 18 is a Harshad number and the answer is 9.
Example 2:
>>> sumOfTheDigitsOfHarshadNumber(x = 23)
>>> -1
Explanation:
The sum of digits of x is 5. 23 is not divisible by 5. So 23 is not a Harshad number and the answer is -1.
"""
|
water-bottles-ii | def maxBottlesDrunk(numBottles: int, numExchange: int) -> int:
"""
You are given two integers numBottles and numExchange.
numBottles represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:
Drink any number of full water bottles turning them into empty bottles.
Exchange numExchange empty bottles with one full water bottle. Then, increase numExchange by one.
Note that you cannot exchange multiple batches of empty bottles for the same value of numExchange. For example, if numBottles == 3 and numExchange == 1, you cannot exchange 3 empty water bottles for 3 full bottles.
Return the maximum number of water bottles you can drink.
Example 1:
>>> maxBottlesDrunk(numBottles = 13, numExchange = 6)
>>> 15
Explanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
Example 2:
>>> maxBottlesDrunk(numBottles = 10, numExchange = 3)
>>> 13
Explanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
"""
|
count-alternating-subarrays | def countAlternatingSubarrays(nums: List[int]) -> int:
"""
You are given a binary array nums.
We call a subarray alternating if no two adjacent elements in the subarray have the same value.
Return the number of alternating subarrays in nums.
Example 1:
>>> countAlternatingSubarrays(nums = [0,1,1,1])
>>> 5
Explanation:
The following subarrays are alternating: [0], [1], [1], [1], and [0,1].
Example 2:
>>> countAlternatingSubarrays(nums = [1,0,1,0])
>>> 10
Explanation:
Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.
"""
|
minimize-manhattan-distances | def minimumDistance(points: List[List[int]]) -> int:
"""
You are given an array points representing integer coordinates of some points on a 2D plane, where points[i] = [xi, yi].
The distance between two points is defined as their Manhattan distance.
Return the minimum possible value for maximum distance between any two points by removing exactly one point.
Example 1:
>>> minimumDistance(points = [[3,10],[5,15],[10,2],[4,4]])
>>> 12
Explanation:
The maximum distance after removing each point is the following:
After removing the 0th point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18.
After removing the 1st point the maximum distance is between points (3, 10) and (10, 2), which is |3 - 10| + |10 - 2| = 15.
After removing the 2nd point the maximum distance is between points (5, 15) and (4, 4), which is |5 - 4| + |15 - 4| = 12.
After removing the 3rd point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18.
12 is the minimum possible maximum distance between any two points after removing exactly one point.
Example 2:
>>> minimumDistance(points = [[1,1],[1,1],[1,1]])
>>> 0
Explanation:
Removing any of the points results in the maximum distance between any two points of 0.
"""
|
find-longest-self-contained-substring | def maxSubstringLength(s: str) -> int:
"""
Given a string s, your task is to find the length of the longest self-contained substring of s.
A substring t of a string s is called self-contained if t != s and for every character in t, it doesn't exist in the rest of s.
Return the length of the longest self-contained substring of s if it exists, otherwise, return -1.
Example 1:
>>> maxSubstringLength(s = "abba")
>>> 2
Explanation:
Let's check the substring "bb". You can see that no other "b" is outside of this substring. Hence the answer is 2.
Example 2:
>>> maxSubstringLength(s = "abab")
>>> -1
Explanation:
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.
Example 3:
>>> maxSubstringLength(s = "abacd")
>>> 4
Explanation:
Let's check the substring "abac". There is only one character outside of this substring and that is "d". There is no "d" inside the chosen substring, so it satisfies the condition and the answer is 4.
"""
|
longest-strictly-increasing-or-strictly-decreasing-subarray | def longestMonotonicSubarray(nums: List[int]) -> int:
"""
You are given an array of integers nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.
Example 1:
>>> longestMonotonicSubarray(nums = [1,4,3,3,2])
>>> 2
Explanation:
The strictly increasing subarrays of nums are [1], [2], [3], [3], [4], and [1,4].
The strictly decreasing subarrays of nums are [1], [2], [3], [3], [4], [3,2], and [4,3].
Hence, we return 2.
Example 2:
>>> longestMonotonicSubarray(nums = [3,3,3,3])
>>> 1
Explanation:
The strictly increasing subarrays of nums are [3], [3], [3], and [3].
The strictly decreasing subarrays of nums are [3], [3], [3], and [3].
Hence, we return 1.
Example 3:
>>> longestMonotonicSubarray(nums = [3,2,1])
>>> 3
Explanation:
The strictly increasing subarrays of nums are [3], [2], and [1].
The strictly decreasing subarrays of nums are [3], [2], [1], [3,2], [2,1], and [3,2,1].
Hence, we return 3.
"""
|
lexicographically-smallest-string-after-operations-with-constraint | def getSmallestString(s: str, k: int) -> str:
"""
You are given a string s and an integer k.
Define a function distance(s1, s2) between two strings s1 and s2 of the same length n as:
The sum of the minimum distance between s1[i] and s2[i] when the characters from 'a' to 'z' are placed in a cyclic order, for all i in the range [0, n - 1].
For example, distance("ab", "cd") == 4, and distance("a", "z") == 1.
You can change any letter of s to any other lowercase English letter, any number of times.
Return a string denoting the lexicographically smallest string t you can get after some changes, such that distance(s, t) <= k.
Example 1:
>>> getSmallestString(s = "zbbz", k = 3)
>>> "aaaz"
Explanation:
Change s to "aaaz". The distance between "zbbz" and "aaaz" is equal to k = 3.
Example 2:
>>> getSmallestString(s = "xaxcd", k = 4)
>>> "aawcd"
Explanation:
The distance between "xaxcd" and "aawcd" is equal to k = 4.
Example 3:
>>> getSmallestString(s = "lol", k = 0)
>>> "lol"
Explanation:
It's impossible to change any character as k = 0.
"""
|
minimum-operations-to-make-median-of-array-equal-to-k | def minOperationsToMakeMedianK(nums: List[int], k: int) -> int:
"""
You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1.
Return the minimum number of operations needed to make the median of nums equal to k.
The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
Example 1:
>>> minOperationsToMakeMedianK(nums = [2,5,6,8,5], k = 4)
>>> 2
Explanation:
We can subtract one from nums[1] and nums[4] to obtain [2, 4, 6, 8, 4]. The median of the resulting array is equal to k.
Example 2:
>>> minOperationsToMakeMedianK(nums = [2,5,6,8,5], k = 7)
>>> 3
Explanation:
We can add one to nums[1] twice and add one to nums[2] once to obtain [2, 7, 7, 8, 5].
Example 3:
>>> minOperationsToMakeMedianK(nums = [1,2,3,4,5,6], k = 4)
>>> 0
Explanation:
The median of the array is already equal to k.
"""
|
minimum-cost-walk-in-weighted-graph | def minimumCost(n: int, edges: List[List[int]], query: List[List[int]]) -> List[int]:
"""
There is an undirected weighted graph with n vertices labeled from 0 to n - 1.
You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi.
A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.
The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator.
You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1.
Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.
Example 1:
>>> minimumCost(n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]])
>>> [1,-1]
Explanation:
To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7).
In the second query, there is no walk between nodes 3 and 4, so the answer is -1.
Example 2:
>>> minimumCost(n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]])
>>> [0]
Explanation:
To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1).
"""
|
find-the-index-of-permutation | def getPermutationIndex(perm: List[int]) -> int:
"""
Given an array perm of length n which is a permutation of [1, 2, ..., n], return the index of perm in the lexicographically sorted array of all of the permutations of [1, 2, ..., n].
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> getPermutationIndex(perm = [1,2])
>>> 0
Explanation:
There are only two permutations in the following order:
[1,2], [2,1]
And [1,2] is at index 0.
Example 2:
>>> getPermutationIndex(perm = [3,1,2])
>>> 4
Explanation:
There are only six permutations in the following order:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]
And [3,1,2] is at index 4.
"""
|
score-of-a-string | def scoreOfString(s: str) -> int:
"""
You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
Example 1:
>>> scoreOfString(s = "hello")
>>> 13
Explanation:
The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.
Example 2:
>>> scoreOfString(s = "zaz")
>>> 50
Explanation:
The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.
"""
|
minimum-rectangles-to-cover-points | def minRectanglesToCoverPoints(points: List[List[int]], w: int) -> int:
"""
You are given a 2D integer array points, where points[i] = [xi, yi]. You are also given an integer w. Your task is to cover all the given points with rectangles.
Each rectangle has its lower end at some point (x1, 0) and its upper end at some point (x2, y2), where x1 <= x2, y2 >= 0, and the condition x2 - x1 <= w must be satisfied for each rectangle.
A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.
Return an integer denoting the minimum number of rectangles needed so that each point is covered by at least one rectangle.
Note: A point may be covered by more than one rectangle.
Example 1:
>>> minRectanglesToCoverPoints(points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1)
>>> 2
Explanation:
The image above shows one possible placement of rectangles to cover the points:
A rectangle with a lower end at (1, 0) and its upper end at (2, 8)
A rectangle with a lower end at (3, 0) and its upper end at (4, 8)
Example 2:
>>> minRectanglesToCoverPoints(points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2)
>>> 3
Explanation:
The image above shows one possible placement of rectangles to cover the points:
A rectangle with a lower end at (0, 0) and its upper end at (2, 2)
A rectangle with a lower end at (3, 0) and its upper end at (5, 5)
A rectangle with a lower end at (6, 0) and its upper end at (6, 6)
Example 3:
>>> minRectanglesToCoverPoints(points = [[2,3],[1,2]], w = 0)
>>> 2
Explanation:
The image above shows one possible placement of rectangles to cover the points:
A rectangle with a lower end at (1, 0) and its upper end at (1, 2)
A rectangle with a lower end at (2, 0) and its upper end at (2, 3)
"""
|
minimum-time-to-visit-disappearing-nodes | def minimumTime(n: int, edges: List[List[int]], disappear: List[int]) -> List[int]:
"""
There is an undirected graph of n nodes. You are given a 2D array edges, where edges[i] = [ui, vi, lengthi] describes an edge between node ui and node vi with a traversal time of lengthi units.
Additionally, you are given an array disappear, where disappear[i] denotes the time when the node i disappears from the graph and you won't be able to visit it.
Note that the graph might be disconnected and might contain multiple edges.
Return the array answer, with answer[i] denoting the minimum units of time required to reach node i from node 0. If node i is unreachable from node 0 then answer[i] is -1.
Example 1:
>>> minimumTime(n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5])
>>> [0,-1,4]
Explanation:
We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
For node 0, we don't need any time as it is our starting point.
For node 1, we need at least 2 units of time to traverse edges[0]. Unfortunately, it disappears at that moment, so we won't be able to visit it.
For node 2, we need at least 4 units of time to traverse edges[2].
Example 2:
>>> minimumTime(n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5])
>>> [0,2,3]
Explanation:
We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
For node 0, we don't need any time as it is the starting point.
For node 1, we need at least 2 units of time to traverse edges[0].
For node 2, we need at least 3 units of time to traverse edges[0] and edges[1].
Example 3:
>>> minimumTime(n = 2, edges = [[0,1,1]], disappear = [1,1])
>>> [0,-1]
Explanation:
Exactly when we reach node 1, it disappears.
"""
|
find-the-number-of-subarrays-where-boundary-elements-are-maximum | def numberOfSubarrays(nums: List[int]) -> int:
"""
You are given an array of positive integers nums.
Return the number of subarrays of nums, where the first and the last elements of the subarray are equal to the largest element in the subarray.
Example 1:
>>> numberOfSubarrays(nums = [1,4,3,3,2])
>>> 6
Explanation:
There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
subarray [1,4,3,3,2], with its largest element 1. The first element is 1 and the last element is also 1.
subarray [1,4,3,3,2], with its largest element 4. The first element is 4 and the last element is also 4.
subarray [1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [1,4,3,3,2], with its largest element 2. The first element is 2 and the last element is also 2.
subarray [1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.
Hence, we return 6.
Example 2:
>>> numberOfSubarrays(nums = [3,3,3])
>>> 6
Explanation:
There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
subarray [3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.
Hence, we return 6.
Example 3:
>>> numberOfSubarrays(nums = [1])
>>> 1
Explanation:
There is a single subarray of nums which is [1], with its largest element 1. The first element is 1 and the last element is also 1.
Hence, we return 1.
"""
|
latest-time-you-can-obtain-after-replacing-characters | def findLatestTime(s: str) -> str:
"""
You are given a string s representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?".
12-hour times are formatted as "HH:MM", where HH is between 00 and 11, and MM is between 00 and 59. The earliest 12-hour time is 00:00, and the latest is 11:59.
You have to replace all the "?" characters in s with digits such that the time we obtain by the resulting string is a valid 12-hour format time and is the latest possible.
Return the resulting string.
Example 1:
>>> findLatestTime(s = "1?:?4")
>>> "11:54"
Explanation: The latest 12-hour format time we can achieve by replacing "?" characters is "11:54".
Example 2:
>>> findLatestTime(s = "0?:5?")
>>> "09:59"
Explanation: The latest 12-hour format time we can achieve by replacing "?" characters is "09:59".
"""
|
maximum-prime-difference | def maximumPrimeDifference(nums: List[int]) -> int:
"""
You are given an integer array nums.
Return an integer that is the maximum distance between the indices of two (not necessarily different) prime numbers in nums.
Example 1:
>>> maximumPrimeDifference(nums = [4,2,9,5,3])
>>> 3
Explanation: nums[1], nums[3], and nums[4] are prime. So the answer is |4 - 1| = 3.
Example 2:
>>> maximumPrimeDifference(nums = [4,8,2,8])
>>> 0
Explanation: nums[2] is prime. Because there is just one prime number, the answer is |2 - 2| = 0.
"""
|
kth-smallest-amount-with-single-denomination-combination | def findKthSmallest(coins: List[int], k: int) -> int:
"""
You are given an integer array coins representing coins of different denominations and an integer k.
You have an infinite number of coins of each denomination. However, you are not allowed to combine coins of different denominations.
Return the kth smallest amount that can be made using these coins.
Example 1:
>>> findKthSmallest(coins = [3,6,9], k = 3)
>>> 9
Explanation: The given coins can make the following amounts:
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.
All of the coins combined produce: 3, 6, 9, 12, 15, etc.
Example 2:
>>> findKthSmallest(coins = [5,2], k = 7)
>>> 12
Explanation: The given coins can make the following amounts:
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.
All of the coins combined produce: 2, 4, 5, 6, 8, 10, 12, 14, 15, etc.
"""
|
minimum-sum-of-values-by-dividing-array | def minimumValueSum(nums: List[int], andValues: List[int]) -> int:
"""
You are given two arrays nums and andValues of length n and m respectively.
The value of an array is equal to the last element of that array.
You have to divide nums into m disjoint contiguous subarrays such that for the ith subarray [li, ri], the bitwise AND of the subarray elements is equal to andValues[i], in other words, nums[li] & nums[li + 1] & ... & nums[ri] == andValues[i] for all 1 <= i <= m, where & represents the bitwise AND operator.
Return the minimum possible sum of the values of the m subarrays nums is divided into. If it is not possible to divide nums into m subarrays satisfying these conditions, return -1.
Example 1:
>>> minimumValueSum(nums = [1,4,3,3,2], andValues = [0,3,3,2])
>>> 12
Explanation:
The only possible way to divide nums is:
[1,4] as 1 & 4 == 0.
[3] as the bitwise AND of a single element subarray is that element itself.
[3] as the bitwise AND of a single element subarray is that element itself.
[2] as the bitwise AND of a single element subarray is that element itself.
The sum of the values for these subarrays is 4 + 3 + 3 + 2 = 12.
Example 2:
>>> minimumValueSum(nums = [2,3,5,7,7,7,5], andValues = [0,7,5])
>>> 17
Explanation:
There are three ways to divide nums:
[[2,3,5],[7,7,7],[5]] with the sum of the values 5 + 7 + 5 == 17.
[[2,3,5,7],[7,7],[5]] with the sum of the values 7 + 7 + 5 == 19.
[[2,3,5,7,7],[7],[5]] with the sum of the values 7 + 7 + 5 == 19.
The minimum possible sum of the values is 17.
Example 3:
>>> minimumValueSum(nums = [1,2,3,4], andValues = [2])
>>> -1
Explanation:
The bitwise AND of the entire array nums is 0. As there is no possible way to divide nums into a single subarray to have the bitwise AND of elements 2, return -1.
"""
|
maximum-number-of-potholes-that-can-be-fixed | def maxPotholes(road: str, budget: int) -> int:
"""
You are given a string road, consisting only of characters "x" and ".", where each "x" denotes a pothole and each "." denotes a smooth road, and an integer budget.
In one repair operation, you can repair n consecutive potholes for a price of n + 1.
Return the maximum number of potholes that can be fixed such that the sum of the prices of all of the fixes doesn't go over the given budget.
Example 1:
>>> maxPotholes(road = "..", budget = 5)
>>> 0
Explanation:
There are no potholes to be fixed.
Example 2:
>>> maxPotholes(road = "..xxxxx", budget = 4)
>>> 3
Explanation:
We fix the first three potholes (they are consecutive). The budget needed for this task is 3 + 1 = 4.
Example 3:
>>> maxPotholes(road = "x.x.xxx...x", budget = 14)
>>> 6
Explanation:
We can fix all the potholes. The total cost would be (1 + 1) + (1 + 1) + (3 + 1) + (1 + 1) = 10 which is within our budget of 14.
"""
|
count-the-number-of-special-characters-i | def numberOfSpecialChars(word: str) -> int:
"""
You are given a string word. A letter is called special if it appears both in lowercase and uppercase in word.
Return the number of special letters in word.
Example 1:
>>> numberOfSpecialChars(word = "aaAbcBC")
>>> 3
Explanation:
The special characters in word are 'a', 'b', and 'c'.
Example 2:
>>> numberOfSpecialChars(word = "abc")
>>> 0
Explanation:
No character in word appears in uppercase.
Example 3:
>>> numberOfSpecialChars(word = "abBCab")
>>> 1
Explanation:
The only special character in word is 'b'.
"""
|
count-the-number-of-special-characters-ii | def numberOfSpecialChars(word: str) -> int:
"""
You are given a string word. A letter c is called special if it appears both in lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c.
Return the number of special letters in word.
Example 1:
>>> numberOfSpecialChars(word = "aaAbcBC")
>>> 3
Explanation:
The special characters are 'a', 'b', and 'c'.
Example 2:
>>> numberOfSpecialChars(word = "abc")
>>> 0
Explanation:
There are no special characters in word.
Example 3:
>>> numberOfSpecialChars(word = "AbBCab")
>>> 0
Explanation:
There are no special characters in word.
"""
|
minimum-number-of-operations-to-satisfy-conditions | def minimumOperations(grid: List[List[int]]) -> int:
"""
You are given a 2D matrix grid of size m x n. In one operation, you can change the value of any cell to any non-negative number. You need to perform some operations such that each cell grid[i][j] is:
Equal to the cell below it, i.e. grid[i][j] == grid[i + 1][j] (if it exists).
Different from the cell to its right, i.e. grid[i][j] != grid[i][j + 1] (if it exists).
Return the minimum number of operations needed.
Example 1:
>>> minimumOperations(grid = [[1,0,2],[1,0,2]])
>>> 0
Explanation:
All the cells in the matrix already satisfy the properties.
Example 2:
>>> minimumOperations(grid = [[1,1,1],[0,0,0]])
>>> 3
Explanation:
The matrix becomes [[1,0,1],[1,0,1]] which satisfies the properties, by doing these 3 operations:
Change grid[1][0] to 1.
Change grid[0][1] to 0.
Change grid[1][2] to 1.
Example 3:
>>> minimumOperations(grid = [[1],[2],[3]])
>>> 2
Explanation:
There is a single column. We can change the value to 1 in each cell using 2 operations.
"""
|
find-edges-in-shortest-paths | def findAnswer(n: int, edges: List[List[int]]) -> List[bool]:
"""
You are given an undirected weighted graph of n nodes numbered from 0 to n - 1. The graph consists of m edges represented by a 2D array edges, where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi.
Consider all the shortest paths from node 0 to node n - 1 in the graph. You need to find a boolean array answer where answer[i] is true if the edge edges[i] is part of at least one shortest path. Otherwise, answer[i] is false.
Return the array answer.
Note that the graph may not be connected.
Example 1:
>>> findAnswer(n = 6, edges = [[0,1,4],[0,2,1],[1,3,2],[1,4,3],[1,5,1],[2,3,1],[3,5,3],[4,5,2]])
>>> [true,true,true,false,true,true,true,false]
Explanation:
The following are all the shortest paths between nodes 0 and 5:
The path 0 -> 1 -> 5: The sum of weights is 4 + 1 = 5.
The path 0 -> 2 -> 3 -> 5: The sum of weights is 1 + 1 + 3 = 5.
The path 0 -> 2 -> 3 -> 1 -> 5: The sum of weights is 1 + 1 + 2 + 1 = 5.
Example 2:
>>> findAnswer(n = 4, edges = [[2,0,1],[0,1,1],[0,3,4],[3,2,2]])
>>> [true,false,false,true]
Explanation:
There is one shortest path between nodes 0 and 3, which is the path 0 -> 2 -> 3 with the sum of weights 1 + 2 = 3.
"""
|
maximum-number-that-makes-result-of-bitwise-and-zero | def maxNumber(n: int) -> int:
"""
Given an integer n, return the maximum integer x such that x <= n, and the bitwise AND of all the numbers in the range [x, n] is 0.
Example 1:
>>> maxNumber(n = 7)
>>> 3
Explanation:
The bitwise AND of [6, 7] is 6.
The bitwise AND of [5, 6, 7] is 4.
The bitwise AND of [4, 5, 6, 7] is 4.
The bitwise AND of [3, 4, 5, 6, 7] is 0.
Example 2:
>>> maxNumber(n = 9)
>>> 7
Explanation:
The bitwise AND of [7, 8, 9] is 0.
Example 3:
>>> maxNumber(n = 17)
>>> 15
Explanation:
The bitwise AND of [15, 16, 17] is 0.
"""
|
make-a-square-with-the-same-color | def canMakeSquare(grid: List[List[str]]) -> bool:
"""
You are given a 2D matrix grid of size 3 x 3 consisting only of characters 'B' and 'W'. Character 'W' represents the white color, and character 'B' represents the black color.
Your task is to change the color of at most one cell so that the matrix has a 2 x 2 square where all cells are of the same color.
Return true if it is possible to create a 2 x 2 square of the same color, otherwise, return false.
Example 1:
>>> canMakeSquare(grid = [["B","W","B"],["B","W","W"],["B","W","B"]])
>>> true
Explanation:
It can be done by changing the color of the grid[0][2].
Example 2:
>>> canMakeSquare(grid = [["B","W","B"],["W","B","W"],["B","W","B"]])
>>> false
Explanation:
It cannot be done by changing at most one cell.
Example 3:
>>> canMakeSquare(grid = [["B","W","B"],["B","W","W"],["B","W","W"]])
>>> true
Explanation:
The grid already contains a 2 x 2 square of the same color.
"""
|
right-triangles | def numberOfRightTriangles(grid: List[List[int]]) -> int:
"""
You are given a 2D boolean matrix grid.
A collection of 3 elements of grid is a right triangle if one of its elements is in the same row with another element and in the same column with the third element. The 3 elements may not be next to each other.
Return an integer that is the number of right triangles that can be made with 3 elements of grid such that all of them have a value of 1.
Example 1:
0
1
0
0
1
1
0
1
0
0
1
0
0
1
1
0
1
0
0
1
0
0
1
1
0
1
0
>>> numberOfRightTriangles(grid = [[0,1,0],[0,1,1],[0,1,0]])
>>> 2
Explanation:
There are two right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle because the 3 elements are in the same column.
Example 2:
1
0
0
0
0
1
0
1
1
0
0
0
>>> numberOfRightTriangles(grid = [[1,0,0,0],[0,1,0,1],[1,0,0,0]])
>>> 0
Explanation:
There are no right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle.
Example 3:
1
0
1
1
0
0
1
0
0
1
0
1
1
0
0
1
0
0
>>> numberOfRightTriangles(grid = [[1,0,1],[1,0,0],[1,0,0]])
>>> 2
Explanation:
There are two right triangles with elements of the value 1.
"""
|
find-all-possible-stable-binary-arrays-i | def numberOfStableArrays(zero: int, one: int, limit: int) -> int:
"""
You are given 3 positive integers zero, one, and limit.
A binary array arr is called stable if:
The number of occurrences of 0 in arr is exactly zero.
The number of occurrences of 1 in arr is exactly one.
Each subarray of arr with a size greater than limit must contain both 0 and 1.
Return the total number of stable binary arrays.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> numberOfStableArrays(zero = 1, one = 1, limit = 2)
>>> 2
Explanation:
The two possible stable binary arrays are [1,0] and [0,1], as both arrays have a single 0 and a single 1, and no subarray has a length greater than 2.
Example 2:
>>> numberOfStableArrays(zero = 1, one = 2, limit = 1)
>>> 1
Explanation:
The only possible stable binary array is [1,0,1].
Note that the binary arrays [1,1,0] and [0,1,1] have subarrays of length 2 with identical elements, hence, they are not stable.
Example 3:
>>> numberOfStableArrays(zero = 3, one = 3, limit = 2)
>>> 14
Explanation:
All the possible stable binary arrays are [0,0,1,0,1,1], [0,0,1,1,0,1], [0,1,0,0,1,1], [0,1,0,1,0,1], [0,1,0,1,1,0], [0,1,1,0,0,1], [0,1,1,0,1,0], [1,0,0,1,0,1], [1,0,0,1,1,0], [1,0,1,0,0,1], [1,0,1,0,1,0], [1,0,1,1,0,0], [1,1,0,0,1,0], and [1,1,0,1,0,0].
"""
|
find-all-possible-stable-binary-arrays-ii | def numberOfStableArrays(zero: int, one: int, limit: int) -> int:
"""
You are given 3 positive integers zero, one, and limit.
A binary array arr is called stable if:
The number of occurrences of 0 in arr is exactly zero.
The number of occurrences of 1 in arr is exactly one.
Each subarray of arr with a size greater than limit must contain both 0 and 1.
Return the total number of stable binary arrays.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> numberOfStableArrays(zero = 1, one = 1, limit = 2)
>>> 2
Explanation:
The two possible stable binary arrays are [1,0] and [0,1].
Example 2:
>>> numberOfStableArrays(zero = 1, one = 2, limit = 1)
>>> 1
Explanation:
The only possible stable binary array is [1,0,1].
Example 3:
>>> numberOfStableArrays(zero = 3, one = 3, limit = 2)
>>> 14
Explanation:
All the possible stable binary arrays are [0,0,1,0,1,1], [0,0,1,1,0,1], [0,1,0,0,1,1], [0,1,0,1,0,1], [0,1,0,1,1,0], [0,1,1,0,0,1], [0,1,1,0,1,0], [1,0,0,1,0,1], [1,0,0,1,1,0], [1,0,1,0,0,1], [1,0,1,0,1,0], [1,0,1,1,0,0], [1,1,0,0,1,0], and [1,1,0,1,0,0].
"""
|
find-the-integer-added-to-array-i | def addedInteger(nums1: List[int], nums2: List[int]) -> int:
"""
You are given two arrays of equal length, nums1 and nums2.
Each element in nums1 has been increased (or decreased in the case of negative) by an integer, represented by the variable x.
As a result, nums1 becomes equal to nums2. Two arrays are considered equal when they contain the same integers with the same frequencies.
Return the integer x.
Example 1:
>>> addedInteger(nums1 = [2,6,4], nums2 = [9,7,5])
>>> 3
Explanation:
The integer added to each element of nums1 is 3.
Example 2:
>>> addedInteger(nums1 = [10], nums2 = [5])
>>> -5
Explanation:
The integer added to each element of nums1 is -5.
Example 3:
>>> addedInteger(nums1 = [1,1,1,1], nums2 = [1,1,1,1])
>>> 0
Explanation:
The integer added to each element of nums1 is 0.
"""
|
find-the-integer-added-to-array-ii | def minimumAddedInteger(nums1: List[int], nums2: List[int]) -> int:
"""
You are given two integer arrays nums1 and nums2.
From nums1 two elements have been removed, and all other elements have been increased (or decreased in the case of negative) by an integer, represented by the variable x.
As a result, nums1 becomes equal to nums2. Two arrays are considered equal when they contain the same integers with the same frequencies.
Return the minimum possible integer x that achieves this equivalence.
Example 1:
>>> minimumAddedInteger(nums1 = [4,20,16,12,8], nums2 = [14,18,10])
>>> -2
Explanation:
After removing elements at indices [0,4] and adding -2, nums1 becomes [18,14,10].
Example 2:
>>> minimumAddedInteger(nums1 = [3,5,5,3], nums2 = [7,7])
>>> 2
Explanation:
After removing elements at indices [0,3] and adding 2, nums1 becomes [7,7].
"""
|
minimum-array-end | def minEnd(n: int, x: int) -> int:
"""
You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.
Return the minimum possible value of nums[n - 1].
Example 1:
>>> minEnd(n = 3, x = 4)
>>> 6
Explanation:
nums can be [4,5,6] and its last element is 6.
Example 2:
>>> minEnd(n = 2, x = 7)
>>> 15
Explanation:
nums can be [7,15] and its last element is 15.
"""
|
find-the-median-of-the-uniqueness-array | def medianOfUniquenessArray(nums: List[int]) -> int:
"""
You are given an integer array nums. The uniqueness array of nums is the sorted array that contains the number of distinct elements of all the subarrays of nums. In other words, it is a sorted array consisting of distinct(nums[i..j]), for all 0 <= i <= j < nums.length.
Here, distinct(nums[i..j]) denotes the number of distinct elements in the subarray that starts at index i and ends at index j.
Return the median of the uniqueness array of nums.
Note that the median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the smaller of the two values is taken.
Example 1:
>>> medianOfUniquenessArray(nums = [1,2,3])
>>> 1
Explanation:
The uniqueness array of nums is [distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])] which is equal to [1, 1, 1, 2, 2, 3]. The uniqueness array has a median of 1. Therefore, the answer is 1.
Example 2:
>>> medianOfUniquenessArray(nums = [3,4,3,4,5])
>>> 2
Explanation:
The uniqueness array of nums is [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]. The uniqueness array has a median of 2. Therefore, the answer is 2.
Example 3:
>>> medianOfUniquenessArray(nums = [4,3,5,4])
>>> 2
Explanation:
The uniqueness array of nums is [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]. The uniqueness array has a median of 2. Therefore, the answer is 2.
"""
|
equalize-strings-by-adding-or-removing-characters-at-ends | def minOperations(initial: str, target: str) -> int:
"""
Given two strings initial and target, your task is to modify initial by performing a series of operations to make it equal to target.
In one operation, you can add or remove one character only at the beginning or the end of the string initial.
Return the minimum number of operations required to transform initial into target.
Example 1:
>>> minOperations(initial = "abcde", target = "cdef")
>>> 3
Explanation:
Remove 'a' and 'b' from the beginning of initial, then add 'f' to the end.
Example 2:
>>> minOperations(initial = "axxy", target = "yabx")
>>> 6
Explanation:
Operation
Resulting String
Add 'y' to the beginning
"yaxxy"
Remove from end
"yaxx"
Remove from end
"yax"
Remove from end
"ya"
Add 'b' to the end
"yab"
Add 'x' to the end
"yabx"
Example 3:
>>> minOperations(initial = "xyz", target = "xyz")
>>> 0
Explanation:
No operations are needed as the strings are already equal.
"""
|
valid-word | def isValid(word: str) -> bool:
"""
A word is considered valid if:
It contains a minimum of 3 characters.
It contains only digits (0-9), and English letters (uppercase and lowercase).
It includes at least one vowel.
It includes at least one consonant.
You are given a string word.
Return true if word is valid, otherwise, return false.
Notes:
'a', 'e', 'i', 'o', 'u', and their uppercases are vowels.
A consonant is an English letter that is not a vowel.
Example 1:
>>> isValid(word = "234Adas")
>>> true
Explanation:
This word satisfies the conditions.
Example 2:
>>> isValid(word = "b3")
>>> false
Explanation:
The length of this word is fewer than 3, and does not have a vowel.
Example 3:
>>> isValid(word = "a3$e")
>>> false
Explanation:
This word contains a '$' character and does not have a consonant.
"""
|
minimum-number-of-operations-to-make-word-k-periodic | def minimumOperationsToMakeKPeriodic(word: str, k: int) -> int:
"""
You are given a string word of size n, and an integer k such that k divides n.
In one operation, you can pick any two indices i and j, that are divisible by k, then replace the substring of length k starting at i with the substring of length k starting at j. That is, replace the substring word[i..i + k - 1] with the substring word[j..j + k - 1].
Return the minimum number of operations required to make word k-periodic.
We say that word is k-periodic if there is some string s of length k such that word can be obtained by concatenating s an arbitrary number of times. For example, if word == “ababab”, then word is 2-periodic for s = "ab".
Example 1:
>>> minimumOperationsToMakeKPeriodic(word = "leetcodeleet", k = 4)
>>> 1
Explanation:
We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".
Example 2:
>>> minimumOperationsToMakeKPeriodic(word = "leetcoleet", k = 2)
>>> 3
Explanation:
We can obtain a 2-periodic string by applying the operations in the table below.
i
j
word
0
2
etetcoleet
4
0
etetetleet
6
0
etetetetet
"""
|
minimum-length-of-anagram-concatenation | def minAnagramLength(s: str) -> int:
"""
You are given a string s, which is known to be a concatenation of anagrams of some string t.
Return the minimum possible length of the string t.
An anagram is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".
Example 1:
>>> minAnagramLength(s = "abba")
>>> 2
Explanation:
One possible string t could be "ba".
Example 2:
>>> minAnagramLength(s = "cdef")
>>> 4
Explanation:
One possible string t could be "cdef", notice that t can be equal to s.
Example 2:
>>> minAnagramLength(s = "abcbcacabbaccba")
>>> 3
"""
|
minimum-cost-to-equalize-array | def minCostToEqualizeArray(nums: List[int], cost1: int, cost2: int) -> int:
"""
You are given an integer array nums and two integers cost1 and cost2. You are allowed to perform either of the following operations any number of times:
Choose an index i from nums and increase nums[i] by 1 for a cost of cost1.
Choose two different indices i, j, from nums and increase nums[i] and nums[j] by 1 for a cost of cost2.
Return the minimum cost required to make all elements in the array equal.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> minCostToEqualizeArray(nums = [4,1], cost1 = 5, cost2 = 2)
>>> 15
Explanation:
The following operations can be performed to make the values equal:
Increase nums[1] by 1 for a cost of 5. nums becomes [4,2].
Increase nums[1] by 1 for a cost of 5. nums becomes [4,3].
Increase nums[1] by 1 for a cost of 5. nums becomes [4,4].
The total cost is 15.
Example 2:
>>> minCostToEqualizeArray(nums = [2,3,3,3,5], cost1 = 2, cost2 = 1)
>>> 6
Explanation:
The following operations can be performed to make the values equal:
Increase nums[0] and nums[1] by 1 for a cost of 1. nums becomes [3,4,3,3,5].
Increase nums[0] and nums[2] by 1 for a cost of 1. nums becomes [4,4,4,3,5].
Increase nums[0] and nums[3] by 1 for a cost of 1. nums becomes [5,4,4,4,5].
Increase nums[1] and nums[2] by 1 for a cost of 1. nums becomes [5,5,5,4,5].
Increase nums[3] by 1 for a cost of 2. nums becomes [5,5,5,5,5].
The total cost is 6.
Example 3:
>>> minCostToEqualizeArray(nums = [3,5,3], cost1 = 1, cost2 = 3)
>>> 4
Explanation:
The following operations can be performed to make the values equal:
Increase nums[0] by 1 for a cost of 1. nums becomes [4,5,3].
Increase nums[0] by 1 for a cost of 1. nums becomes [5,5,3].
Increase nums[2] by 1 for a cost of 1. nums becomes [5,5,4].
Increase nums[2] by 1 for a cost of 1. nums becomes [5,5,5].
The total cost is 4.
"""
|
maximum-hamming-distances | def maxHammingDistances(nums: List[int], m: int) -> List[int]:
"""
Given an array nums and an integer m, with each element nums[i] satisfying 0 <= nums[i] < 2m, return an array answer. The answer array should be of the same length as nums, where each element answer[i] represents the maximum Hamming distance between nums[i] and any other element nums[j] in the array.
The Hamming distance between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).
Example 1:
>>> maxHammingDistances(nums = [9,12,9,11], m = 4)
>>> [2,3,2,3]
Explanation:
The binary representation of nums = [1001,1100,1001,1011].
The maximum hamming distances for each index are:
nums[0]: 1001 and 1100 have a distance of 2.
nums[1]: 1100 and 1011 have a distance of 3.
nums[2]: 1001 and 1100 have a distance of 2.
nums[3]: 1011 and 1100 have a distance of 3.
Example 2:
>>> maxHammingDistances(nums = [3,4,6,10], m = 4)
>>> [3,3,2,3]
Explanation:
The binary representation of nums = [0011,0100,0110,1010].
The maximum hamming distances for each index are:
nums[0]: 0011 and 0100 have a distance of 3.
nums[1]: 0100 and 0011 have a distance of 3.
nums[2]: 0110 and 1010 have a distance of 2.
nums[3]: 1010 and 0100 have a distance of 3.
"""
|
check-if-grid-satisfies-conditions | def satisfiesConditions(grid: List[List[int]]) -> bool:
"""
You are given a 2D matrix grid of size m x n. You need to check if each cell grid[i][j] is:
Equal to the cell below it, i.e. grid[i][j] == grid[i + 1][j] (if it exists).
Different from the cell to its right, i.e. grid[i][j] != grid[i][j + 1] (if it exists).
Return true if all the cells satisfy these conditions, otherwise, return false.
Example 1:
>>> satisfiesConditions(grid = [[1,0,2],[1,0,2]])
>>> true
Explanation:
All the cells in the grid satisfy the conditions.
Example 2:
>>> satisfiesConditions(grid = [[1,1,1],[0,0,0]])
>>> false
Explanation:
All cells in the first row are equal.
Example 3:
>>> satisfiesConditions(grid = [[1],[2],[3]])
>>> false
Explanation:
Cells in the first column have different values.
"""
|
maximum-points-inside-the-square | def maxPointsInsideSquare(points: List[List[int]], s: str) -> int:
"""
You are given a 2D array points and a string s where, points[i] represents the coordinates of point i, and s[i] represents the tag of point i.
A valid square is a square centered at the origin (0, 0), has edges parallel to the axes, and does not contain two points with the same tag.
Return the maximum number of points contained in a valid square.
Note:
A point is considered to be inside the square if it lies on or within the square's boundaries.
The side length of the square can be zero.
Example 1:
>>> maxPointsInsideSquare(points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca")
>>> 2
Explanation:
The square of side length 4 covers two points points[0] and points[1].
Example 2:
>>> maxPointsInsideSquare(points = [[1,1],[-2,-2],[-2,2]], s = "abb")
>>> 1
Explanation:
The square of side length 2 covers one point, which is points[0].
Example 3:
>>> maxPointsInsideSquare(points = [[1,1],[-1,-1],[2,-2]], s = "ccd")
>>> 0
Explanation:
It's impossible to make any valid squares centered at the origin such that it covers only one point among points[0] and points[1].
"""
|
minimum-substring-partition-of-equal-character-frequency | def minimumSubstringsInPartition(s: str) -> int:
"""
Given a string s, you need to partition it into one or more balanced substrings. For example, if s == "ababcc" then ("abab", "c", "c"), ("ab", "abc", "c"), and ("ababcc") are all valid partitions, but ("a", "bab", "cc"), ("aba", "bc", "c"), and ("ab", "abcc") are not. The unbalanced substrings are bolded.
Return the minimum number of substrings that you can partition s into.
Note: A balanced string is a string where each character in the string occurs the same number of times.
Example 1:
>>> minimumSubstringsInPartition(s = "fabccddg")
>>> 3
Explanation:
We can partition the string s into 3 substrings in one of the following ways: ("fab, "ccdd", "g"), or ("fabc", "cd", "dg").
Example 2:
>>> minimumSubstringsInPartition(s = "abababaccddb")
>>> 2
Explanation:
We can partition the string s into 2 substrings like so: ("abab", "abaccddb").
"""
|
permutation-difference-between-two-strings | def findPermutationDifference(s: str, t: str) -> int:
"""
You are given two strings s and t such that every character occurs at most once in s and t is a permutation of s.
The permutation difference between s and t is defined as the sum of the absolute difference between the index of the occurrence of each character in s and the index of the occurrence of the same character in t.
Return the permutation difference between s and t.
Example 1:
>>> findPermutationDifference(s = "abc", t = "bac")
>>> 2
Explanation:
For s = "abc" and t = "bac", the permutation difference of s and t is equal to the sum of:
The absolute difference between the index of the occurrence of "a" in s and the index of the occurrence of "a" in t.
The absolute difference between the index of the occurrence of "b" in s and the index of the occurrence of "b" in t.
The absolute difference between the index of the occurrence of "c" in s and the index of the occurrence of "c" in t.
That is, the permutation difference between s and t is equal to |0 - 1| + |1 - 0| + |2 - 2| = 2.
Example 2:
>>> findPermutationDifference(s = "abcde", t = "edbac")
>>> 12
Explanation: The permutation difference between s and t is equal to |0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12.
"""
|
taking-maximum-energy-from-the-mystic-dungeon | def maximumEnergy(energy: List[int], k: int) -> int:
"""
In a mystic dungeon, n magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.
You have been cursed in such a way that after absorbing energy from magician i, you will be instantly transported to magician (i + k). This process will be repeated until you reach the magician where (i + k) does not exist.
In other words, you will choose a starting point and then teleport with k jumps until you reach the end of the magicians' sequence, absorbing all the energy during the journey.
You are given an array energy and an integer k. Return the maximum possible energy you can gain.
Note that when you are reach a magician, you must take energy from them, whether it is negative or positive energy.
Example 1:
>>> maximumEnergy(energy = [5,2,-10,-5,1], k = 3)
>>> 3
Explanation: We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.
Example 2:
>>> maximumEnergy(energy = [-2,-3,-1], k = 2)
>>> -1
Explanation: We can gain a total energy of -1 by starting from magician 2.
"""
|
maximum-difference-score-in-a-grid | def maxScore(grid: List[List[int]]) -> int:
"""
You are given an m x n matrix grid consisting of positive integers. You can move from a cell in the matrix to any other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value c1 to a cell with the value c2 is c2 - c1.
You can start at any cell, and you have to make at least one move.
Return the maximum total score you can achieve.
Example 1:
>>> maxScore(grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]])
>>> 9
Explanation: We start at the cell (0, 1), and we perform the following moves:
- Move from the cell (0, 1) to (2, 1) with a score of 7 - 5 = 2.
- Move from the cell (2, 1) to (2, 2) with a score of 14 - 7 = 7.
The total score is 2 + 7 = 9.
Example 2:
>>> maxScore(grid = [[4,3,2],[3,2,1]])
>>> -1
Explanation: We start at the cell (0, 0), and we perform one move: (0, 0) to (0, 1). The score is 3 - 4 = -1.
"""
|
find-the-minimum-cost-array-permutation | def findPermutation(nums: List[int]) -> List[int]:
"""
You are given an array nums which is a permutation of [0, 1, 2, ..., n - 1]. The score of any permutation of [0, 1, 2, ..., n - 1] named perm is defined as:
score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|
Return the permutation perm which has the minimum possible score. If multiple permutations exist with this score, return the one that is lexicographically smallest among them.
Example 1:
>>> findPermutation(nums = [1,0,2])
>>> [0,1,2]
Explanation:
The lexicographically smallest permutation with minimum cost is [0,1,2]. The cost of this permutation is |0 - 0| + |1 - 2| + |2 - 1| = 2.
Example 2:
>>> findPermutation(nums = [0,2,1])
>>> [0,2,1]
Explanation:
The lexicographically smallest permutation with minimum cost is [0,2,1]. The cost of this permutation is |0 - 1| + |2 - 2| + |1 - 0| = 2.
"""
|
special-array-i | def isArraySpecial(nums: List[int]) -> bool:
"""
An array is considered special if the parity of every pair of adjacent elements is different. In other words, one element in each pair must be even, and the other must be odd.
You are given an array of integers nums. Return true if nums is a special array, otherwise, return false.
Example 1:
>>> isArraySpecial(nums = [1])
>>> true
Explanation:
There is only one element. So the answer is true.
Example 2:
>>> isArraySpecial(nums = [2,1,4])
>>> true
Explanation:
There is only two pairs: (2,1) and (1,4), and both of them contain numbers with different parity. So the answer is true.
Example 3:
>>> isArraySpecial(nums = [4,3,1,6])
>>> false
Explanation:
nums[1] and nums[2] are both odd. So the answer is false.
"""
|
special-array-ii | def isArraySpecial(nums: List[int], queries: List[List[int]]) -> List[bool]:
"""
An array is considered special if every pair of its adjacent elements contains two numbers with different parity.
You are given an array of integer nums and a 2D integer matrix queries, where for queries[i] = [fromi, toi] your task is to check that subarray nums[fromi..toi] is special or not.
Return an array of booleans answer such that answer[i] is true if nums[fromi..toi] is special.
Example 1:
>>> isArraySpecial(nums = [3,4,1,2,6], queries = [[0,4]])
>>> [false]
Explanation:
The subarray is [3,4,1,2,6]. 2 and 6 are both even.
Example 2:
>>> isArraySpecial(nums = [4,3,1,6], queries = [[0,2],[2,3]])
>>> [false,true]
Explanation:
The subarray is [4,3,1]. 3 and 1 are both odd. So the answer to this query is false.
The subarray is [1,6]. There is only one pair: (1,6) and it contains numbers with different parity. So the answer to this query is true.
"""
|
sum-of-digit-differences-of-all-pairs | def sumDigitDifferences(nums: List[int]) -> int:
"""
You are given an array nums consisting of positive integers where all integers have the same number of digits.
The digit difference between two integers is the count of different digits that are in the same position in the two integers.
Return the sum of the digit differences between all pairs of integers in nums.
Example 1:
>>> sumDigitDifferences(nums = [13,23,12])
>>> 4
Explanation:
We have the following:
- The digit difference between 13 and 23 is 1.
- The digit difference between 13 and 12 is 1.
- The digit difference between 23 and 12 is 2.
So the total sum of digit differences between all pairs of integers is 1 + 1 + 2 = 4.
Example 2:
>>> sumDigitDifferences(nums = [10,10,10,10])
>>> 0
Explanation:
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.
"""
|
find-number-of-ways-to-reach-the-k-th-stair | def waysToReachStair(k: int) -> int:
"""
You are given a non-negative integer k. There exists a staircase with an infinite number of stairs, with the lowest stair numbered 0.
Alice has an integer jump, with an initial value of 0. She starts on stair 1 and wants to reach stair k using any number of operations. If she is on stair i, in one operation she can:
Go down to stair i - 1. This operation cannot be used consecutively or on stair 0.
Go up to stair i + 2jump. And then, jump becomes jump + 1.
Return the total number of ways Alice can reach stair k.
Note that it is possible that Alice reaches the stair k, and performs some operations to reach the stair k again.
Example 1:
>>> waysToReachStair(k = 0)
>>> 2
Explanation:
The 2 possible ways of reaching stair 0 are:
Alice starts at stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Alice starts at stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Using an operation of the second type, she goes up 20 stairs to reach stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Example 2:
>>> waysToReachStair(k = 1)
>>> 4
Explanation:
The 4 possible ways of reaching stair 1 are:
Alice starts at stair 1. Alice is at stair 1.
Alice starts at stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Using an operation of the second type, she goes up 20 stairs to reach stair 1.
Alice starts at stair 1.
Using an operation of the second type, she goes up 20 stairs to reach stair 2.
Using an operation of the first type, she goes down 1 stair to reach stair 1.
Alice starts at stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Using an operation of the second type, she goes up 20 stairs to reach stair 1.
Using an operation of the first type, she goes down 1 stair to reach stair 0.
Using an operation of the second type, she goes up 21 stairs to reach stair 2.
Using an operation of the first type, she goes down 1 stair to reach stair 1.
"""
|
maximum-number-of-upgradable-servers | def maxUpgrades(count: List[int], upgrade: List[int], sell: List[int], money: List[int]) -> List[int]:
"""
You have n data centers and need to upgrade their servers.
You are given four arrays count, upgrade, sell, and money of length n, which show:
The number of servers
The cost of upgrading a single server
The money you get by selling a server
The money you initially have
for each data center respectively.
Return an array answer, where for each data center, the corresponding element in answer represents the maximum number of servers that can be upgraded.
Note that the money from one data center cannot be used for another data center.
Example 1:
>>> maxUpgrades(count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9])
>>> [3,2]
Explanation:
For the first data center, if we sell one server, we'll have 8 + 4 = 12 units of money and we can upgrade the remaining 3 servers.
For the second data center, if we sell one server, we'll have 9 + 2 = 11 units of money and we can upgrade the remaining 2 servers.
Example 2:
>>> maxUpgrades(count = [1], upgrade = [2], sell = [1], money = [1])
>>> [0]
"""
|
find-the-level-of-tree-with-minimum-sum | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minimumLevel(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree root where each node has a value, return the level of the tree that has the minimum sum of values among all the levels (in case of a tie, return the lowest level).
Note that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.
Example 1:
>>> __init__(root = [50,6,2,30,80,7])
>>> 2
Explanation:
Example 2:
>>> __init__(root = [36,17,10,null,null,24])
>>> 3
Explanation:
Example 3:
>>> __init__(root = [5,null,5,null,5])
>>> 1
Explanation:
"""
|
find-the-xor-of-numbers-which-appear-twice | def duplicateNumbersXOR(nums: List[int]) -> int:
"""
You are given an array nums, where each number in the array appears either once or twice.
Return the bitwise XOR of all the numbers that appear twice in the array, or 0 if no number appears twice.
Example 1:
>>> duplicateNumbersXOR(nums = [1,2,1,3])
>>> 1
Explanation:
The only number that appears twice in nums is 1.
Example 2:
>>> duplicateNumbersXOR(nums = [1,2,3])
>>> 0
Explanation:
No number appears twice in nums.
Example 3:
>>> duplicateNumbersXOR(nums = [1,2,2,1])
>>> 3
Explanation:
Numbers 1 and 2 appeared twice. 1 XOR 2 == 3.
"""
|
find-occurrences-of-an-element-in-an-array | def occurrencesOfElement(nums: List[int], queries: List[int], x: int) -> List[int]:
"""
You are given an integer array nums, an integer array queries, and an integer x.
For each queries[i], you need to find the index of the queries[i]th occurrence of x in the nums array. If there are fewer than queries[i] occurrences of x, the answer should be -1 for that query.
Return an integer array answer containing the answers to all queries.
Example 1:
>>> occurrencesOfElement(nums = [1,3,1,7], queries = [1,3,2,4], x = 1)
>>> [0,-1,2,-1]
Explanation:
For the 1st query, the first occurrence of 1 is at index 0.
For the 2nd query, there are only two occurrences of 1 in nums, so the answer is -1.
For the 3rd query, the second occurrence of 1 is at index 2.
For the 4th query, there are only two occurrences of 1 in nums, so the answer is -1.
Example 2:
>>> occurrencesOfElement(nums = [1,2,3], queries = [10], x = 5)
>>> [-1]
Explanation:
For the 1st query, 5 doesn't exist in nums, so the answer is -1.
"""
|
find-the-number-of-distinct-colors-among-the-balls | def queryResults(limit: int, queries: List[List[int]]) -> List[int]:
"""
You are given an integer limit and a 2D array queries of size n x 2.
There are limit + 1 balls with distinct labels in the range [0, limit]. Initially, all balls are uncolored. For every query in queries that is of the form [x, y], you mark ball x with the color y. After each query, you need to find the number of colors among the balls.
Return an array result of length n, where result[i] denotes the number of colors after ith query.
Note that when answering a query, lack of a color will not be considered as a color.
Example 1:
>>> queryResults(limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]])
>>> [1,2,2,3]
Explanation:
After query 0, ball 1 has color 4.
After query 1, ball 1 has color 4, and ball 2 has color 5.
After query 2, ball 1 has color 3, and ball 2 has color 5.
After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.
Example 2:
>>> queryResults(limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]])
>>> [1,2,2,3,4]
Explanation:
After query 0, ball 0 has color 1.
After query 1, ball 0 has color 1, and ball 1 has color 2.
After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.
After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.
After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.
"""
|
block-placement-queries | def getResults(queries: List[List[int]]) -> List[bool]:
"""
There exists an infinite number line, with its origin at 0 and extending towards the positive x-axis.
You are given a 2D array queries, which contains two types of queries:
For a query of type 1, queries[i] = [1, x]. Build an obstacle at distance x from the origin. It is guaranteed that there is no obstacle at distance x when the query is asked.
For a query of type 2, queries[i] = [2, x, sz]. Check if it is possible to place a block of size sz anywhere in the range [0, x] on the line, such that the block entirely lies in the range [0, x]. A block cannot be placed if it intersects with any obstacle, but it may touch it. Note that you do not actually place the block. Queries are separate.
Return a boolean array results, where results[i] is true if you can place the block specified in the ith query of type 2, and false otherwise.
Example 1:
>>> getResults(queries = [[1,2],[2,3,3],[2,3,1],[2,2,2]])
>>> [false,true,true]
Explanation:
For query 0, place an obstacle at x = 2. A block of size at most 2 can be placed before x = 3.
Example 2:
>>> getResults(queries = [[1,7],[2,7,6],[1,2],[2,7,5],[2,7,6]])
>>> [true,true,false]
Explanation:
Place an obstacle at x = 7 for query 0. A block of size at most 7 can be placed before x = 7.
Place an obstacle at x = 2 for query 2. Now, a block of size at most 5 can be placed before x = 7, and a block of size at most 2 before x = 2.
"""
|
find-the-number-of-good-pairs-i | def numberOfPairs(nums1: List[int], nums2: List[int], k: int) -> int:
"""
You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k.
A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k (0 <= i <= n - 1, 0 <= j <= m - 1).
Return the total number of good pairs.
Example 1:
>>> numberOfPairs(nums1 = [1,3,4], nums2 = [1,3,4], k = 1)
>>> 5
Explanation:
The 5 good pairs are (0, 0), (1, 0), (1, 1), (2, 0), and (2, 2).
Example 2:
>>> numberOfPairs(nums1 = [1,2,4,12], nums2 = [2,4], k = 3)
>>> 2
Explanation:
The 2 good pairs are (3, 0) and (3, 1).
"""
|
string-compression-iii | def compressedString(word: str) -> str:
"""
Given a string word, compress it using the following algorithm:
Begin with an empty string comp. While word is not empty, use the following operation:
Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
Append the length of the prefix followed by c to comp.
Return the string comp.
Example 1:
>>> compressedString(word = "abcde")
>>> "1a1b1c1d1e"
Explanation:
Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.
For each prefix, append "1" followed by the character to comp.
Example 2:
>>> compressedString(word = "aaaaaaaaaaaaaabb")
>>> "9a5a2b"
Explanation:
Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.
For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
For prefix "aaaaa", append "5" followed by "a" to comp.
For prefix "bb", append "2" followed by "b" to comp.
"""
|
find-the-number-of-good-pairs-ii | def numberOfPairs(nums1: List[int], nums2: List[int], k: int) -> int:
"""
You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k.
A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k (0 <= i <= n - 1, 0 <= j <= m - 1).
Return the total number of good pairs.
Example 1:
>>> numberOfPairs(nums1 = [1,3,4], nums2 = [1,3,4], k = 1)
>>> 5
Explanation:
The 5 good pairs are (0, 0), (1, 0), (1, 1), (2, 0), and (2, 2).
Example 2:
>>> numberOfPairs(nums1 = [1,2,4,12], nums2 = [2,4], k = 3)
>>> 2
Explanation:
The 2 good pairs are (3, 0) and (3, 1).
"""
|
maximum-sum-of-subsequence-with-non-adjacent-elements | def maximumSumSubsequence(nums: List[int], queries: List[List[int]]) -> int:
"""
You are given an array nums consisting of integers. You are also given a 2D array queries, where queries[i] = [posi, xi].
For query i, we first set nums[posi] equal to xi, then we calculate the answer to query i which is the maximum sum of a subsequence of nums where no two adjacent elements are selected.
Return the sum of the answers to all queries.
Since the final answer may be very large, return it modulo 109 + 7.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
>>> maximumSumSubsequence(nums = [3,5,9], queries = [[1,-2],[0,-3]])
>>> 21
Explanation:
After the 1st query, nums = [3,-2,9] and the maximum sum of a subsequence with non-adjacent elements is 3 + 9 = 12.
After the 2nd query, nums = [-3,-2,9] and the maximum sum of a subsequence with non-adjacent elements is 9.
Example 2:
>>> maximumSumSubsequence(nums = [0,-1], queries = [[0,-5]])
>>> 0
Explanation:
After the 1st query, nums = [-5,-1] and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).
"""
|
better-compression-of-string | def betterCompression(compressed: str) -> str:
"""
You are given a string compressed representing a compressed version of a string. The format is a character followed by its frequency. For example, "a3b1a1c2" is a compressed version of the string "aaabacc".
We seek a better compression with the following conditions:
Each character should appear only once in the compressed version.
The characters should be in alphabetical order.
Return the better compression of compressed.
Note: In the better version of compression, the order of letters may change, which is acceptable.
Example 1:
>>> betterCompression(compressed = "a3c9b2c1")
>>> "a3b2c10"
Explanation:
Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.
Hence, in the resulting string, it should have a size of 10.
Example 2:
>>> betterCompression(compressed = "c2b3a1")
>>> "a1b3c2"
Example 3:
>>> betterCompression(compressed = "a2b4c1")
>>> "a2b4c1"
"""
|
minimum-number-of-chairs-in-a-waiting-room | def minimumChairs(s: str) -> int:
"""
You are given a string s. Simulate events at each second i:
If s[i] == 'E', a person enters the waiting room and takes one of the chairs in it.
If s[i] == 'L', a person leaves the waiting room, freeing up a chair.
Return the minimum number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially empty.
Example 1:
>>> minimumChairs(s = "EEEEEEE")
>>> 7
Explanation:
After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.
Example 2:
>>> minimumChairs(s = "ELELEEL")
>>> 2
Explanation:
Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.
Second
Event
People in the Waiting Room
Available Chairs
0
Enter
1
1
1
Leave
0
2
2
Enter
1
1
3
Leave
0
2
4
Enter
1
1
5
Enter
2
0
6
Leave
1
1
Example 3:
>>> minimumChairs(s = "ELEELEELLL")
>>> 3
Explanation:
Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.
Second
Event
People in the Waiting Room
Available Chairs
0
Enter
1
2
1
Leave
0
3
2
Enter
1
2
3
Enter
2
1
4
Leave
1
2
5
Enter
2
1
6
Enter
3
0
7
Leave
2
1
8
Leave
1
2
9
Leave
0
3
"""
|
count-days-without-meetings | def countDays(days: int, meetings: List[List[int]]) -> int:
"""
You are given a positive integer days representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array meetings of size n where, meetings[i] = [start_i, end_i] represents the starting and ending days of meeting i (inclusive).
Return the count of days when the employee is available for work but no meetings are scheduled.
Note: The meetings may overlap.
Example 1:
>>> countDays(days = 10, meetings = [[5,7],[1,3],[9,10]])
>>> 2
Explanation:
There is no meeting scheduled on the 4th and 8th days.
Example 2:
>>> countDays(days = 5, meetings = [[2,4],[1,3]])
>>> 1
Explanation:
There is no meeting scheduled on the 5th day.
Example 3:
>>> countDays(days = 6, meetings = [[1,6]])
>>> 0
Explanation:
Meetings are scheduled for all working days.
"""
|
lexicographically-minimum-string-after-removing-stars | def clearStars(s: str) -> str:
"""
You are given a string s. It may contain any number of '*' characters. Your task is to remove all '*' characters.
While there is a '*', do the following operation:
Delete the leftmost '*' and the smallest non-'*' character to its left. If there are several smallest characters, you can delete any of them.
Return the lexicographically smallest resulting string after removing all '*' characters.
Example 1:
>>> clearStars(s = "aaba*")
>>> "aab"
Explanation:
We should delete one of the 'a' characters with '*'. If we choose s[3], s becomes the lexicographically smallest.
Example 2:
>>> clearStars(s = "abc")
>>> "abc"
Explanation:
There is no '*' in the string.
"""
|
find-subarray-with-bitwise-or-closest-to-k | def minimumDifference(nums: List[int], k: int) -> int:
"""
You are given an array nums and an integer k. You need to find a subarray of nums such that the absolute difference between k and the bitwise OR of the subarray elements is as small as possible. In other words, select a subarray nums[l..r] such that |k - (nums[l] OR nums[l + 1] ... OR nums[r])| is minimum.
Return the minimum possible value of the absolute difference.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
>>> minimumDifference(nums = [1,2,4,5], k = 3)
>>> 0
Explanation:
The subarray nums[0..1] has OR value 3, which gives the minimum absolute difference |3 - 3| = 0.
Example 2:
>>> minimumDifference(nums = [1,3,1,3], k = 2)
>>> 1
Explanation:
The subarray nums[1..1] has OR value 3, which gives the minimum absolute difference |3 - 2| = 1.
Example 3:
>>> minimumDifference(nums = [1], k = 10)
>>> 9
Explanation:
There is a single subarray with OR value 1, which gives the minimum absolute difference |10 - 1| = 9.
"""
|
bitwise-or-of-adjacent-elements | def orArray(nums: List[int]) -> List[int]:
"""
Given an array nums of length n, return an array answer of length n - 1 such that answer[i] = nums[i] | nums[i + 1] where | is the bitwise OR operation.
Example 1:
>>> orArray(nums = [1,3,7,15])
>>> [3,7,15]
Example 2:
>>> orArray(nums = [8,4,2])
>>> [12,6]
Example 3:
>>> orArray(nums = [5,4,9,11])
>>> [5,13,11]
"""
|
clear-digits | def clearDigits(s: str) -> str:
"""
You are given a string s.
Your task is to remove all digits by doing this operation repeatedly:
Delete the first digit and the closest non-digit character to its left.
Return the resulting string after removing all digits.
Note that the operation cannot be performed on a digit that does not have any non-digit character to its left.
Example 1:
>>> clearDigits(s = "abc")
>>> "abc"
Explanation:
There is no digit in the string.
Example 2:
>>> clearDigits(s = "cb34")
>>> ""
Explanation:
First, we apply the operation on s[2], and s becomes "c4".
Then we apply the operation on s[1], and s becomes "".
"""
|
find-the-first-player-to-win-k-games-in-a-row | def findWinningPlayer(skills: List[int], k: int) -> int:
"""
A competition consists of n players numbered from 0 to n - 1.
You are given an integer array skills of size n and a positive integer k, where skills[i] is the skill level of player i. All integers in skills are unique.
All players are standing in a queue in order from player 0 to player n - 1.
The competition process is as follows:
The first two players in the queue play a game, and the player with the higher skill level wins.
After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.
The winner of the competition is the first player who wins k games in a row.
Return the initial index of the winning player.
Example 1:
>>> findWinningPlayer(skills = [4,2,6,3,9], k = 2)
>>> 2
Explanation:
Initially, the queue of players is [0,1,2,3,4]. The following process happens:
Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is [0,2,3,4,1].
Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is [2,3,4,1,0].
Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is [2,4,1,0,3].
Player 2 won k = 2 games in a row, so the winner is player 2.
Example 2:
>>> findWinningPlayer(skills = [2,5,4], k = 3)
>>> 1
Explanation:
Initially, the queue of players is [0,1,2]. The following process happens:
Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is [1,2,0].
Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is [1,0,2].
Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is [1,2,0].
Player 1 won k = 3 games in a row, so the winner is player 1.
"""
|
find-the-maximum-length-of-a-good-subsequence-i | def maximumLength(nums: List[int], k: int) -> int:
"""
You are given an integer array nums and a non-negative integer k. A sequence of integers seq is called good if there are at most k indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1].
Return the maximum possible length of a good subsequence of nums.
Example 1:
>>> maximumLength(nums = [1,2,1,1,3], k = 2)
>>> 4
Explanation:
The maximum length subsequence is [1,2,1,1,3].
Example 2:
>>> maximumLength(nums = [1,2,3,4,5,1], k = 0)
>>> 2
Explanation:
The maximum length subsequence is [1,2,3,4,5,1].
"""
|
find-the-maximum-length-of-a-good-subsequence-ii | def maximumLength(nums: List[int], k: int) -> int:
"""
You are given an integer array nums and a non-negative integer k. A sequence of integers seq is called good if there are at most k indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1].
Return the maximum possible length of a good subsequence of nums.
Example 1:
>>> maximumLength(nums = [1,2,1,1,3], k = 2)
>>> 4
Explanation:
The maximum length subsequence is [1,2,1,1,3].
Example 2:
>>> maximumLength(nums = [1,2,3,4,5,1], k = 0)
>>> 2
Explanation:
The maximum length subsequence is [1,2,3,4,5,1].
"""
|
find-the-child-who-has-the-ball-after-k-seconds | def numberOfChild(n: int, k: int) -> int:
"""
You are given two positive integers n and k. There are n children numbered from 0 to n - 1 standing in a queue in order from left to right.
Initially, child 0 holds a ball and the direction of passing the ball is towards the right direction. After each second, the child holding the ball passes it to the child next to them. Once the ball reaches either end of the line, i.e. child 0 or child n - 1, the direction of passing is reversed.
Return the number of the child who receives the ball after k seconds.
Example 1:
>>> numberOfChild(n = 3, k = 5)
>>> 1
Explanation:
Time elapsed
Children
0
[0, 1, 2]
1
[0, 1, 2]
2
[0, 1, 2]
3
[0, 1, 2]
4
[0, 1, 2]
5
[0, 1, 2]
Example 2:
>>> numberOfChild(n = 5, k = 6)
>>> 2
Explanation:
Time elapsed
Children
0
[0, 1, 2, 3, 4]
1
[0, 1, 2, 3, 4]
2
[0, 1, 2, 3, 4]
3
[0, 1, 2, 3, 4]
4
[0, 1, 2, 3, 4]
5
[0, 1, 2, 3, 4]
6
[0, 1, 2, 3, 4]
Example 3:
>>> numberOfChild(n = 4, k = 2)
>>> 2
Explanation:
Time elapsed
Children
0
[0, 1, 2, 3]
1
[0, 1, 2, 3]
2
[0, 1, 2, 3]
"""
|
find-the-n-th-value-after-k-seconds | def valueAfterKSeconds(n: int, k: int) -> int:
"""
You are given two integers n and k.
Initially, you start with an array a of n integers where a[i] = 1 for all 0 <= i <= n - 1. After each second, you simultaneously update each element to be the sum of all its preceding elements plus the element itself. For example, after one second, a[0] remains the same, a[1] becomes a[0] + a[1], a[2] becomes a[0] + a[1] + a[2], and so on.
Return the value of a[n - 1] after k seconds.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> valueAfterKSeconds(n = 4, k = 5)
>>> 56
Explanation:
Second
State After
0
[1,1,1,1]
1
[1,2,3,4]
2
[1,3,6,10]
3
[1,4,10,20]
4
[1,5,15,35]
5
[1,6,21,56]
Example 2:
>>> valueAfterKSeconds(n = 5, k = 3)
>>> 35
Explanation:
Second
State After
0
[1,1,1,1,1]
1
[1,2,3,4,5]
2
[1,3,6,10,15]
3
[1,4,10,20,35]
"""
|
maximum-total-reward-using-operations-i | def maxTotalReward(rewardValues: List[int]) -> int:
"""
You are given an integer array rewardValues of length n, representing the values of rewards.
Initially, your total reward x is 0, and all indices are unmarked. You are allowed to perform the following operation any number of times:
Choose an unmarked index i from the range [0, n - 1].
If rewardValues[i] is greater than your current total reward x, then add rewardValues[i] to x (i.e., x = x + rewardValues[i]), and mark the index i.
Return an integer denoting the maximum total reward you can collect by performing the operations optimally.
Example 1:
>>> maxTotalReward(rewardValues = [1,1,3,3])
>>> 4
Explanation:
During the operations, we can choose to mark the indices 0 and 2 in order, and the total reward will be 4, which is the maximum.
Example 2:
>>> maxTotalReward(rewardValues = [1,6,4,3,2])
>>> 11
Explanation:
Mark the indices 0, 2, and 1 in order. The total reward will then be 11, which is the maximum.
"""
|
maximum-total-reward-using-operations-ii | def maxTotalReward(rewardValues: List[int]) -> int:
"""
You are given an integer array rewardValues of length n, representing the values of rewards.
Initially, your total reward x is 0, and all indices are unmarked. You are allowed to perform the following operation any number of times:
Choose an unmarked index i from the range [0, n - 1].
If rewardValues[i] is greater than your current total reward x, then add rewardValues[i] to x (i.e., x = x + rewardValues[i]), and mark the index i.
Return an integer denoting the maximum total reward you can collect by performing the operations optimally.
Example 1:
>>> maxTotalReward(rewardValues = [1,1,3,3])
>>> 4
Explanation:
During the operations, we can choose to mark the indices 0 and 2 in order, and the total reward will be 4, which is the maximum.
Example 2:
>>> maxTotalReward(rewardValues = [1,6,4,3,2])
>>> 11
Explanation:
Mark the indices 0, 2, and 1 in order. The total reward will then be 11, which is the maximum.
"""
|
the-number-of-ways-to-make-the-sum | def numberOfWays(n: int) -> int:
"""
You have an infinite number of coins with values 1, 2, and 6, and only 2 coins with value 4.
Given an integer n, return the number of ways to make the sum of n with the coins you have.
Since the answer may be very large, return it modulo 109 + 7.
Note that the order of the coins doesn't matter and [2, 2, 3] is the same as [2, 3, 2].
Example 1:
>>> numberOfWays(n = 4)
>>> 4
Explanation:
Here are the four combinations: [1, 1, 1, 1], [1, 1, 2], [2, 2], [4].
Example 2:
>>> numberOfWays(n = 12)
>>> 22
Explanation:
Note that [4, 4, 4] is not a valid combination since we cannot use 4 three times.
Example 3:
>>> numberOfWays(n = 5)
>>> 4
Explanation:
Here are the four combinations: [1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 2], [1, 4].
"""
|
count-pairs-that-form-a-complete-day-i | def countCompleteDayPairs(hours: List[int]) -> int:
"""
Given an integer array hours representing times in hours, return an integer denoting the number of pairs i, j where i < j and hours[i] + hours[j] forms a complete day.
A complete day is defined as a time duration that is an exact multiple of 24 hours.
For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
Example 1:
>>> countCompleteDayPairs(hours = [12,12,30,24,24])
>>> 2
Explanation:
The pairs of indices that form a complete day are (0, 1) and (3, 4).
Example 2:
>>> countCompleteDayPairs(hours = [72,48,24,3])
>>> 3
Explanation:
The pairs of indices that form a complete day are (0, 1), (0, 2), and (1, 2).
"""
|
count-pairs-that-form-a-complete-day-ii | def countCompleteDayPairs(hours: List[int]) -> int:
"""
Given an integer array hours representing times in hours, return an integer denoting the number of pairs i, j where i < j and hours[i] + hours[j] forms a complete day.
A complete day is defined as a time duration that is an exact multiple of 24 hours.
For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
Example 1:
>>> countCompleteDayPairs(hours = [12,12,30,24,24])
>>> 2
Explanation: The pairs of indices that form a complete day are (0, 1) and (3, 4).
Example 2:
>>> countCompleteDayPairs(hours = [72,48,24,3])
>>> 3
Explanation: The pairs of indices that form a complete day are (0, 1), (0, 2), and (1, 2).
"""
|
maximum-total-damage-with-spell-casting | def maximumTotalDamage(power: List[int]) -> int:
"""
A magician has various spells.
You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value.
It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.
Each spell can be cast only once.
Return the maximum possible total damage that a magician can cast.
Example 1:
>>> maximumTotalDamage(power = [1,1,3,4])
>>> 6
Explanation:
The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.
Example 2:
>>> maximumTotalDamage(power = [7,1,6,6])
>>> 13
Explanation:
The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.
"""
|
peaks-in-array | def countOfPeaks(nums: List[int], queries: List[List[int]]) -> List[int]:
"""
A peak in an array arr is an element that is greater than its previous and next element in arr.
You are given an integer array nums and a 2D integer array queries.
You have to process queries of two types:
queries[i] = [1, li, ri], determine the count of peak elements in the subarray nums[li..ri].
queries[i] = [2, indexi, vali], change nums[indexi] to vali.
Return an array answer containing the results of the queries of the first type in order.
Notes:
The first and the last element of an array or a subarray cannot be a peak.
Example 1:
>>> countOfPeaks(nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]])
>>> [0]
Explanation:
First query: We change nums[3] to 4 and nums becomes [3,1,4,4,5].
Second query: The number of peaks in the [3,1,4,4,5] is 0.
Example 2:
>>> countOfPeaks(nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]])
>>> [0,1]
Explanation:
First query: nums[2] should become 4, but it is already set to 4.
Second query: The number of peaks in the [4,1,4] is 0.
Third query: The second 4 is a peak in the [4,1,4,2,1].
"""
|
minimum-moves-to-get-a-peaceful-board | def minMoves(rooks: List[List[int]]) -> int:
"""
Given a 2D array rooks of length n, where rooks[i] = [xi, yi] indicates the position of a rook on an n x n chess board. Your task is to move the rooks 1 cell at a time vertically or horizontally (to an adjacent cell) such that the board becomes peaceful.
A board is peaceful if there is exactly one rook in each row and each column.
Return the minimum number of moves required to get a peaceful board.
Note that at no point can there be two rooks in the same cell.
Example 1:
>>> minMoves(rooks = [[0,0],[1,0],[1,1]])
>>> 3
Explanation:
Example 2:
>>> minMoves(rooks = [[0,0],[0,1],[0,2],[0,3]])
>>> 6
Explanation:
"""
|
find-minimum-operations-to-make-all-elements-divisible-by-three | def minimumOperations(nums: List[int]) -> int:
"""
You are given an integer array nums. In one operation, you can add or subtract 1 from any element of nums.
Return the minimum number of operations to make all elements of nums divisible by 3.
Example 1:
>>> minimumOperations(nums = [1,2,3,4])
>>> 3
Explanation:
All array elements can be made divisible by 3 using 3 operations:
Subtract 1 from 1.
Add 1 to 2.
Subtract 1 from 4.
Example 2:
>>> minimumOperations(nums = [3,6,9])
>>> 0
"""
|
minimum-operations-to-make-binary-array-elements-equal-to-one-i | def minOperations(nums: List[int]) -> int:
"""
You are given a binary array nums.
You can do the following operation on the array any number of times (possibly zero):
Choose any 3 consecutive elements from the array and flip all of them.
Flipping an element means changing its value from 0 to 1, and from 1 to 0.
Return the minimum number of operations required to make all elements in nums equal to 1. If it is impossible, return -1.
Example 1:
>>> minOperations(nums = [0,1,1,1,0,0])
>>> 3
Explanation:
We can do the following operations:
Choose the elements at indices 0, 1 and 2. The resulting array is nums = [1,0,0,1,0,0].
Choose the elements at indices 1, 2 and 3. The resulting array is nums = [1,1,1,0,0,0].
Choose the elements at indices 3, 4 and 5. The resulting array is nums = [1,1,1,1,1,1].
Example 2:
>>> minOperations(nums = [0,1,1,1])
>>> -1
Explanation:
It is impossible to make all elements equal to 1.
"""
|
minimum-operations-to-make-binary-array-elements-equal-to-one-ii | def minOperations(nums: List[int]) -> int:
"""
You are given a binary array nums.
You can do the following operation on the array any number of times (possibly zero):
Choose any index i from the array and flip all the elements from index i to the end of the array.
Flipping an element means changing its value from 0 to 1, and from 1 to 0.
Return the minimum number of operations required to make all elements in nums equal to 1.
Example 1:
>>> minOperations(nums = [0,1,1,0,1])
>>> 4
Explanation:
We can do the following operations:
Choose the index i = 1. The resulting array will be nums = [0,0,0,1,0].
Choose the index i = 0. The resulting array will be nums = [1,1,1,0,1].
Choose the index i = 4. The resulting array will be nums = [1,1,1,0,0].
Choose the index i = 3. The resulting array will be nums = [1,1,1,1,1].
Example 2:
>>> minOperations(nums = [1,0,0,0])
>>> 1
Explanation:
We can do the following operation:
Choose the index i = 1. The resulting array will be nums = [1,1,1,1].
"""
|
count-the-number-of-inversions | def numberOfPermutations(n: int, requirements: List[List[int]]) -> int:
"""
You are given an integer n and a 2D array requirements, where requirements[i] = [endi, cnti] represents the end index and the inversion count of each requirement.
A pair of indices (i, j) from an integer array nums is called an inversion if:
i < j and nums[i] > nums[j]
Return the number of permutations perm of [0, 1, 2, ..., n - 1] such that for all requirements[i], perm[0..endi] has exactly cnti inversions.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> numberOfPermutations(n = 3, requirements = [[2,2],[0,0]])
>>> 2
Explanation:
The two permutations are:
[2, 0, 1]
Prefix [2, 0, 1] has inversions (0, 1) and (0, 2).
Prefix [2] has 0 inversions.
[1, 2, 0]
Prefix [1, 2, 0] has inversions (0, 2) and (1, 2).
Prefix [1] has 0 inversions.
Example 2:
>>> numberOfPermutations(n = 3, requirements = [[2,2],[1,1],[0,0]])
>>> 1
Explanation:
The only satisfying permutation is [2, 0, 1]:
Prefix [2, 0, 1] has inversions (0, 1) and (0, 2).
Prefix [2, 0] has an inversion (0, 1).
Prefix [2] has 0 inversions.
Example 3:
>>> numberOfPermutations(n = 2, requirements = [[0,0],[1,0]])
>>> 1
Explanation:
The only satisfying permutation is [0, 1]:
Prefix [0] has 0 inversions.
Prefix [0, 1] has an inversion (0, 1).
"""
|
minimum-average-of-smallest-and-largest-elements | def minimumAverage(nums: List[int]) -> float:
"""
You have an array of floating point numbers averages which is initially empty. You are given an array nums of n integers where n is even.
You repeat the following procedure n / 2 times:
Remove the smallest element, minElement, and the largest element maxElement, from nums.
Add (minElement + maxElement) / 2 to averages.
Return the minimum element in averages.
Example 1:
>>> minimumAverage(nums = [7,8,3,4,15,13,4,1])
>>> 5.5
Explanation:
step
nums
averages
0
[7,8,3,4,15,13,4,1]
[]
1
[7,8,3,4,13,4]
[8]
2
[7,8,4,4]
[8,8]
3
[7,4]
[8,8,6]
4
[]
[8,8,6,5.5]
The smallest element of averages, 5.5, is returned.
Example 2:
>>> minimumAverage(nums = [1,9,8,3,10,5])
>>> 5.5
Explanation:
step
nums
averages
0
[1,9,8,3,10,5]
[]
1
[9,8,3,5]
[5.5]
2
[8,5]
[5.5,6]
3
[]
[5.5,6,6.5]
Example 3:
>>> minimumAverage(nums = [1,2,3,7,8,9])
>>> 5.0
Explanation:
step
nums
averages
0
[1,2,3,7,8,9]
[]
1
[2,3,7,8]
[5]
2
[3,7]
[5,5]
3
[]
[5,5,5]
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.