problem_title
stringlengths 3
77
| python_solutions
stringlengths 81
8.45k
| post_href
stringlengths 64
213
| upvotes
int64 0
1.2k
| question
stringlengths 0
3.6k
| post_title
stringlengths 2
100
| views
int64 1
60.9k
| slug
stringlengths 3
77
| acceptance
float64 0.14
0.91
| user
stringlengths 3
26
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
| number
int64 1
2.48k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum number of operations to make arrays similar | class Solution:
def makeSimilar(self, A: List[int], B: List[int]) -> int:
if sum(A)!=sum(B): return 0
# The first intuition is that only odd numbers can be chaged to odd numbers and even to even hence separate them
# Now minimum steps to making the target to highest number in B is by converting max of A to max of B similarily
# every number in A can be paired with a number in B by index hence sorting
# now we need only the number of positives or number of negatives.
oddA,evenA=[i for i in A if i%2],[i for i in A if i%2==0]
oddB,evenB=[i for i in B if i%2],[i for i in B if i%2==0]
oddA.sort(),evenA.sort()
oddB.sort(),evenB.sort()
res=0
for i,j in zip(oddA,oddB):
if i>=j: res+=i-j
for i,j in zip(evenA,evenB):
if i>=j: res+=i-j
return res//2 | https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/discuss/2734139/Python-or-Simple-OddEven-Sorting-O(nlogn)-or-Walmart-OA-India-or-Simple-Explanation | 3 | You are given two positive integer arrays nums and target, of the same length.
In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:
set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the same.
Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.
Example 1:
Input: nums = [8,12,6], target = [2,14,10]
Output: 2
Explanation: It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = [10,12,4].
- Choose i = 1 and j = 2, nums = [10,14,2].
It can be shown that 2 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,5], target = [4,1,3]
Output: 1
Explanation: We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = [1,4,3].
Example 3:
Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0
Explanation: The array nums is already similiar to target.
Constraints:
n == nums.length == target.length
1 <= n <= 105
1 <= nums[i], target[i] <= 106
It is possible to make nums similar to target. | Python | Simple Odd/Even Sorting O(nlogn) | Walmart OA India | Simple Explanation | 245 | minimum-number-of-operations-to-make-arrays-similar | 0.649 | tarushfx | Hard | 33,552 | 2,449 |
odd string difference | class Solution:
def oddString(self, words: List[str]) -> str:
k=len(words[0])
arr=[]
for i in words:
l=[]
for j in range(1,k):
diff=ord(i[j])-ord(i[j-1])
l.append(diff)
arr.append(l)
for i in range(len(arr)):
if arr.count(arr[i])==1:
return words[i] | https://leetcode.com/problems/odd-string-difference/discuss/2774188/Easy-to-understand-python-solution | 2 | You are given an array of equal-length strings words. Assume that the length of each string is n.
Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.
For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1].
All the strings in words have the same difference integer array, except one. You should find that string.
Return the string in words that has different difference integer array.
Example 1:
Input: words = ["adc","wzy","abc"]
Output: "abc"
Explanation:
- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].
- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1].
- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1].
The odd array out is [1, 1], so we return the corresponding string, "abc".
Example 2:
Input: words = ["aaa","bob","ccc","ddd"]
Output: "bob"
Explanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].
Constraints:
3 <= words.length <= 100
n == words[i].length
2 <= n <= 20
words[i] consists of lowercase English letters. | Easy to understand python solution | 87 | odd-string-difference | 0.595 | Vistrit | Easy | 33,559 | 2,451 |
words within two edits of dictionary | class Solution:
def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:
# T: ((N + M) * L^3), S: O(M * L^3)
N, M, L = len(queries), len(dictionary), len(queries[0])
validWords = set()
for word in dictionary:
for w in self.wordModifications(word):
validWords.add(w)
ans = []
for word in queries:
for w in self.wordModifications(word):
if w in validWords:
ans.append(word)
break
return ans
def wordModifications(self, word):
# T: O(L^3)
L = len(word)
for i in range(L):
yield word[:i] + "*" + word[i+1:]
for i, j in itertools.combinations(range(L), 2):
yield word[:i] + "*" + word[i+1:j] + "*" + word[j+1:] | https://leetcode.com/problems/words-within-two-edits-of-dictionary/discuss/2757378/Python-Simple-HashSet-solution-O((N%2BM)-*-L3) | 2 | You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.
In one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word from dictionary.
Return a list of all words from queries, that match with some word from dictionary after a maximum of two edits. Return the words in the same order they appear in queries.
Example 1:
Input: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
Output: ["word","note","wood"]
Explanation:
- Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood".
- Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke".
- It would take more than 2 edits for "ants" to equal a dictionary word.
- "wood" can remain unchanged (0 edits) and match the corresponding dictionary word.
Thus, we return ["word","note","wood"].
Example 2:
Input: queries = ["yes"], dictionary = ["not"]
Output: []
Explanation:
Applying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.
Constraints:
1 <= queries.length, dictionary.length <= 100
n == queries[i].length == dictionary[j].length
1 <= n <= 100
All queries[i] and dictionary[j] are composed of lowercase English letters. | [Python] Simple HashSet solution O((N+M) * L^3) | 45 | words-within-two-edits-of-dictionary | 0.603 | rcomesan | Medium | 33,583 | 2,452 |
destroy sequential targets | class Solution:
def destroyTargets(self, nums: List[int], space: int) -> int:
# example: nums = [3,7,8,1,1,5], space = 2
groups = defaultdict(list)
for num in nums:
groups[num % space].append(num)
# print(groups) # defaultdict(<class 'list'>, {1: [3, 7, 1, 1, 5], 0: [8]}) groups is [3, 7, 1, 1, 5] and [8]
""" min of [3, 7, 1, 1, 5] can destroy all others (greedy approach) => 1 can destory 1,3,5,7 ... """
performance = defaultdict(list)
for group in groups.values():
performance[len(group)].append(min(group))
# print(performance) # defaultdict(<class 'list'>, {5: [1], 1: [8]})
# nums that can destory 5 targets are [1], nums that can destory 1 target are [8]
return min(performance[max(performance)]) | https://leetcode.com/problems/destroy-sequential-targets/discuss/2756374/Python-or-Greedy-or-Group-or-Example | 3 | You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer. You want to destroy the maximum number of targets in nums.
Return the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.
Example 1:
Input: nums = [3,7,8,1,1,5], space = 2
Output: 1
Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...
In this case, we would destroy 5 total targets (all except for nums[2]).
It is impossible to destroy more than 5 targets, so we return nums[3].
Example 2:
Input: nums = [1,3,5,2,4,6], space = 2
Output: 1
Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets.
It is not possible to destroy more than 3 targets.
Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.
Example 3:
Input: nums = [6,2,5], space = 100
Output: 2
Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= space <= 109 | Python | Greedy | Group | Example | 122 | destroy-sequential-targets | 0.373 | yzhao156 | Medium | 33,608 | 2,453 |
next greater element iv | class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
ans = [-1] * len(nums)
s, ss = [], []
for i, x in enumerate(nums):
while ss and nums[ss[-1]] < x: ans[ss.pop()] = x
buff = []
while s and nums[s[-1]] < x: buff.append(s.pop())
while buff: ss.append(buff.pop())
s.append(i)
return ans | https://leetcode.com/problems/next-greater-element-iv/discuss/2757259/Python3-intermediate-stack | 1 | You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > i
nums[j] > nums[i]
There exists exactly one index k such that nums[k] > nums[i] and i < k < j.
If there is no such nums[j], the second greater integer is considered to be -1.
For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109 | [Python3] intermediate stack | 38 | next-greater-element-iv | 0.396 | ye15 | Hard | 33,619 | 2,454 |
average value of even numbers that are divisible by three | class Solution:
def averageValue(self, nums: List[int]) -> int:
l=[]
for i in nums:
if i%6==0:
l.append(i)
return sum(l)//len(l) if len(l)>0 else 0 | https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/discuss/2770799/Easy-Python-Solution | 2 | Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.
Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
Example 1:
Input: nums = [1,3,6,10,12,15]
Output: 9
Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.
Example 2:
Input: nums = [1,2,4,7,10]
Output: 0
Explanation: There is no single number that satisfies the requirement, so return 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000 | Easy Python Solution | 107 | average-value-of-even-numbers-that-are-divisible-by-three | 0.58 | Vistrit | Easy | 33,623 | 2,455 |
most popular video creator | class Solution:
def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:
memo = {}
#tracking the max popular video count
overall_max_popular_video_count = -1
#looping over the creators
for i in range(len(creators)):
if creators[i] in memo:
#Step 1: update number of views for the creator
memo[creators[i]][0] += views[i]
#Step 2: update current_popular_video_view and id_of_most_popular_video_so_far
if memo[creators[i]][2] < views[i]:
memo[creators[i]][1] = ids[i]
memo[creators[i]][2] = views[i]
#Step 2a: finding the lexicographically smallest id as we hit the current_popularity_video_view again!
elif memo[creators[i]][2] == views[i]:
memo[creators[i]][1] = min(memo[creators[i]][1],ids[i])
else:
#adding new entry to our memo
#new entry is of the format memo[creator[i]] = [total number current views for the creator, store the lexicographic id of the popular video, current popular view of the creator]
memo[creators[i]] = [views[i],ids[i],views[i]]
#track the max popular video count
overall_max_popular_video_count = max(memo[creators[i]][0],overall_max_popular_video_count)
result = []
for i in memo:
if memo[i][0] == overall_max_popular_video_count:
result.append([i,memo[i][1]])
return result | https://leetcode.com/problems/most-popular-video-creator/discuss/2758104/Python-Hashmap-solution-or-No-Sorting | 5 | You are given two string arrays creators and ids, and an integer array views, all of length n. The ith video on a platform was created by creator[i], has an id of ids[i], and has views[i] views.
The popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highest popularity and the id of their most viewed video.
If multiple creators have the highest popularity, find all of them.
If multiple videos have the highest view count for a creator, find the lexicographically smallest id.
Return a 2D array of strings answer where answer[i] = [creatori, idi] means that creatori has the highest popularity and idi is the id of their most popular video. The answer can be returned in any order.
Example 1:
Input: creators = ["alice","bob","alice","chris"], ids = ["one","two","three","four"], views = [5,10,5,4]
Output: [["alice","one"],["bob","two"]]
Explanation:
The popularity of alice is 5 + 5 = 10.
The popularity of bob is 10.
The popularity of chris is 4.
alice and bob are the most popular creators.
For bob, the video with the highest view count is "two".
For alice, the videos with the highest view count are "one" and "three". Since "one" is lexicographically smaller than "three", it is included in the answer.
Example 2:
Input: creators = ["alice","alice","alice"], ids = ["a","b","c"], views = [1,2,2]
Output: [["alice","b"]]
Explanation:
The videos with id "b" and "c" have the highest view count.
Since "b" is lexicographically smaller than "c", it is included in the answer.
Constraints:
n == creators.length == ids.length == views.length
1 <= n <= 105
1 <= creators[i].length, ids[i].length <= 5
creators[i] and ids[i] consist only of lowercase English letters.
0 <= views[i] <= 105 | Python Hashmap solution | No Sorting | 330 | most-popular-video-creator | 0.441 | dee7 | Medium | 33,656 | 2,456 |
minimum addition to make integer beautiful | class Solution:
def makeIntegerBeautiful(self, n: int, target: int) -> int:
i=n
l=1
while i<=10**12:
s=0
for j in str(i):
s+=int(j)
if s<=target:
return i-n
i//=10**l
i+=1
i*=10**l
l+=1 | https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/discuss/2758079/Check-next-10-next-100-next-1000-and-so-on... | 2 | You are given two positive integers n and target.
An integer is considered beautiful if the sum of its digits is less than or equal to target.
Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.
Example 1:
Input: n = 16, target = 6
Output: 4
Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.
Example 2:
Input: n = 467, target = 6
Output: 33
Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.
Example 3:
Input: n = 1, target = 1
Output: 0
Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.
Constraints:
1 <= n <= 1012
1 <= target <= 150
The input will be generated such that it is always possible to make n beautiful. | Check next 10, next 100, next 1000 and so on... | 97 | minimum-addition-to-make-integer-beautiful | 0.368 | shreyasjain0912 | Medium | 33,677 | 2,457 |
height of binary tree after subtree removal queries | class Solution:
def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
depth = {}
height = {}
nodes_at_depth = {}
max_height = 0
def rec(n, d):
nonlocal max_height
if n is None:
return 0
height_below = max(rec(n.left, d+1), rec(n.right, d+1))
v = n.val
depth[v] = d
h = d + 1 + height_below
height[v] = h
max_height = max(max_height, h)
if d not in nodes_at_depth:
nodes_at_depth[d] = [v]
else:
nodes_at_depth[d].append(v)
return 1 + height_below
rec(root, -1) # subtract one because the problem reports heights weird
ret = []
for q in queries:
if height[q] >= max_height:
d = depth[q]
for cousin in nodes_at_depth[depth[q]]:
if cousin != q: # don't count self, obviously
d = max(d, height[cousin])
ret.append(d)
else:
ret.append(max_height)
return ret | https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/discuss/2760795/Python3-Triple-dict-depth-height-nodes_at_depth | 0 | You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m.
You have to perform m independent queries on the tree where in the ith query you do the following:
Remove the subtree rooted at the node with the value queries[i] from the tree. It is guaranteed that queries[i] will not be equal to the value of the root.
Return an array answer of size m where answer[i] is the height of the tree after performing the ith query.
Note:
The queries are independent, so the tree returns to its initial state after each query.
The height of a tree is the number of edges in the longest simple path from the root to some node in the tree.
Example 1:
Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]
Output: [2]
Explanation: The diagram above shows the tree after removing the subtree rooted at node with value 4.
The height of the tree is 2 (The path 1 -> 3 -> 2).
Example 2:
Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]
Output: [3,2,3,2]
Explanation: We have the following queries:
- Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4).
- Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1).
- Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6).
- Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).
Constraints:
The number of nodes in the tree is n.
2 <= n <= 105
1 <= Node.val <= n
All the values in the tree are unique.
m == queries.length
1 <= m <= min(n, 104)
1 <= queries[i] <= n
queries[i] != root.val | Python3 Triple dict depth, height, nodes_at_depth | 12 | height-of-binary-tree-after-subtree-removal-queries | 0.354 | godshiva | Hard | 33,696 | 2,458 |
apply operations to an array | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]*=2
nums[i+1]=0
temp = []
zeros = []
a=nums
for i in range(len(a)):
if a[i] !=0:
temp.append(a[i])
else:
zeros.append(a[i])
return (temp+zeros) | https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786435/Python-Simple-Python-Solution-89-ms | 3 | You are given a 0-indexed array nums of size n consisting of non-negative integers.
You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:
If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.
After performing all the operations, shift all the 0's to the end of the array.
For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].
Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Example 1:
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.
Constraints:
2 <= nums.length <= 2000
0 <= nums[i] <= 1000 | [ Python ] 🐍🐍 Simple Python Solution ✅✅ 89 ms | 31 | apply-operations-to-an-array | 0.671 | sourav638 | Easy | 33,698 | 2,460 |
maximum sum of distinct subarrays with length k | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = collections.Counter(nums[:k]) #from collections import Counter (elements and their respective count are stored as a dictionary)
summ = sum(nums[:k])
res = 0
if len(seen) == k:
res = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i-k]
seen[nums[i]] += 1
seen[nums[i-k]] -= 1
if seen[nums[i-k]] == 0:
del seen[nums[i-k]]
if len(seen) == k:
res = max(res, summ)
return res | https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783646/Python-easy-solution-using-libraries | 4 | You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:
The length of the subarray is k, and
All the elements of the subarray are distinct.
Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,5,4,2,9,9,9], k = 3
Output: 15
Explanation: The subarrays of nums with length 3 are:
- [1,5,4] which meets the requirements and has a sum of 10.
- [5,4,2] which meets the requirements and has a sum of 11.
- [4,2,9] which meets the requirements and has a sum of 15.
- [2,9,9] which does not meet the requirements because the element 9 is repeated.
- [9,9,9] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions
Example 2:
Input: nums = [4,4,4], k = 3
Output: 0
Explanation: The subarrays of nums with length 3 are:
- [4,4,4] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 105 | ✅✅Python easy solution using libraries | 224 | maximum-sum-of-distinct-subarrays-with-length-k | 0.344 | Sumit6258 | Medium | 33,748 | 2,461 |
total cost to hire k workers | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
q = costs[:candidates]
qq = costs[max(candidates, len(costs)-candidates):]
heapify(q)
heapify(qq)
ans = 0
i, ii = candidates, len(costs)-candidates-1
for _ in range(k):
if not qq or q and q[0] <= qq[0]:
ans += heappop(q)
if i <= ii:
heappush(q, costs[i])
i += 1
else:
ans += heappop(qq)
if i <= ii:
heappush(qq, costs[ii])
ii -= 1
return ans | https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783147/Python3-priority-queues | 24 | You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.
You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:
You will run k sessions and hire exactly one worker in each session.
In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.
For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].
In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.
If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
A worker can only be chosen once.
Return the total cost to hire exactly k workers.
Example 1:
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
Example 2:
Input: costs = [1,2,4,1], k = 3, candidates = 3
Output: 4
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
The total hiring cost is 4.
Constraints:
1 <= costs.length <= 105
1 <= costs[i] <= 105
1 <= k, candidates <= costs.length | [Python3] priority queues | 1,200 | total-cost-to-hire-k-workers | 0.374 | ye15 | Medium | 33,780 | 2,462 |
minimum total distance traveled | class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
robot.sort()
factory.sort()
m, n = len(robot), len(factory)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m): dp[i][-1] = inf
for j in range(n-1, -1, -1):
prefix = 0
qq = deque([(m, 0)])
for i in range(m-1, -1, -1):
prefix += abs(robot[i] - factory[j][0])
if qq[0][0] > i+factory[j][1]: qq.popleft()
while qq and qq[-1][1] >= dp[i][j+1] - prefix: qq.pop()
qq.append((i, dp[i][j+1] - prefix))
dp[i][j] = qq[0][1] + prefix
return dp[0][0] | https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783245/Python3-O(MN)-DP | 13 | There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.
The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.
All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.
At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.
Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.
Note that
All robots move at the same speed.
If two robots move in the same direction, they will never collide.
If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
If the robot moved from a position x to a position y, the distance it moved is |y - x|.
Example 1:
Input: robot = [0,4,6], factory = [[2,2],[6,2]]
Output: 4
Explanation: As shown in the figure:
- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.
- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.
- The third robot at position 6 will be repaired at the second factory. It does not need to move.
The limit of the first factory is 2, and it fixed 2 robots.
The limit of the second factory is 2, and it fixed 1 robot.
The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
Example 2:
Input: robot = [1,-1], factory = [[-2,1],[2,1]]
Output: 2
Explanation: As shown in the figure:
- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.
- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.
The limit of the first factory is 1, and it fixed 1 robot.
The limit of the second factory is 1, and it fixed 1 robot.
The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.
Constraints:
1 <= robot.length, factory.length <= 100
factory[j].length == 2
-109 <= robot[i], positionj <= 109
0 <= limitj <= robot.length
The input will be generated such that it is always possible to repair every robot. | [Python3] O(MN) DP | 769 | minimum-total-distance-traveled | 0.397 | ye15 | Hard | 33,799 | 2,463 |
number of distinct averages | class Solution:
def distinctAverages(self, nums: List[int]) -> int:
av=[]
nums.sort()
while nums:
av.append((nums[-1]+nums[0])/2)
nums.pop(-1)
nums.pop(0)
return len(set(av)) | https://leetcode.com/problems/number-of-distinct-averages/discuss/2817811/Easy-Python-Solution | 2 | You are given a 0-indexed integer array nums of even length.
As long as nums is not empty, you must repetitively:
Find the minimum number in nums and remove it.
Find the maximum number in nums and remove it.
Calculate the average of the two removed numbers.
The average of two numbers a and b is (a + b) / 2.
For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.
Return the number of distinct averages calculated using the above process.
Note that when there is a tie for a minimum or maximum number, any can be removed.
Example 1:
Input: nums = [4,1,4,0,3,5]
Output: 2
Explanation:
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.
Example 2:
Input: nums = [1,100]
Output: 1
Explanation:
There is only one average to be calculated after removing 1 and 100, so we return 1.
Constraints:
2 <= nums.length <= 100
nums.length is even.
0 <= nums[i] <= 100 | Easy Python Solution | 75 | number-of-distinct-averages | 0.588 | Vistrit | Easy | 33,805 | 2,465 |
count ways to build good strings | class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
def recursive(s,ans):
if len(s)>=low and len(s)<=high:
ans+=[s]
if len(s)>high:
return
recursive(s+"0"*zero,ans)
recursive(s+"1"*one,ans)
return
ans=[]
recursive("",ans)
return len(ans) | https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3 | 1 | Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
Append the character '0' zero times.
Append the character '1' one times.
This can be performed any number of times.
A good string is a string constructed by the above process having a length between low and high (inclusive).
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.
Example 1:
Input: low = 3, high = 3, zero = 1, one = 1
Output: 8
Explanation:
One possible valid good string is "011".
It can be constructed as follows: "" -> "0" -> "01" -> "011".
All binary strings from "000" to "111" are good strings in this example.
Example 2:
Input: low = 2, high = 3, zero = 1, one = 2
Output: 5
Explanation: The good strings are "00", "11", "000", "110", and "011".
Constraints:
1 <= low <= high <= 105
1 <= zero, one <= low | Easy solution from Recursion to memoization || 3 approaches || PYTHON3 | 32 | count-ways-to-build-good-strings | 0.419 | dabbiruhaneesh | Medium | 33,846 | 2,466 |
most profitable path in a tree | class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
path_b = set([bob])
lvl_b = {bob:0}
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
n = len(amount)
node_lvl = [0] * n
q = deque([0])
lvl = 0
seen = set([0])
while q:
size = len(q)
for _ in range(size):
u = q.popleft()
node_lvl[u] = lvl
for v in g[u]:
if v in seen:
continue
q.append(v)
seen.add(v)
lvl += 1
b = bob
lvl = 1
while b != 0:
for v in g[b]:
if node_lvl[v] > node_lvl[b]:
continue
b = v
cost = amount[b]
path_b.add(b)
lvl_b[b] = lvl
break
lvl += 1
# print(f"lvl_b {lvl_b} path_b {path_b} ")
cost_a = []
q = deque([(0, amount[0])])
seen = set([0])
lvl = 1
while q:
size = len(q)
for _ in range(size):
u, pre_cost = q.popleft()
child_cnt = 0
for v in g[u]:
if v in seen:
continue
seen.add(v)
child_cnt += 1
cost = pre_cost
inc = amount[v]
if v in path_b:
if lvl_b[v] == lvl:
cost += inc//2
elif lvl_b[v] > lvl:
cost += inc
else:
cost += 0
else:
cost += amount[v]
q.append((v, cost))
if child_cnt == 0:
cost_a.append(pre_cost)
lvl += 1
ans = max(cost_a)
return ans | https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2838006/BFS-%2B-Graph-%2B-level-O(n) | 0 | There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:
the price needed to open the gate at node i, if amount[i] is negative, or,
the cash reward obtained on opening the gate at node i, otherwise.
The game goes on as follows:
Initially, Alice is at node 0 and Bob is at node bob.
At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.
For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
If the gate is already open, no price will be required, nor will there be any cash reward.
If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.
If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.
Return the maximum net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output: 6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output: -7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= bob < n
amount.length == n
amount[i] is an even integer in the range [-104, 104]. | BFS + Graph + level, O(n) | 2 | most-profitable-path-in-a-tree | 0.464 | goodgoodwish | Medium | 33,859 | 2,467 |
split message based on limit | class Solution:
def splitMessage(self, message: str, limit: int) -> List[str]:
def splitable_within(parts_limit):
# check the message length achievable with <parts_limit> parts
length = sum(limit - len(str(i)) - len(str(parts_limit)) - 3 for i in range(1, parts_limit + 1))
return length >= len(message)
parts_limit = 9
if not splitable_within(parts_limit):
parts_limit = 99
if not splitable_within(parts_limit):
parts_limit = 999
if not splitable_within(parts_limit):
parts_limit = 9999
if not splitable_within(parts_limit):
return []
# generate the actual message parts
parts = []
m_index = 0 # message index
for part_index in range(1, parts_limit + 1):
if m_index >= len(message): break
length = limit - len(str(part_index)) - len(str(parts_limit)) - 3
parts.append(message[m_index:m_index + length])
m_index += length
return [f'{part}<{i + 1}/{len(parts)}>' for i, part in enumerate(parts)] | https://leetcode.com/problems/split-message-based-on-limit/discuss/2807491/Python-Simple-dumb-O(N)-solution | 2 | You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.
Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.
Example 1:
Input: message = "this is really a very awesome message", limit = 9
Output: ["thi<1/14>","s i<2/14>","s r<3/14>","eal<4/14>","ly <5/14>","a v<6/14>","ery<7/14>"," aw<8/14>","eso<9/14>","me<10/14>"," m<11/14>","es<12/14>","sa<13/14>","ge<14/14>"]
Explanation:
The first 9 parts take 3 characters each from the beginning of message.
The next 5 parts take 2 characters each to finish splitting message.
In this example, each part, including the last, has length 9.
It can be shown it is not possible to split message into less than 14 parts.
Example 2:
Input: message = "short message", limit = 15
Output: ["short mess<1/2>","age<2/2>"]
Explanation:
Under the given constraints, the string can be split into two parts:
- The first part comprises of the first 10 characters, and has a length 15.
- The next part comprises of the last 3 characters, and has a length 8.
Constraints:
1 <= message.length <= 104
message consists only of lowercase English letters and ' '.
1 <= limit <= 104 | [Python] Simple dumb O(N) solution | 62 | split-message-based-on-limit | 0.483 | vudinhhung942k | Hard | 33,868 | 2,468 |
convert the temperature | class Solution:
def convertTemperature(self, celsius: float) -> List[float]:
return [(celsius + 273.15),(celsius * 1.80 + 32.00)] | https://leetcode.com/problems/convert-the-temperature/discuss/2839560/Python-or-Easy-Solution | 4 | You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].
Return the array ans. Answers within 10-5 of the actual answer will be accepted.
Note that:
Kelvin = Celsius + 273.15
Fahrenheit = Celsius * 1.80 + 32.00
Example 1:
Input: celsius = 36.50
Output: [309.65000,97.70000]
Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70.
Example 2:
Input: celsius = 122.11
Output: [395.26000,251.79800]
Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798.
Constraints:
0 <= celsius <= 1000 | Python | Easy Solution✔ | 127 | convert-the-temperature | 0.909 | manayathgeorgejames | Easy | 33,880 | 2,469 |
number of subarrays with lcm equal to k | class Solution:
def subarrayLCM(self, nums: List[int], k: int) -> int:
def find_lcm(num1, num2):
if(num1>num2):
num = num1
den = num2
else:
num = num2
den = num1
rem = num % den
while(rem != 0):
num = den
den = rem
rem = num % den
gcd = den
lcm = int(int(num1 * num2)/int(gcd))
return lcm
count=0
for i in range(len(nums)):
lcm=1
for j in range(i,len(nums)):
lcm=find_lcm(nums[j],lcm)
if lcm==k:
count+=1
if lcm>k:
break
return count | https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808943/Beginners-Approach-%3A | 1 | Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.
Example 1:
Input: nums = [3,6,2,7,1], k = 6
Output: 4
Explanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are:
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
Example 2:
Input: nums = [3], k = 2
Output: 0
Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i], k <= 1000 | Beginners Approach : | 57 | number-of-subarrays-with-lcm-equal-to-k | 0.388 | goxy_coder | Medium | 33,919 | 2,470 |
minimum number of operations to sort a binary tree by level | class Solution:
def minimumOperations(self, root: Optional[TreeNode]) -> int:
ans = 0
queue = deque([root])
while queue:
vals = []
for _ in range(len(queue)):
node = queue.popleft()
vals.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
mp = {x : i for i, x in enumerate(sorted(vals))}
visited = [0]*len(vals)
for i in range(len(vals)):
cnt = 0
while not visited[i] and i != mp[vals[i]]:
visited[i] = 1
cnt += 1
i = mp[vals[i]]
ans += max(0, cnt-1)
return ans | https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2808960/Python3-BFS | 6 | You are given the root of a binary tree with unique values.
In one operation, you can choose any two nodes at the same level and swap their values.
Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.
The level of a node is the number of edges along the path between it and the root node.
Example 1:
Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]
Output: 3
Explanation:
- Swap 4 and 3. The 2nd level becomes [3,4].
- Swap 7 and 5. The 3rd level becomes [5,6,8,7].
- Swap 8 and 7. The 3rd level becomes [5,6,7,8].
We used 3 operations so return 3.
It can be proven that 3 is the minimum number of operations needed.
Example 2:
Input: root = [1,3,2,7,6,5,4]
Output: 3
Explanation:
- Swap 3 and 2. The 2nd level becomes [2,3].
- Swap 7 and 4. The 3rd level becomes [4,6,5,7].
- Swap 6 and 5. The 3rd level becomes [4,5,6,7].
We used 3 operations so return 3.
It can be proven that 3 is the minimum number of operations needed.
Example 3:
Input: root = [1,2,3,4,5,6]
Output: 0
Explanation: Each level is already sorted in increasing order so return 0.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 105
All the values of the tree are unique. | [Python3] BFS | 567 | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0.629 | ye15 | Medium | 33,930 | 2,471 |
maximum number of non overlapping palindrome substrings | class Solution:
def maxPalindromes(self, s: str, k: int) -> int:
n = len(s)
dp = [0] * (n + 1)
for i in range(k, n + 1):
dp[i] = dp[i - 1]
for length in range(k, k + 2):
j = i - length
if j < 0:
break
if self.isPalindrome(s, j, i):
dp[i] = max(dp[i], 1 + dp[j])
return dp[-1]
def isPalindrome(self, s, j, i):
left, right = j, i - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True | https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2808845/Python3-DP-with-Explanations-or-Only-Check-Substrings-of-Length-k-and-k-%2B-1 | 11 | You are given a string s and a positive integer k.
Select a set of non-overlapping substrings from the string s that satisfy the following conditions:
The length of each substring is at least k.
Each substring is a palindrome.
Return the maximum number of substrings in an optimal selection.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abaccdbbd", k = 3
Output: 2
Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3.
It can be shown that we cannot find a selection with more than two valid substrings.
Example 2:
Input: s = "adbcda", k = 2
Output: 0
Explanation: There is no palindrome substring of length at least 2 in the string.
Constraints:
1 <= k <= s.length <= 2000
s consists of lowercase English letters. | [Python3] DP with Explanations | Only Check Substrings of Length k and k + 1 | 542 | maximum-number-of-non-overlapping-palindrome-substrings | 0.366 | xil899 | Hard | 33,937 | 2,472 |
number of unequal triplets in array | class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
c = Counter(nums)
res = 0
left = 0
right = len(nums)
for _, freq in c.items():
right -= freq
res += left * freq * right
left += freq
return res | https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834169/Python-Hashmap-O(n)-with-diagrams | 10 | You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:
0 <= i < j < k < nums.length
nums[i], nums[j], and nums[k] are pairwise distinct.
In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].
Return the number of triplets that meet the conditions.
Example 1:
Input: nums = [4,4,2,4,3]
Output: 3
Explanation: The following triplets meet the conditions:
- (0, 2, 4) because 4 != 2 != 3
- (1, 2, 4) because 4 != 2 != 3
- (2, 3, 4) because 2 != 4 != 3
Since there are 3 triplets, we return 3.
Note that (2, 0, 4) is not a valid triplet because 2 > 0.
Example 2:
Input: nums = [1,1,1,1,1]
Output: 0
Explanation: No triplets meet the conditions so we return 0.
Constraints:
3 <= nums.length <= 100
1 <= nums[i] <= 1000 | Python Hashmap O(n) with diagrams | 242 | number-of-unequal-triplets-in-array | 0.699 | cheatcode-ninja | Easy | 33,956 | 2,475 |
closest nodes queries in a binary search tree | class Solution(object):
def closestNodes(self, root, queries):
def dfs(root, arr):
if not root: return
dfs(root.left, arr)
arr.append(root.val)
dfs(root.right, arr)
arr = []
dfs(root, arr)
ans = []
n = len(arr)
for key in queries:
left, right = 0, n - 1
while right >= left:
mid = (right + left) // 2
if arr[mid] == key:
break
elif arr[mid] > key:
right = mid - 1
else:
left = mid + 1
if arr[mid] == key:
ans.append([arr[mid], arr[mid]])
elif arr[mid] > key:
if (mid - 1) >= 0:
ans.append([arr[mid - 1], arr[mid]])
else:
ans.append([-1, arr[mid]])
else:
if (mid + 1) < n:
ans.append([arr[mid], arr[mid + 1]])
else:
ans.append([arr[mid], -1])
return ans | https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831726/Binary-Search-Approach-or-Python | 11 | You are given the root of a binary search tree and an array queries of size n consisting of positive integers.
Find a 2D array answer of size n where answer[i] = [mini, maxi]:
mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead.
maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead.
Return the array answer.
Example 1:
Input: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]
Output: [[2,2],[4,6],[15,-1]]
Explanation: We answer the queries in the following way:
- The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2].
- The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6].
- The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].
Example 2:
Input: root = [4,null,9], queries = [3]
Output: [[-1,4]]
Explanation: The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].
Constraints:
The number of nodes in the tree is in the range [2, 105].
1 <= Node.val <= 106
n == queries.length
1 <= n <= 105
1 <= queries[i] <= 106 | Binary Search Approach | Python | 975 | closest-nodes-queries-in-a-binary-search-tree | 0.404 | its_krish_here | Medium | 33,977 | 2,476 |
minimum fuel cost to report to the capital | class Solution:
def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:
n = len(roads) + 1
graph = defaultdict(list)
for a, b in roads:
graph[a].append(b)
graph[b].append(a)
def dfs(u, p):
cnt = 1
for v in graph[u]:
if v == p: continue
cnt += dfs(v, u)
if u != 0:
self.ans += math.ceil(cnt / seats) # number of litters for `cnt` people to travel from node `u` to node `p`
return cnt
self.ans = 0
dfs(0, -1)
return self.ans | https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2834516/Python-DFS-Picture-explanation-O(N) | 33 | There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
There is a meeting for the representatives of each city. The meeting is in the capital city.
There is a car in each city. You are given an integer seats that indicates the number of seats in each car.
A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Input: roads = [[0,1],[0,2],[0,3]], seats = 5
Output: 3
Explanation:
- Representative1 goes directly to the capital with 1 liter of fuel.
- Representative2 goes directly to the capital with 1 liter of fuel.
- Representative3 goes directly to the capital with 1 liter of fuel.
It costs 3 liters of fuel at minimum.
It can be proven that 3 is the minimum number of liters of fuel needed.
Example 2:
Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
Output: 7
Explanation:
- Representative2 goes directly to city 3 with 1 liter of fuel.
- Representative2 and representative3 go together to city 1 with 1 liter of fuel.
- Representative2 and representative3 go together to the capital with 1 liter of fuel.
- Representative1 goes directly to the capital with 1 liter of fuel.
- Representative5 goes directly to the capital with 1 liter of fuel.
- Representative6 goes directly to city 4 with 1 liter of fuel.
- Representative4 and representative6 go together to the capital with 1 liter of fuel.
It costs 7 liters of fuel at minimum.
It can be proven that 7 is the minimum number of liters of fuel needed.
Example 3:
Input: roads = [], seats = 1
Output: 0
Explanation: No representatives need to travel to the capital city.
Constraints:
1 <= n <= 105
roads.length == n - 1
roads[i].length == 2
0 <= ai, bi < n
ai != bi
roads represents a valid tree.
1 <= seats <= 105 | [Python] DFS - Picture explanation - O(N) | 528 | minimum-fuel-cost-to-report-to-the-capital | 0.53 | hiepit | Medium | 33,984 | 2,477 |
number of beautiful partitions | class Solution:
def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:
n = len(s)
MOD = 10**9 + 7
def isPrime(c):
return c in ['2', '3', '5', '7']
@lru_cache(None)
def dp(i, k):
if k == 0 and i <= n:
return 1
if i >= n:
return 0
ans = dp(i+1, k) # Skip
if isPrime(s[i]) and not isPrime(s[i-1]): # Split
ans += dp(i+minLength, k-1)
return ans % MOD
if not isPrime(s[0]) or isPrime(s[-1]): return 0
return dp(minLength, k-1) | https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2833244/Python-Top-down-DP-Clean-and-Concise-O(N-*-K) | 21 | You are given a string s that consists of the digits '1' to '9' and two integers k and minLength.
A partition of s is called beautiful if:
s is partitioned into k non-intersecting substrings.
Each substring has a length of at least minLength.
Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime.
Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 109 + 7.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "23542185131", k = 3, minLength = 2
Output: 3
Explanation: There exists three ways to create a beautiful partition:
"2354 | 218 | 5131"
"2354 | 21851 | 31"
"2354218 | 51 | 31"
Example 2:
Input: s = "23542185131", k = 3, minLength = 3
Output: 1
Explanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131".
Example 3:
Input: s = "3312958", k = 3, minLength = 1
Output: 1
Explanation: There exists one way to create a beautiful partition: "331 | 29 | 58".
Constraints:
1 <= k, minLength <= s.length <= 1000
s consists of the digits '1' to '9'. | [Python] Top down DP - Clean & Concise - O(N * K) | 382 | number-of-beautiful-partitions | 0.294 | hiepit | Hard | 33,997 | 2,478 |