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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
average salary excluding the minimum and maximum salary | class Solution:
def average(self, salary: List[int]) -> float:
minimum = float("inf")
maximum = float("-inf")
i = 0
sums = 0
while i<len(salary):
minimum = min(minimum, salary[i])
maximum = max(maximum, salary[i])
sums+=salary[i]
i+=1
return (sums - (maximum+minimum))/(i-2) | https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2213970/Python3-one-pass-solution-beats-99.20-of-submissions | 6 | You are given an array of unique integers salary where salary[i] is the salary of the ith employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
Constraints:
3 <= salary.length <= 100
1000 <= salary[i] <= 106
All the integers of salary are unique. | π Python3 one pass solution beats 99.20% of submissions | 207 | average-salary-excluding-the-minimum-and-maximum-salary | 0.627 | Dark_wolf_jss | Easy | 22,161 | 1,491 |
the kth factor of n | class Solution:
def kthFactor(self, n: int, k: int) -> int:
factors = []
for i in range(1,n+1):
if n % i == 0:
factors.append(i)
if k > len(factors):
return -1
else:
return factors[k-1] | https://leetcode.com/problems/the-kth-factor-of-n/discuss/1352274/Python3-simple-solution-using-list | 1 | You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
Example 2:
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2nd factor is 7.
Example 3:
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
Constraints:
1 <= k <= n <= 1000
Follow up:
Could you solve this problem in less than O(n) complexity? | Python3 simple solution using list | 139 | the-kth-factor-of-n | 0.624 | EklavyaJoshi | Medium | 22,210 | 1,492 |
longest subarray of 1s after deleting one element | class Solution:
def longestSubarray(self, nums: List[int]) -> int:
m=0
l=len(nums)
one=True
for i in range(0,l):
if nums[i]==0:
one=False
left=i-1
right=i+1
ones=0
while left>=0:
if nums[left]==1:
ones=ones+1
left=left-1
else:
break
while right<l:
if nums[right]==1:
ones=ones+1
right=right+1
else:
break
if ones>m:
m=ones
if one:
return l-1
return m | https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708121/Easy-Solution-without-DP-Simple-Pictorial-Explanation-or-Python-Solution. | 12 | Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1. | [Easy Solution without DP] Simple Pictorial Explanation | Python Solution. | 1,100 | longest-subarray-of-1s-after-deleting-one-element | 0.602 | lazerx | Medium | 22,239 | 1,493 |
parallel courses ii | class Solution:
def minNumberOfSemesters(self, n: int, dependencies: List[List[int]], k: int) -> int:
pre = [0]*n # prerequisites
for u, v in dependencies:
pre[v-1] |= 1 << (u-1)
@cache
def fn(mask):
"""Return min semesters to take remaining courses."""
if mask == (1 << n) - 1: return 0 # all courses taken
can = [] # available courses
for i in range(n):
if not mask & 1 << i and mask & pre[i] == pre[i]:
can.append(i)
ans = inf
for courses in combinations(can, min(k, len(can))):
temp = mask | reduce(lambda x, y: x | 1 << y, courses, 0)
ans = min(ans, 1 + fn(temp))
return ans
return fn(0) | https://leetcode.com/problems/parallel-courses-ii/discuss/1111255/Python3-dp | 2 | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k.
In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.
Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.
Example 1:
Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2
Output: 3
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
Example 2:
Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2
Output: 4
Explanation: The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
Constraints:
1 <= n <= 15
1 <= k <= n
0 <= relations.length <= n * (n-1) / 2
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
All the pairs [prevCoursei, nextCoursei] are unique.
The given graph is a directed acyclic graph. | [Python3] dp | 171 | parallel-courses-ii | 0.311 | ye15 | Hard | 22,268 | 1,494 |
path crossing | class Solution:
def isPathCrossing(self, path: str) -> bool:
l = [(0,0)]
x,y = 0,0
for i in path:
if i == 'N':
y += 1
if i == 'S':
y -= 1
if i == 'E':
x += 1
if i == 'W':
x -= 1
if (x,y) in l:
return True
else:
l.append((x,y))
return False | https://leetcode.com/problems/path-crossing/discuss/1132447/Python3-simple-solution-faster-than-99-users | 4 | Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.
Example 1:
Input: path = "NES"
Output: false
Explanation: Notice that the path doesn't cross any point more than once.
Example 2:
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.
Constraints:
1 <= path.length <= 104
path[i] is either 'N', 'S', 'E', or 'W'. | Python3 simple solution faster than 99% users | 252 | path-crossing | 0.558 | EklavyaJoshi | Easy | 22,272 | 1,496 |
check if array pairs are divisible by k | class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
freq = dict()
for x in arr: freq[x%k] = 1 + freq.get(x%k, 0)
return all(freq[x] == freq.get(xx:=(k-x)%k, 0) and (x != xx or freq[x]%2 == 0) for x in freq) | https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/709252/Python3-3-line-frequency-table | 3 | Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Constraints:
arr.length == n
1 <= n <= 105
n is even.
-109 <= arr[i] <= 109
1 <= k <= 105 | [Python3] 3-line frequency table | 255 | check-if-array-pairs-are-divisible-by-k | 0.396 | ye15 | Medium | 22,296 | 1,497 |
number of subsequences that satisfy the given sum condition | class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
n = len(nums)
nums.sort()
i, j = 0, n-1
res = 0
NUM = 10**9+7
while i <= j:
if nums[i] + nums[j] > target:
j -= 1
elif nums[i] + nums[j] <= target:
res += pow(2, j-i, NUM)
i += 1
#else: # nums[i] + nums[j] == target
return res % NUM | https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/discuss/1703899/python-easy-two-pointers-%2B-sorting-solution | 3 | You are given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= target <= 106 | python easy two-pointers + sorting solution | 755 | number-of-subsequences-that-satisfy-the-given-sum-condition | 0.381 | byuns9334 | Medium | 22,302 | 1,498 |
max value of equation | class Solution:
def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:
ans = -inf
hp = []
for xj, yj in points:
while hp and xj - hp[0][1] > k: heappop(hp)
if hp:
ans = max(ans, xj + yj - hp[0][0])
heappush(hp, (xj-yj, xj))
return ans | https://leetcode.com/problems/max-value-of-equation/discuss/709364/Python3-heap | 8 | You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.
Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.
Example 1:
Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
Example 2:
Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
Constraints:
2 <= points.length <= 105
points[i].length == 2
-108 <= xi, yi <= 108
0 <= k <= 2 * 108
xi < xj for all 1 <= i < j <= points.length
xi form a strictly increasing sequence. | [Python3] heap | 721 | max-value-of-equation | 0.464 | ye15 | Hard | 22,309 | 1,499 |
can make arithmetic progression from sequence | class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
return len(set(arr[i-1] - arr[i] for i in range(1, len(arr)))) == 1 | https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720103/Python3-2-line-(sorting) | 17 | A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Example 2:
Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-106 <= arr[i] <= 106 | [Python3] 2-line (sorting) | 1,100 | can-make-arithmetic-progression-from-sequence | 0.681 | ye15 | Easy | 22,311 | 1,502 |
last moment before all ants fall out of a plank | class Solution:
def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
if left and not right:
return max(left)
if not left and right:
return n - min(right)
if not left and not right:
return 0
if left and right:
return max(max(left), n - min(right)) | https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/discuss/720202/PythonPython3-Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank | 1 | We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.
When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.
When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.
Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.
Example 1:
Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: In the image above:
-The ant at index 0 is named A and going to the right.
-The ant at index 1 is named B and going to the right.
-The ant at index 3 is named C and going to the left.
-The ant at index 4 is named D and going to the left.
The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).
Example 2:
Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
Output: 7
Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.
Example 3:
Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []
Output: 7
Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.
Constraints:
1 <= n <= 104
0 <= left.length <= n + 1
0 <= left[i] <= n
0 <= right.length <= n + 1
0 <= right[i] <= n
1 <= left.length + right.length <= n + 1
All values of left and right are unique, and each value can appear only in one of the two arrays. | [Python/Python3] Last Moment Before All Ants Fall Out of a Plank | 87 | last-moment-before-all-ants-fall-out-of-a-plank | 0.553 | newborncoder | Medium | 22,355 | 1,503 |
count submatrices with all ones | class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
#precipitate mat to histogram
for i in range(m):
for j in range(n):
if mat[i][j] and i > 0:
mat[i][j] += mat[i-1][j] #histogram
ans = 0
for i in range(m):
stack = [] #mono-stack of indices of non-decreasing height
cnt = 0
for j in range(n):
while stack and mat[i][stack[-1]] > mat[i][j]:
jj = stack.pop() #start
kk = stack[-1] if stack else -1 #end
cnt -= (mat[i][jj] - mat[i][j])*(jj - kk) #adjust to reflect lower height
cnt += mat[i][j] #count submatrices bottom-right at (i, j)
ans += cnt
stack.append(j)
return ans | https://leetcode.com/problems/count-submatrices-with-all-ones/discuss/721999/Python3-O(MN)-histogram-model | 111 | Given an m x n binary matrix mat, return the number of submatrices that have all ones.
Example 1:
Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
Example 2:
Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Output: 24
Explanation:
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
Constraints:
1 <= m, n <= 150
mat[i][j] is either 0 or 1. | [Python3] O(MN) histogram model | 7,600 | count-submatrices-with-all-ones | 0.578 | ye15 | Medium | 22,360 | 1,504 |
minimum possible integer after at most k adjacent swaps on digits | class Solution:
def minInteger(self, num: str, k: int) -> str:
n = len(num)
if k >= n*(n-1)//2: return "".join(sorted(num)) #special case
#find smallest elements within k swaps
#and swap it to current position
num = list(num)
for i in range(n):
if not k: break
#find minimum within k swaps
ii = i
for j in range(i+1, min(n, i+k+1)):
if num[ii] > num[j]: ii = j
#swap the min to current position
if ii != i:
k -= ii-i
for j in range(ii, i, -1):
num[j-1], num[j] = num[j], num[j-1]
return "".join(num) | https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/discuss/720123/Python3-brute-force | 2 | You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 104
num consists of only digits and does not contain leading zeros.
1 <= k <= 109 | [Python3] brute force | 374 | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0.383 | ye15 | Hard | 22,364 | 1,505 |
reformat date | class Solution:
def reformatDate(self, date: str) -> str:
s = date.split() # Divides the elements into 3 individual parts
monthDict = {'Jan': '01', 'Feb': '02',
'Mar': '03', 'Apr': '04',
'May': '05', 'Jun': '06',
'Jul': '07', 'Aug': '08',
'Sep': '09', 'Oct': '10',
'Nov': '11', 'Dec': '12'}
day = s[0][:-2] # Removes the last 2 elements of the day
month = s[1]
year = s[2]
if int(day) < 10: # Adds 0 to the front of day if day < 10
day = '0' + day
return ''.join(f'{year}-{monthDict[month]}-{day}') # Joins it all together. Month is used to draw out the corresponding number from the dict. | https://leetcode.com/problems/reformat-date/discuss/1861804/Python-3-Easy-Dict.-Solution-wout-imports-(98) | 12 | Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to the format YYYY-MM-DD, where:
YYYY denotes the 4 digit year.
MM denotes the 2 digit month.
DD denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
The given dates are guaranteed to be valid, so no error handling is necessary. | Python 3 - Easy Dict. Solution w/out imports (98%) | 768 | reformat-date | 0.626 | IvanTsukei | Easy | 22,365 | 1,507 |
range sum of sorted subarray sums | class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
ans = []
for i in range(len(nums)):
prefix = 0
for ii in range(i, len(nums)):
prefix += nums[ii]
ans.append(prefix)
ans.sort()
return sum(ans[left-1:right]) % 1_000_000_007 | https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/730973/Python3-priority-queue | 46 | You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
Constraints:
n == nums.length
1 <= nums.length <= 1000
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2 | [Python3] priority queue | 3,600 | range-sum-of-sorted-subarray-sums | 0.593 | ye15 | Medium | 22,398 | 1,508 |
minimum difference between largest and smallest value in three moves | class Solution:
def minDifference(self, nums: List[int]) -> int:
n = len(nums)
# If nums are less than 3 all can be replace,
# so min diff will be 0, which is default condition
if n > 3:
# Init min difference
min_diff = float("inf")
# sort the array
nums = sorted(nums)
# Get the window size, this indicates, if we
# remove 3 element in an array how many element
# are left, consider 0 as the index, window
# size should be (n-3), but for array starting
# with 0 it should be ((n-1)-3)
window = (n-1)-3
# Run through the entire array slinding the
# window and calculating minimum difference
# between the first and the last element of
# that window
for i in range(n):
if i+window >= n:
break
else:
min_diff = min(nums[i+window]-nums[i], min_diff)
# return calculated minimum difference
return min_diff
return 0 # default condition | https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1433873/Python3Python-Easy-readable-solution-with-comments. | 10 | You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.
It can be shown that there is no way to make the difference 0 in 3 moves.
Example 3:
Input: nums = [3,100,20]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes [3,7,20].
In the second move, change 20 to 7. nums becomes [3,7,7].
In the third move, change 3 to 7. nums becomes [7,7,7].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109 | [Python3/Python] Easy readable solution with comments. | 1,000 | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0.546 | ssshukla26 | Medium | 22,403 | 1,509 |
stone game iv | class Solution:
def winnerSquareGame(self, n: int) -> bool:
dp = [False] * (n + 1)
squares = []
curSquare = 1
for i in range(1, n + 1):
if i == curSquare * curSquare:
squares.append(i)
curSquare += 1
dp[i] = True
else:
for square in squares:
if not dp[i - square]:
dp[i] = True
break
return dp[n] | https://leetcode.com/problems/stone-game-iv/discuss/1708107/Python3-DP | 8 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
Example 1:
Input: n = 1
Output: true
Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2
Output: false
Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4
Output: true
Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
Constraints:
1 <= n <= 105 | [Python3] DP | 397 | stone-game-iv | 0.605 | PatrickOweijane | Hard | 22,413 | 1,510 |
number of good pairs | class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
hashMap = {}
res = 0
for number in nums:
if number in hashMap:
res += hashMap[number]
hashMap[number] += 1
else:
hashMap[number] = 1
return res | https://leetcode.com/problems/number-of-good-pairs/discuss/749025/Python-O(n)-simple-dictionary-solution | 88 | Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100 | Python O(n) simple dictionary solution | 6,200 | number-of-good-pairs | 0.882 | Arturo001 | Easy | 22,427 | 1,512 |
number of substrings with only 1s | class Solution:
def numSub(self, s: str) -> int:
res = 0
s = s.split("0")
for one in s:
if one == "":
continue
n = len(one)
temp = (n / 2)*(2*n + (n-1)*-1)
if temp >= 1000000007:
res += temp % 1000000007
else:
res += temp
return int(res) | https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731754/Python-Sum-of-Arithmetic-Progression-with-explanation-**100.00-Faster** | 8 | Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'. | [Python] Sum of Arithmetic Progression with explanation **100.00% Faster** | 506 | number-of-substrings-with-only-1s | 0.454 | Jasper-W | Medium | 22,479 | 1,513 |
path with maximum probability | class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
graph, prob = dict(), dict() #graph with prob
for i, (u, v) in enumerate(edges):
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
prob[u, v] = prob[v, u] = succProb[i]
h = [(-1, start)] #Dijkstra's algo
seen = set()
while h:
p, n = heappop(h)
if n == end: return -p
seen.add(n)
for nn in graph.get(n, []):
if nn in seen: continue
heappush(h, (p * prob.get((n, nn), 0), nn))
return 0 | https://leetcode.com/problems/path-with-maximum-probability/discuss/731655/Python3-Dijkstra's-algo | 27 | You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
Example 2:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000
Example 3:
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.
Constraints:
2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
There is at most one edge between every two nodes. | [Python3] Dijkstra's algo | 2,500 | path-with-maximum-probability | 0.484 | ye15 | Medium | 22,497 | 1,514 |
best position for a service centre | class Solution:
def getMinDistSum(self, positions: List[List[int]]) -> float:
#euclidean distance
fn = lambda x, y: sum(sqrt((x-xx)**2 + (y-yy)**2) for xx, yy in positions)
#centroid as starting point
x = sum(x for x, _ in positions)/len(positions)
y = sum(y for _, y in positions)/len(positions)
ans = fn(x, y)
chg = 100 #change since 0 <= positions[i][0], positions[i][1] <= 100
while chg > 1e-6: #accuracy within 1e-5
zoom = True
for dx, dy in (-1, 0), (0, -1), (0, 1), (1, 0):
xx = x + chg * dx
yy = y + chg * dy
dd = fn(xx, yy)
if dd < ans:
ans = dd
x, y = xx, yy
zoom = False
break
if zoom: chg /= 2
return ans | https://leetcode.com/problems/best-position-for-a-service-centre/discuss/731717/Python3-geometric-median | 62 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.
Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.
In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:
Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: positions = [[0,1],[1,0],[1,2],[2,1]]
Output: 4.00000
Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.
Example 2:
Input: positions = [[1,1],[3,3]]
Output: 2.82843
Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843
Constraints:
1 <= positions.length <= 50
positions[i].length == 2
0 <= xi, yi <= 100 | [Python3] geometric median | 3,700 | best-position-for-a-service-centre | 0.377 | ye15 | Hard | 22,502 | 1,515 |
water bottles | class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = r = 0
while numBottles:
ans += numBottles
numBottles, r = divmod(numBottles + r, numExchange)
return ans | https://leetcode.com/problems/water-bottles/discuss/743152/Python3-5-line-iterative | 9 | There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.
Example 1:
Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.
Example 2:
Input: numBottles = 15, numExchange = 4
Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.
Constraints:
1 <= numBottles <= 100
2 <= numExchange <= 100 | [Python3] 5-line iterative | 573 | water-bottles | 0.602 | ye15 | Easy | 22,503 | 1,518 |
number of nodes in the sub tree with the same label | class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
ans = [0] * n
tree = collections.defaultdict(list)
for a, b in edges: # build tree
tree[a].append(b)
tree[b].append(a)
def dfs(node): # dfs
nonlocal visited, ans, tree
c = collections.Counter(labels[node])
for nei in tree[node]:
if nei in visited: continue # avoid revisit
visited.add(nei)
c += dfs(nei) # add counter (essentially adding a 26 elements dictionary)
ans[node] = c.get(labels[node]) # assign count of label to this node
return c
visited = set([0])
dfs(0)
return ans | https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/discuss/1441578/Python-3-or-DFS-Graph-Counter-or-Explanation | 7 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).
The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.
Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.
A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.
Example 1:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
Output: [2,1,1,1,1,1,1]
Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
Example 2:
Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
Output: [4,2,1,1]
Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
Example 3:
Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
Output: [3,2,1,1,1]
Constraints:
1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
labels.length == n
labels is consisting of only of lowercase English letters. | Python 3 | DFS, Graph, Counter | Explanation | 366 | number-of-nodes-in-the-sub-tree-with-the-same-label | 0.41 | idontknoooo | Medium | 22,528 | 1,519 |
maximum number of non overlapping substrings | class Solution:
def maxNumOfSubstrings(self, s: str) -> List[str]:
locs = {}
for i, x in enumerate(s):
locs.setdefault(x, []).append(i)
def fn(lo, hi):
"""Return expanded range covering all chars in s[lo:hi+1]."""
for xx in locs:
k0 = bisect_left(locs[xx], lo)
k1 = bisect_left(locs[xx], hi)
if k0 < k1 and (locs[xx][0] < lo or hi < locs[xx][-1]):
lo = min(lo, locs[xx][0])
hi = max(hi, locs[xx][-1])
lo, hi = fn(lo, hi)
return lo, hi
group = set()
for x in locs:
group.add(fn(locs[x][0], locs[x][-1]))
ans = [] # ISMP (interval scheduling maximization problem)
prev = -1
for lo, hi in sorted(group, key=lambda x: x[1]):
if prev < lo:
ans.append(s[lo:hi+1])
prev = hi
return ans | https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/1208758/Python3-greedy | 1 | Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:
The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.
A substring that contains a certain character c must also contain all occurrences of c.
Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.
Notice that you can return the substrings in any order.
Example 1:
Input: s = "adefaddaccc"
Output: ["e","f","ccc"]
Explanation: The following are all the possible substrings that meet the conditions:
[
"adefaddaccc"
"adefadda",
"ef",
"e",
"f",
"ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
Example 2:
Input: s = "abbaccd"
Output: ["d","bb","cc"]
Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters. | [Python3] greedy | 281 | maximum-number-of-non-overlapping-substrings | 0.381 | ye15 | Hard | 22,532 | 1,520 |
find a value of a mysterious function closest to target | class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
ans, seen = inf, set()
for x in arr:
seen = {ss & x for ss in seen} | {x}
ans = min(ans, min(abs(ss - target) for ss in seen))
return ans | https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target/discuss/746723/Python3-bitwise-and | 8 | Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Example 1:
Input: arr = [9,12,3,7,15], target = 5
Output: 2
Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
Example 2:
Input: arr = [1000000,1000000,1000000], target = 1
Output: 999999
Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
Example 3:
Input: arr = [1,2,4,8,16], target = 0
Output: 0
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 106
0 <= target <= 107 | [Python3] bitwise and | 306 | find-a-value-of-a-mysterious-function-closest-to-target | 0.436 | ye15 | Hard | 22,534 | 1,521 |
count odd numbers in an interval range | class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 0:
return (high-low+1)//2
return (high-low)//2 + 1 | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/discuss/1813332/Python-3-or-Math-or-Intuitive | 60 | Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9 | Python 3 | Math | Intuitive | 4,500 | count-odd-numbers-in-an-interval-range | 0.462 | ndus | Easy | 22,537 | 1,523 |
number of sub arrays with odd sum | class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
cumSum = odd = even = 0
for num in arr:
cumSum += num
if cumSum % 2:
odd += 1
else:
even += 1
return odd * (even + 1) % (pow(10, 9) + 7) | https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/discuss/2061760/Python-oror-8-line-math-using-Prefix-Sum | 1 | Given an array of integers arr, return the number of subarrays with an odd sum.
Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 100 | Python || 8-line math using Prefix Sum | 138 | number-of-sub-arrays-with-odd-sum | 0.436 | gulugulugulugulu | Medium | 22,594 | 1,524 |
number of good ways to split a string | class Solution:
def numSplits(self, s: str) -> int:
# this is not neccessary, but speeds things up
length = len(s)
if length == 1: # never splittable
return 0
elif length == 2: # always splittable
return 1
# we are recording the first and last occurence of each included letter
first = {} # max size = 26
last = {} # max size = 26
for index, character in enumerate(s): # O(n)
if character not in first:
first[character] = index
last[character] = index
# we are concatenating the collected indices into a list and sort them
indices = list(first.values()) + list(last.values()) # max length 26 + 26 = 52
indices.sort() # sorting is constant O(1) because of the length limit above
# all possible splits will be in the middle of this list
middle = len(indices)//2 # always an integer because indices has an even length
# there are this many possible splits between the two 'median' numbers
return indices[middle] - indices[middle-1] | https://leetcode.com/problems/number-of-good-ways-to-split-a-string/discuss/1520004/99.7-Python-3-solution-with-17-lines-no-search-explained | 70 | You are given a string s.
A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.
Return the number of good splits you can make in s.
Example 1:
Input: s = "aacaba"
Output: 2
Explanation: There are 5 ways to split "aacaba" and 2 of them are good.
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
Example 2:
Input: s = "abcd"
Output: 1
Explanation: Split the string as follows ("ab", "cd").
Constraints:
1 <= s.length <= 105
s consists of only lowercase English letters. | 99.7% Python 3 solution with 17 lines, no search, explained | 2,200 | number-of-good-ways-to-split-a-string | 0.694 | epistoteles | Medium | 22,600 | 1,525 |
minimum number of increments on subarrays to form a target array | class Solution:
def minNumberOperations(self, target: List[int]) -> int:
res = target[0]
for i in range(1, len(target)):
if target[i] >= target[i - 1]:
res -= target[i - 1]
res += target[i]
return res | https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/discuss/1589995/Python3-O(n)-time-O(1)-space-solution | 1 | You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.
Example 2:
Input: target = [3,1,1,2]
Output: 4
Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]
Example 3:
Input: target = [3,1,5,4,2]
Output: 7
Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].
Constraints:
1 <= target.length <= 105
1 <= target[i] <= 105 | [Python3] O(n) time, O(1) space solution | 87 | minimum-number-of-increments-on-subarrays-to-form-a-target-array | 0.686 | maosipov11 | Hard | 22,624 | 1,526 |
shuffle string | class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
res = [''] * len(s)
for i in range(len(s)):
res[indices[i]] = s[i]
return ''.join(i for i in res) | https://leetcode.com/problems/shuffle-string/discuss/768482/Simple-Python-Solution-Faster-than-99.56 | 25 | You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
Constraints:
s.length == indices.length == n
1 <= n <= 100
s consists of only lowercase English letters.
0 <= indices[i] < n
All values of indices are unique. | Simple Python Solution - Faster than 99.56% | 4,200 | shuffle-string | 0.857 | parkershamblin | Easy | 22,628 | 1,528 |
minimum suffix flips | class Solution:
def minFlips(self, target: str) -> int:
return len(list(groupby("0" + target)))-1 | https://leetcode.com/problems/minimum-suffix-flips/discuss/755814/Python3-1-line | 16 | You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.
In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.
Return the minimum number of operations needed to make s equal to target.
Example 1:
Input: target = "10111"
Output: 3
Explanation: Initially, s = "00000".
Choose index i = 2: "00000" -> "00111"
Choose index i = 0: "00111" -> "11000"
Choose index i = 1: "11000" -> "10111"
We need at least 3 flip operations to form target.
Example 2:
Input: target = "101"
Output: 3
Explanation: Initially, s = "000".
Choose index i = 0: "000" -> "111"
Choose index i = 1: "111" -> "100"
Choose index i = 2: "100" -> "101"
We need at least 3 flip operations to form target.
Example 3:
Input: target = "00000"
Output: 0
Explanation: We do not need any operations since the initial s already equals target.
Constraints:
n == target.length
1 <= n <= 105
target[i] is either '0' or '1'. | [Python3] 1-line | 872 | minimum-suffix-flips | 0.724 | ye15 | Medium | 22,687 | 1,529 |
number of good leaf nodes pairs | class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
def dfs(node):
"""Return (a list of) distances to leaves of sub-tree rooted at node."""
nonlocal ans
if not node: return []
if node.left is node.right is None: return [0]
left,right = dfs(node.left), dfs(node.right)
ans += sum(2 + x + y <= distance for x in left for y in right)
return [1 + x for x in left + right]
ans = 0
dfs(root)
return ans | https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/discuss/755979/Python3-recursive-postorder-dfs | 3 | You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2:
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].
Constraints:
The number of nodes in the tree is in the range [1, 210].
1 <= Node.val <= 100
1 <= distance <= 10 | [Python3] recursive postorder dfs | 264 | number-of-good-leaf-nodes-pairs | 0.607 | ye15 | Medium | 22,705 | 1,530 |
string compression ii | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
rle = lambda x: x if x <= 1 else int(log10(x)) + 2 # rle length of a char repeated x times
@cache
def fn(i, k, prev, cnt):
"""Return length of rle of s[i:] with k chars to be deleted."""
if k < 0: return inf
if i == len(s): return 0
ans = fn(i+1, k-1, prev, cnt) # delete current character
if prev == s[i]:
ans = min(ans, fn(i+1, k, s[i], cnt+1) + rle(cnt+1) - rle(cnt))
else:
ans = min(ans, fn(i+1, k, s[i], 1) + 1)
return ans
return fn(0, k, "", 0) | https://leetcode.com/problems/string-compression-ii/discuss/1203398/Python3-top-down-dp | 12 | Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.
Example 1:
Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
Example 2:
Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
Example 3:
Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
Constraints:
1 <= s.length <= 100
0 <= k <= s.length
s contains only lowercase English letters. | [Python3] top-down dp | 1,300 | string-compression-ii | 0.499 | ye15 | Hard | 22,711 | 1,531 |
count good triplets | class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
return sum(abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c for i in range(len(arr)) for j in range(i+1, len(arr)) for k in range(j+1, len(arr))) | https://leetcode.com/problems/count-good-triplets/discuss/767942/Python3-1-line | 4 | Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.
Return the number of good triplets.
Example 1:
Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
Example 2:
Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.
Constraints:
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000 | [Python3] 1-line | 1,800 | count-good-triplets | 0.808 | ye15 | Easy | 22,716 | 1,534 |
find the winner of an array game | class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
win = cnt = 0 #winner & count
for i, x in enumerate(arr):
if win < x: win, cnt = x, 0 #new winner in town
if i: cnt += 1 #when initializing (i.e. i == 0) count is 0
if cnt == k: break #early break
return win | https://leetcode.com/problems/find-the-winner-of-an-array-game/discuss/767983/Python3-6-line-O(N) | 7 | Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.
Return the integer which will win the game.
It is guaranteed that there will be a winner of the game.
Example 1:
Input: arr = [2,1,3,5,4,6,7], k = 2
Output: 5
Explanation: Let's see the rounds of the game:
Round | arr | winner | win_count
1 | [2,1,3,5,4,6,7] | 2 | 1
2 | [2,3,5,4,6,7,1] | 3 | 1
3 | [3,5,4,6,7,1,2] | 5 | 1
4 | [5,4,6,7,1,2,3] | 5 | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
Example 2:
Input: arr = [3,2,1], k = 10
Output: 3
Explanation: 3 will win the first 10 rounds consecutively.
Constraints:
2 <= arr.length <= 105
1 <= arr[i] <= 106
arr contains distinct integers.
1 <= k <= 109 | [Python3] 6-line O(N) | 267 | find-the-winner-of-an-array-game | 0.488 | ye15 | Medium | 22,741 | 1,535 |
minimum swaps to arrange a binary grid | class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
#summarizing row into number
row = [0]*m
for i in range(m):
row[i] = next((j for j in reversed(range(n)) if grid[i][j]), 0)
ans = 0
#sequentially looking for row to fill in
for k in range(m):
for i, v in enumerate(row):
if v <= k: #enough trailing zeros
ans += i
row.pop(i) #value used
break
else: return -1 #cannot find such row
return ans | https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768030/Python3-bubble-ish-sort | 13 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
Example 1:
Input: grid = [[0,0,1],[1,1,0],[1,0,0]]
Output: 3
Example 2:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
Output: -1
Explanation: All rows are similar, swaps have no effect on the grid.
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,1]]
Output: 0
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
grid[i][j] is either 0 or 1 | [Python3] bubble-ish sort | 750 | minimum-swaps-to-arrange-a-binary-grid | 0.465 | ye15 | Medium | 22,744 | 1,536 |
get the maximum score | class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
ans = i = ii = s = ss = 0
while i < len(nums1) and ii < len(nums2):
#update range sum & move pointer
if nums1[i] < nums2[ii]:
s += nums1[i]
i += 1
elif nums1[i] > nums2[ii]:
ss += nums2[ii]
ii += 1
#add larger range sum to ans
#add common value & move pointers
else:
ans += max(s, ss) + nums1[i]
s = ss = 0
i, ii = i+1, ii+1
#complete the range sum & update ans
ans += max(s + sum(nums1[i:]), ss + sum(nums2[ii:]))
return ans % 1_000_000_007 | https://leetcode.com/problems/get-the-maximum-score/discuss/768050/Python3-range-sum-with-two-pointers-O(M%2BN) | 1 | You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:
Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).
The score is defined as the sum of unique values in a valid path.
Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output: 30
Explanation: Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)
The maximum is obtained with the path in green [2,4,6,8,10].
Example 2:
Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
Output: 109
Explanation: Maximum sum is obtained with the path [1,3,5,100].
Example 3:
Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
Output: 40
Explanation: There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path [6,7,8,9,10].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 107
nums1 and nums2 are strictly increasing. | [Python3] range sum with two pointers O(M+N) | 73 | get-the-maximum-score | 0.393 | ye15 | Hard | 22,746 | 1,537 |
kth missing positive number | class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
ss, x = set(arr), 1
while True:
if x not in ss: k -= 1
if not k: return x
x += 1 | https://leetcode.com/problems/kth-missing-positive-number/discuss/784720/Python3-O(N)-and-O(logN)-solutions | 5 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Return the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
Follow up:
Could you solve this problem in less than O(n) complexity? | [Python3] O(N) and O(logN) solutions | 240 | kth-missing-positive-number | 0.56 | ye15 | Easy | 22,749 | 1,539 |
can convert string in k moves | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
cycles, extra = divmod(k, 26)
shifts = [cycles + (shift <= extra) for shift in range(26)]
for cs, ct in zip(s, t):
shift = (ord(ct) - ord(cs)) % 26
if shift == 0:
continue
if not shifts[shift]:
return False
shifts[shift] -= 1
return True | https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/2155709/python-3-or-simple-O(n)O(1)-solution | 0 | Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:
Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.
Remember that any index j can be picked at most once.
Return true if it's possible to convert s into t in no more than k moves, otherwise return false.
Example 1:
Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
Example 2:
Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
Example 3:
Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
Constraints:
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s, t contain only lowercase English letters. | python 3 | simple O(n)/O(1) solution | 67 | can-convert-string-in-k-moves | 0.332 | dereky4 | Medium | 22,800 | 1,540 |
minimum insertions to balance a parentheses string | class Solution:
def minInsertions(self, s: str) -> int:
"""
(
"""
res = need = 0
for i in range(len(s)):
if s[i] == '(':
need += 2
if need % 2 == 1:
res += 1
need -= 1
if s[i] == ')':
need -= 1
if need == -1:
res += 1
need = 1
return res + need | https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2825876/Python | 0 | Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:
Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.
For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.
You can insert the characters '(' and ')' at any position of the string to balance it if needed.
Return the minimum number of insertions needed to make s balanced.
Example 1:
Input: s = "(()))"
Output: 1
Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.
Example 2:
Input: s = "())"
Output: 0
Explanation: The string is already balanced.
Example 3:
Input: s = "))())("
Output: 3
Explanation: Add '(' to match the first '))', Add '))' to match the last '('.
Constraints:
1 <= s.length <= 105
s consists of '(' and ')' only. | Python | 2 | minimum-insertions-to-balance-a-parentheses-string | 0.499 | lillllllllly | Medium | 22,804 | 1,541 |
find longest awesome substring | class Solution:
def longestAwesome(self, s: str) -> int:
# li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
li = [2**i for i in range(10)]
# checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}
checker = set(li)
checker.add(0)
# di: k = prefix xor, v = the first idx I got a new prefix_xor_value.
di = collections.OrderedDict({0: -1})
maxLength = prefix_xor = 0
for i in range(len(s)):
prefix_xor ^= li[int(s[i])]
# Found a new prefix_xor_value
if prefix_xor not in di:
di[prefix_xor] = i
# XOR operation with previous prefix_xor_value
for key in di.keys():
if i - di[key] <= maxLength:
break
# s[di[key] : i] is Awesome Substring
if key ^ prefix_xor in checker:
maxLength = i - di[key]
return maxLength | https://leetcode.com/problems/find-longest-awesome-substring/discuss/2259262/Python3-or-Prefix-xor-or-O(n)-Solution | 1 | You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
Example 2:
Input: s = "12345678"
Output: 1
Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
Constraints:
1 <= s.length <= 105
s consists only of digits. | Python3 | Prefix xor | O(n) Solution | 75 | find-longest-awesome-substring | 0.414 | shugokra | Hard | 22,816 | 1,542 |
make the string great | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and abs(ord(stack[-1]) - ord(c)) == 32: stack.pop() #pop "bad"
else: stack.append(c) #push "good"
return "".join(stack) | https://leetcode.com/problems/make-the-string-great/discuss/781044/Python3-5-line-stack-O(N) | 34 | Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100
s contains only lower and upper case English letters. | [Python3] 5-line stack O(N) | 1,400 | make-the-string-great | 0.633 | ye15 | Easy | 22,818 | 1,544 |
find kth bit in nth binary string | class Solution:
def findKthBit(self, n: int, k: int) -> str:
if k == 1: return "0"
if k == 2**(n-1): return "1"
if k < 2**(n-1): return self.findKthBit(n-1, k)
return "0" if self.findKthBit(n-1, 2**n-k) == "1" else "1" | https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781062/Python3-4-line-recursive | 11 | Given two positive integers n and k, the binary string Sn is formed as follows:
S1 = "0"
Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
For example, the first four strings in the above sequence are:
S1 = "0"
S2 = "011"
S3 = "0111001"
S4 = "011100110110001"
Return the kth bit in Sn. It is guaranteed that k is valid for the given n.
Example 1:
Input: n = 3, k = 1
Output: "0"
Explanation: S3 is "0111001".
The 1st bit is "0".
Example 2:
Input: n = 4, k = 11
Output: "1"
Explanation: S4 is "011100110110001".
The 11th bit is "1".
Constraints:
1 <= n <= 20
1 <= k <= 2n - 1 | [Python3] 4-line recursive | 432 | find-kth-bit-in-nth-binary-string | 0.583 | ye15 | Medium | 22,872 | 1,545 |
maximum number of non overlapping subarrays with sum equals target | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
ans = prefix = 0
seen = set([0]) #prefix sum seen so far ()
for i, x in enumerate(nums):
prefix += x
if prefix - target in seen:
ans += 1
seen.clear() #reset seen
seen.add(prefix)
return ans | https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/781075/Python3-O(N)-prefix-sum | 2 | Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).
Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
0 <= target <= 106 | [Python3] O(N) prefix sum | 54 | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | 0.472 | ye15 | Medium | 22,892 | 1,546 |
minimum cost to cut a stick | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
@lru_cache(None)
def fn(lo, hi):
"""Return cost of cutting [lo, hi]."""
cc = [c for c in cuts if lo < c < hi] #collect cuts within this region
if not cc: return 0
ans = inf
for mid in cc: ans = min(ans, fn(lo, mid) + fn(mid, hi))
return ans + hi - lo
return fn(0, n) | https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp | 6 | Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:
Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.
Return the minimum total cost of the cuts.
Example 1:
Input: n = 7, cuts = [1,3,4,5]
Output: 16
Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:
The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
Example 2:
Input: n = 9, cuts = [5,6,1,4,2]
Output: 22
Explanation: If you try the given cuts ordering the cost will be 25.
There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.
Constraints:
2 <= n <= 106
1 <= cuts.length <= min(n - 1, 100)
1 <= cuts[i] <= n - 1
All the integers in cuts array are distinct. | [Python3] top-down & bottom-up dp | 488 | minimum-cost-to-cut-a-stick | 0.57 | ye15 | Hard | 22,897 | 1,547 |
three consecutive odds | class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
count = 0
for i in range(0, len(arr)):
if arr[i] %2 != 0:
count += 1
if count == 3:
return True
else:
count = 0
return False | https://leetcode.com/problems/three-consecutive-odds/discuss/794097/Python3-straight-forward-solution | 20 | Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
Example 1:
Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000 | Python3 straight forward solution | 1,600 | three-consecutive-odds | 0.636 | sjha2048 | Easy | 22,903 | 1,550 |
minimum operations to make array equal | class Solution:
def minOperations(self, n: int) -> int:
if(n%2!=0):
n=n//2
return n*(n+1)
else:
n=n//2
return n**2 | https://leetcode.com/problems/minimum-operations-to-make-array-equal/discuss/1704407/Understandable-code-for-beginners-like-me-in-python-!! | 2 | You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.
Example 1:
Input: n = 3
Output: 2
Explanation: arr = [1, 3, 5]
First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
Example 2:
Input: n = 6
Output: 9
Constraints:
1 <= n <= 104 | Understandable code for beginners like me in python !! | 92 | minimum-operations-to-make-array-equal | 0.811 | kabiland | Medium | 22,937 | 1,551 |
magnetic force between two balls | class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
def fn(d):
"""Return True if d is a feasible distance."""
ans, prev = 0, -inf # where previous ball is put
for x in position:
if x - prev >= d:
ans += 1
if ans == m: return True
prev = x
return False
# "last True" binary search (in contrast to "first True" binary search)
lo, hi = 1, position[-1] - position[0]
while lo < hi:
mid = lo + hi + 1 >> 1
if fn(mid): lo = mid
else: hi = mid - 1
return lo | https://leetcode.com/problems/magnetic-force-between-two-balls/discuss/794249/Python3-binary-search-distance-space | 4 | In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 105
1 <= position[i] <= 109
All integers in position are distinct.
2 <= m <= position.length | [Python3] binary search distance space | 473 | magnetic-force-between-two-balls | 0.57 | ye15 | Medium | 22,962 | 1,552 |
minimum number of days to eat n oranges | class Solution:
def minDays(self, n: int) -> int:
ans = 0
queue = [n]
seen = set()
while queue: #bfs
newq = []
for x in queue:
if x == 0: return ans
seen.add(x)
if x-1 not in seen: newq.append(x-1)
if x % 2 == 0 and x//2 not in seen: newq.append(x//2)
if x % 3 == 0 and x//3 not in seen: newq.append(x//3)
ans += 1
queue = newq | https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/discuss/794275/Python3-bfs | 26 | There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose one of the actions per day.
Given the integer n, return the minimum number of days to eat n oranges.
Example 1:
Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange, 10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange 1 - 1 = 0.
You need at least 4 days to eat the 10 oranges.
Example 2:
Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange 1 - 1 = 0.
You need at least 3 days to eat the 6 oranges.
Constraints:
1 <= n <= 2 * 109 | [Python3] bfs | 1,500 | minimum-number-of-days-to-eat-n-oranges | 0.346 | ye15 | Hard | 22,969 | 1,553 |
thousand separator | class Solution:
def thousandSeparator(self, n: int) -> str:
return f"{n:,}".replace(",", ".") | https://leetcode.com/problems/thousand-separator/discuss/805712/Python3-1-line | 25 | Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Constraints:
0 <= n <= 231 - 1 | [Python3] 1-line | 980 | thousand-separator | 0.549 | ye15 | Easy | 22,975 | 1,556 |
minimum number of vertices to reach all nodes | class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
if not edges:
return []
incoming_degrees = {i: 0 for i in range(n)}
for x, y in edges:
incoming_degrees[y] += 1
result = [k for k, v in incoming_degrees.items() if v == 0]
return result | https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1212672/Python-Easy-Solution-Count-of-Nodes-with-Zero-Incoming-Degree | 4 | Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Example 2:
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
Constraints:
2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi < n
All pairs (fromi, toi) are distinct. | Python Easy Solution - Count of Nodes with Zero Incoming-Degree | 195 | minimum-number-of-vertices-to-reach-all-nodes | 0.796 | ChidinmaKO | Medium | 23,002 | 1,557 |
minimum numbers of function calls to make target array | class Solution:
def minOperations(self, nums: List[int]) -> int:
return sum(bin(a).count('1') for a in nums) + len(bin(max(nums))) - 2 - 1 | https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/807358/Python-Bit-logic-Explained | 3 | You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:
You want to use the modify function to convert arr to nums using the minimum number of calls.
Return the minimum number of function calls to make nums from arr.
The test cases are generated so that the answer fits in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109 | Python Bit logic Explained | 125 | minimum-numbers-of-function-calls-to-make-target-array | 0.642 | akhil_ak | Medium | 23,031 | 1,558 |
detect cycles in 2d grid | class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def fn(i, j, d):
"""Traverse the grid to find cycle via backtracking."""
if grid[i][j] != "BLACK":
val = grid[i][j]
grid[i][j] = "GRAY" # mark visited in this trial
for ii, jj, dd in ((i-1, j, -2), (i, j-1, -1), (i, j+1, 1), (i+1, j, 2)):
if 0 <= ii < m and 0 <= jj < n and d + dd != 0: # in range & not going back
if grid[ii][jj] == "GRAY": return True #cycle found
if grid[ii][jj] == val: fn(ii, jj, dd)
grid[i][j] = val
for i in range(m):
for j in range(n):
if fn(i, j, 0): return True
grid[i][j] = "BLACK" # mark "no cycle"
return False | https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/806630/Python3-memoized-dfs-with-a-direction-parameter-(16-line) | 1 | Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.
Return true if any cycle of the same value exists in grid, otherwise, return false.
Example 1:
Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:
Example 2:
Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:
Example 3:
Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid consists only of lowercase English letters. | [Python3] memoized dfs with a direction parameter (16-line) | 75 | detect-cycles-in-2d-grid | 0.48 | ye15 | Medium | 23,037 | 1,559 |
most visited sector in a circular track | class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
x, xx = rounds[0], rounds[-1]
return list(range(x, xx+1)) if x <= xx else list(range(1, xx+1)) + list(range(x, n+1)) | https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/806738/Python3-2-line | 10 | Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
Example 1:
Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
Example 2:
Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]
Example 3:
Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]
Constraints:
2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1] for 0 <= i < m | [Python3] 2-line | 1,200 | most-visited-sector-in-a-circular-track | 0.584 | ye15 | Easy | 23,046 | 1,560 |
maximum number of coins you can get | class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles.sort(reverse=True)
sum = 0
for i in range(1,len(piles)-int(len(piles)/3),2):
sum += piles[i]
print(sum)
return sum | https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1232262/Python-Simple-Solution | 2 | There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with the maximum number of coins.
Your friend Bob will pick the last pile.
Repeat until there are no more piles of coins.
Given an array of integers piles where piles[i] is the number of coins in the ith pile.
Return the maximum number of coins that you can have.
Example 1:
Input: piles = [2,4,1,2,7,8]
Output: 9
Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
The maximum number of coins which you can have are: 7 + 2 = 9.
On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.
Example 2:
Input: piles = [2,4,5]
Output: 4
Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4]
Output: 18
Constraints:
3 <= piles.length <= 105
piles.length % 3 == 0
1 <= piles[i] <= 104 | Python Simple Solution | 146 | maximum-number-of-coins-you-can-get | 0.786 | yashwant_mahawar | Medium | 23,052 | 1,561 |
find latest group of size m | class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
span = [0]*(len(arr)+2)
freq = [0]*(len(arr)+1)
ans = -1
for i, x in enumerate(arr, 1):
freq[span[x-1]] -= 1
freq[span[x+1]] -= 1
span[x] = span[x-span[x-1]] = span[x+span[x+1]] = 1 + span[x-1] + span[x+1]
freq[span[x]] += 1
if freq[m]: ans = i
return ans | https://leetcode.com/problems/find-latest-group-of-size-m/discuss/809823/Python3-summarizing-two-approaches | 0 | Given an array arr that represents a permutation of numbers from 1 to n.
You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.
You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.
Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.
Constraints:
n == arr.length
1 <= m <= n <= 105
1 <= arr[i] <= n
All integers in arr are distinct. | [Python3] summarizing two approaches | 57 | find-latest-group-of-size-m | 0.425 | ye15 | Medium | 23,086 | 1,562 |
stone game v | class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
length = len(stoneValue)
if length == 1:
return 0
# Calculate sum
s = [0 for _ in range(length)]
s[0] = stoneValue[0]
for i in range(1, length):
s[i] = s[i-1] + stoneValue[i]
# dp for best value, best_cut for where is the cut in (i, j), i, j inclusive
dp = [[0 for _ in range(length)] for _ in range(length)]
best_cut = [[0 for _ in range(length)] for _ in range(length)]
for i in range(0, length-1):
dp[i][i+1] = min(stoneValue[i], stoneValue[i+1])
best_cut[i][i+1] = i
for t in range(2, length):
for i in range(0, length-t):
tmp_dp = 0
tmp_cut = 0
left_bound = best_cut[i][i+t-1]
if left_bound > i:
left_bound -= 1
right_bound = best_cut[i+1][i+t]
if right_bound < i+t-1:
right_bound += 1
for k in range(left_bound, 1+right_bound):
s1 = s[k] - s[i-1] if i > 0 else s[k]
s2 = s[i+t] - s[k]
if s1 < s2:
tmp = s1 + dp[i][k]
if tmp > tmp_dp:
tmp_dp = tmp
tmp_cut = k
elif s1 > s2:
tmp = s2 + dp[k+1][i+t]
if tmp > tmp_dp:
tmp_dp = tmp
tmp_cut = k
else:
tmp1 = s1 + dp[i][k]
tmp2 = s2 + dp[k+1][i+t]
if tmp1 > tmp_dp:
tmp_dp = tmp1
tmp_cut = k
if tmp2 > tmp_dp:
tmp_dp = tmp2
tmp_cut = k
dp[i][i+t] = tmp_dp
best_cut[i][i+t] = tmp_cut
return dp[0][length-1] | https://leetcode.com/problems/stone-game-v/discuss/1504994/Python-O(n2)-optimized-solution.-O(n3)-cannot-pass. | 4 | There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
The game ends when there is only one stone remaining. Alice's is initially zero.
Return the maximum score that Alice can obtain.
Example 1:
Input: stoneValue = [6,2,3,4,5,5]
Output: 18
Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.
In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).
The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.
Example 2:
Input: stoneValue = [7,7,7,7,7,7,7]
Output: 28
Example 3:
Input: stoneValue = [4]
Output: 0
Constraints:
1 <= stoneValue.length <= 500
1 <= stoneValue[i] <= 106 | Python O(n^2) optimized solution. O(n^3) cannot pass. | 202 | stone-game-v | 0.406 | pureme | Hard | 23,087 | 1,563 |
detect pattern of length m repeated k or more times | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
for i in range(len(arr)-m+1):
count = 1
x = arr[i:i+m]
res = 1
for j in range(i+m,len(arr)-m+1,m):
if x == arr[j:j+m]:
count += 1
else:
res = max(res,count)
count = 1
x = arr[j:j+m]
res = max(res,count)
if res >= k:
return True
return False | https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1254278/Python3-simple-solution | 2 | Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
Constraints:
2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100 | Python3 simple solution | 124 | detect-pattern-of-length-m-repeated-k-or-more-times | 0.436 | EklavyaJoshi | Easy | 23,092 | 1,566 |
maximum length of subarray with positive product | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = pos = neg = 0
for x in nums:
if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0
elif x < 0: pos, neg = 1 + neg if neg else 0, 1 + pos
else: pos = neg = 0 # reset
ans = max(ans, pos)
return ans | https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819332/Python3-7-line-O(N)-time-and-O(1)-space | 59 | Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109 | [Python3] 7-line O(N) time & O(1) space | 2,700 | maximum-length-of-subarray-with-positive-product | 0.438 | ye15 | Medium | 23,107 | 1,567 |
minimum number of days to disconnect island | class Solution:
def minDays(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimension
grid = "".join("".join(map(str, x)) for x in grid)
@lru_cache(None)
def fn(s):
"""Return True if grid is disconnected."""
row, grid = [], []
for i, c in enumerate(s, 1):
row.append(int(c))
if i%n == 0:
grid.append(row)
row = []
def dfs(i, j):
""""""
grid[i][j] = 0
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]: dfs(ii, jj)
return 1
return sum(dfs(i, j) for i in range(m) for j in range(n) if grid[i][j])
#bfs
queue = [grid]
level = 0
seen = {grid}
while queue:
tmp = []
for node in queue:
if fn(node) == 0 or fn(node) >= 2: return level
for i in range(m*n):
if node[i] == "1":
nn = node[:i] + "0" + node[i+1:]
if nn not in seen:
seen.add(nn)
tmp.append(nn)
queue = tmp
level += 1 | https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/discuss/819360/Python3-bfs | 0 | You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.
The grid is said to be connected if we have exactly one island, otherwise is said disconnected.
In one day, we are allowed to change any single land cell (1) into a water cell (0).
Return the minimum number of days to disconnect the grid.
Example 1:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
Output: 2
Explanation: We need at least 2 days to get a disconnected grid.
Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
Example 2:
Input: grid = [[1,1]]
Output: 2
Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j] is either 0 or 1. | [Python3] bfs | 66 | minimum-number-of-days-to-disconnect-island | 0.468 | ye15 | Hard | 23,132 | 1,568 |
number of ways to reorder array to get same bst | class Solution:
def numOfWays(self, nums: List[int]) -> int:
def fn(nums):
"""Post-order traversal."""
if len(nums) <= 1: return len(nums) # boundary condition
ll = [x for x in nums if x < nums[0]]
rr = [x for x in nums if x > nums[0]]
left, right = fn(ll), fn(rr)
if not left or not right: return left or right
ans = comb(len(rr)+len(ll), len(rr))
return ans*left*right
return (fn(nums)-1) % 1_000_000_007 | https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819349/Python3-math-ish | 2 | Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.
For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.
Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [2,1,3]
Output: 1
Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
Example 2:
Input: nums = [3,4,5,1,2]
Output: 5
Explanation: The following 5 arrays will yield the same BST:
[3,1,2,4,5]
[3,1,4,2,5]
[3,1,4,5,2]
[3,4,1,2,5]
[3,4,1,5,2]
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: There are no other orderings of nums that will yield the same BST.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= nums.length
All integers in nums are distinct. | [Python3] math-ish | 337 | number-of-ways-to-reorder-array-to-get-same-bst | 0.481 | ye15 | Hard | 23,133 | 1,569 |
matrix diagonal sum | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
"""
The primary diagonal is formed by the elements A00, A11, A22, A33.
Condition for Primary Diagonal:
The row-column condition is row = column.
The secondary diagonal is formed by the elements A03, A12, A21, A30.
Condition for Secondary Diagonal:
The row-column condition is row = numberOfRows - column -1.
"""
s = 0
l , mid = len(mat), len(mat)//2
for i in range(l):
s += mat[i][i] # primary diagonal
s += mat[len(mat)-i-1][i] # secondary diagonal
# If the mat is odd, then diagonal will coincide, so subtract the middle element
if l%2 != 0:
s -= mat[mid][mid]
return s | https://leetcode.com/problems/matrix-diagonal-sum/discuss/1369404/PYTHON-Best-solution-with-explanation.-SC-%3A-O(1)-TC-%3A-O(n) | 5 | Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100 | [PYTHON] Best solution with explanation. SC : O(1) TC : O(n) | 233 | matrix-diagonal-sum | 0.798 | er1shivam | Easy | 23,135 | 1,572 |
number of ways to split a string | class Solution:
def numWays(self, s: str) -> int:
total = s.count('1')
if total % 3: return 0
n = len(s)
if not total: return (1+n-2) * (n-2) // 2 % 1000000007
avg, ans = total // 3, 0
cnt = first_part_right_zeros = last_part_left_zeros = 0
for i in range(n):
if s[i] == '1': cnt += 1
elif cnt == avg: first_part_right_zeros += 1
elif cnt > avg: break
cnt = 0
for i in range(n-1, -1, -1):
if s[i] == '1': cnt += 1
elif cnt == avg: last_part_left_zeros += 1
elif cnt > avg: break
return (first_part_right_zeros+1) * (last_part_left_zeros+1) % 1000000007 | https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830700/Python-3-or-Math-(Pass)-Backtracking-(TLE)-or-Explanation | 2 | Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.
Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "10101"
Output: 4
Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1"
"1|01|01"
"10|10|1"
"10|1|01"
Example 2:
Input: s = "1001"
Output: 0
Example 3:
Input: s = "0000"
Output: 3
Explanation: There are three ways to split s in 3 parts.
"0|0|00"
"0|00|0"
"00|0|0"
Constraints:
3 <= s.length <= 105
s[i] is either '0' or '1'. | Python 3 | Math (Pass), Backtracking (TLE) | Explanation | 215 | number-of-ways-to-split-a-string | 0.325 | idontknoooo | Medium | 23,188 | 1,573 |
shortest subarray to be removed to make array sorted | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
def lowerbound(left, right, target):
while left < right:
mid = left + (right - left) // 2
if arr[mid] == target:
right = mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid
return left
N = len(arr)
# find the longest ascending array on the left side
i = 0
while i + 1 < N and arr[i] <= arr[i+1]:
i += 1
if i == N - 1:
# it is already in ascending order
return 0
# find the longest ascending array on the right side
j = N - 1
while j - 1 >= 0 and arr[j] >= arr[j-1]:
j -= 1
if j == 0:
# the entire array is in decending order
return N - 1
# keep ascending array on right side or left side
result = min(N - (N - j), N - i -1)
# find the shortest unordered subarray in the middle
for k in range(i+1):
l = lowerbound(j, len(arr), arr[k])
result = min(result, l - (k + 1))
return result | https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/835866/Python-Solution-Based-on-Binary-Search | 4 | Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Constraints:
1 <= arr.length <= 105
0 <= arr[i] <= 109 | Python Solution Based on Binary Search | 694 | shortest-subarray-to-be-removed-to-make-array-sorted | 0.366 | pochy | Medium | 23,195 | 1,574 |
count all possible routes | class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
@lru_cache(None)
def fn(n, x):
"""Return all possible routes from n to finish with x fuel."""
if x < 0: return 0 # not going anywhere without fuel
ans = 0
if n == finish: ans += 1
for nn in range(len(locations)):
if nn != n: ans += fn(nn, x-abs(locations[n] - locations[nn]))
return ans
return fn(start, fuel) % 1_000_000_007 | https://leetcode.com/problems/count-all-possible-routes/discuss/831260/Python3-top-down-dp | 3 | You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.
Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).
Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
Explanation: The following are all possible routes, each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3
Example 2:
Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
Explanation: The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
Example 3:
Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
Constraints:
2 <= locations.length <= 100
1 <= locations[i] <= 109
All integers in locations are distinct.
0 <= start, finish < locations.length
1 <= fuel <= 200 | [Python3] top-down dp | 169 | count-all-possible-routes | 0.568 | ye15 | Hard | 23,203 | 1,575 |
replace all s to avoid consecutive repeating characters | class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for c in "abc":
if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c):
s[i] = c
break
return "".join(s) | https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/831516/Python3-one-of-three-letters | 66 | Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
Constraints:
1 <= s.length <= 100
s consist of lowercase English letters and '?'. | [Python3] one of three letters | 3,100 | replace-all-s-to-avoid-consecutive-repeating-characters | 0.491 | ye15 | Easy | 23,205 | 1,576 |
number of ways where square of number is equal to product of two numbers | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
sqr1, sqr2 = defaultdict(int), defaultdict(int)
m, n = len(nums1), len(nums2)
for i in range(m):
sqr1[nums1[i]**2] += 1
for j in range(n):
sqr2[nums2[j]**2] += 1
res = 0
for i in range(m-1):
for j in range(i+1, m):
if nums1[i]*nums1[j] in sqr2:
res += sqr2[nums1[i]*nums1[j]]
for i in range(n-1):
for j in range(i+1, n):
if nums2[i]*nums2[j] in sqr1:
res += sqr1[nums2[i]*nums2[j]]
return res | https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1658113/Python-intuitive-hashmap-solution-O(n*m)-time | 2 | Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.
Example 1:
Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8).
Example 2:
Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 12 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].
Example 3:
Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].
Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].
Constraints:
1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 105 | Python intuitive hashmap solution, O(n*m) time | 114 | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | 0.4 | byuns9334 | Medium | 23,219 | 1,577 |
minimum time to make rope colorful | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
ans = prev = 0 # index of previously retained letter
for i in range(1, len(s)):
if s[prev] != s[i]: prev = i
else:
ans += min(cost[prev], cost[i])
if cost[prev] < cost[i]: prev = i
return ans | https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/831500/Python3-greedy | 58 | Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
Example 1:
Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:
Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
n == colors.length == neededTime.length
1 <= n <= 105
1 <= neededTime[i] <= 104
colors contains only lowercase English letters. | [Python3] greedy | 3,800 | minimum-time-to-make-rope-colorful | 0.637 | ye15 | Medium | 23,224 | 1,578 |
special positions in a binary matrix | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
onesx = []
onesy = []
for ri, rv in enumerate(mat):
for ci, cv in enumerate(rv):
if cv == 1:
onesx.append(ri)
onesy.append(ci)
count = 0
for idx in range(len(onesx)):
if onesx.count(onesx[idx]) == 1:
if onesy.count(onesy[idx]) == 1:
count += 1
return count | https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1802763/Python-Memory-Efficient-Solution | 4 | Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
Example 1:
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
Example 2:
Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Explanation: (0, 0), (1, 1) and (2, 2) are special positions.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j] is either 0 or 1. | π Python Memory-Efficient Solution | 129 | special-positions-in-a-binary-matrix | 0.654 | croatoan | Easy | 23,278 | 1,582 |
count unhappy friends | class Solution:
def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
def find_preferred_friends(x: int) -> List[int]:
"""
Returns friends of x that have a higher preference than partner.
"""
partner = partners[x] # Find the partner of x.
x_friends = friend_prefs[x] # Find all the friends of x.
partner_ranking = x_friends[partner] # Get the partner's ranking amongst those friends.
return list(x_friends)[:partner_ranking] # Return all friends with a preferred lower ranking.
def is_unhappy(x: int) -> bool:
"""
Returns True if person x is unhappy, otherwise False.
"""
# Find the partner for person x.
partner = partners[x]
# Find the friends that person x prefers more than this partner.
preferred_friends = find_preferred_friends(x)
# A friend is unhappy with their partner if there is another friend with a higher preference
# and that friend prefers them over their partner.
return any(friend_prefs[friend][x] <= friend_prefs[friend][partners[friend]]
for friend in preferred_friends)
# Create dictionary to lookup friend preference for any person.
friend_prefs = {
person: {friend: pref for pref, friend in enumerate(friends)}
for person, friends in enumerate(preferences)
}
# Example:
# {0: {1: 0, 3: 1, 2: 2},
# 1: {2: 0, 3: 1, 0: 2},
# 2: {1: 0, 3: 1, 0: 2},
# 3: {0: 0, 2: 1, 1: 2}}
# Create dictionary to find anyone's partner.
partners = {}
for x, y in pairs:
partners[x] = y
partners[y] = x
# Count and return the number of unhappy people.
return sum(is_unhappy(person) for person in range(n)) | https://leetcode.com/problems/count-unhappy-friends/discuss/1103620/Readable-python-solution | 3 | You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | Readable python solution | 325 | count-unhappy-friends | 0.603 | alexanco | Medium | 23,299 | 1,583 |
min cost to connect all points | class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
manhattan = lambda p1, p2: abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
n, c = len(points), collections.defaultdict(list)
for i in range(n):
for j in range(i+1, n):
d = manhattan(points[i], points[j])
c[i].append((d, j))
c[j].append((d, i))
cnt, ans, visited, heap = 1, 0, [0] * n, c[0]
visited[0] = 1
heapq.heapify(heap)
while heap:
d, j = heapq.heappop(heap)
if not visited[j]:
visited[j], cnt, ans = 1, cnt+1, ans+d
for record in c[j]: heapq.heappush(heap, record)
if cnt >= n: break
return ans | https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/843995/Python-3-or-Min-Spanning-Tree-or-Prim's-Algorithm | 80 | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000
-106 <= xi, yi <= 106
All pairs (xi, yi) are distinct. | Python 3 | Min Spanning Tree | Prim's Algorithm | 13,100 | min-cost-to-connect-all-points | 0.641 | idontknoooo | Medium | 23,308 | 1,584 |
check if string is transformable with substring sort operations | class Solution:
def isTransformable(self, s: str, t: str) -> bool:
if sorted(s) != sorted(t): return False # edge case
pos = [deque() for _ in range(10)]
for i, ss in enumerate(s): pos[int(ss)].append(i)
for tt in t:
i = pos[int(tt)].popleft()
for ii in range(int(tt)):
if pos[ii] and pos[ii][0] < i: return False # cannot swap
return True | https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/844119/Python3-8-line-deque | 2 | Given two strings s and t, transform string s into string t using the following operation any number of times:
Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
For example, applying the operation on the underlined substring in "14234" results in "12344".
Return true if it is possible to transform s into t. Otherwise, return false.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "84532", t = "34852"
Output: true
Explanation: You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -> "84352"
"84352" (from index 0 to 2) -> "34852"
Example 2:
Input: s = "34521", t = "23415"
Output: true
Explanation: You can transform s into t using the following sort operations:
"34521" -> "23451"
"23451" -> "23415"
Example 3:
Input: s = "12345", t = "12435"
Output: false
Constraints:
s.length == t.length
1 <= s.length <= 105
s and t consist of only digits. | [Python3] 8-line deque | 198 | check-if-string-is-transformable-with-substring-sort-operations | 0.484 | ye15 | Hard | 23,325 | 1,585 |
sum of all odd length subarrays | class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
s=0
for i in range(len(arr)):
for j in range(i,len(arr),2):
s+=sum(arr[i:j+1])
return s | https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/943380/Python-Simple-Solution | 53 | Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 1000
Follow up:
Could you solve this problem in O(n) time complexity? | Python Simple Solution | 4,100 | sum-of-all-odd-length-subarrays | 0.835 | lokeshsenthilkumar | Easy | 23,326 | 1,588 |
maximum sum obtained of any permutation | class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
chg = [0]*len(nums) # change
for i, j in requests:
chg[i] += 1
if j+1 < len(nums): chg[j+1] -= 1
for i in range(1, len(nums)): chg[i] += chg[i-1] # cumulated change
return sum(n*c for n, c in zip(sorted(nums), sorted(chg))) % 1_000_000_007 | https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/discuss/858448/Python3-mark-and-sweep | 0 | We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
Output: 19
Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is [3,5,4,2,1] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
requests[1] -> nums[0] + nums[1] = 3 + 5 = 8
Total sum: 11 + 8 = 19, which is the best that you can do.
Example 2:
Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
Output: 11
Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
Example 3:
Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
Output: 47
Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] <= 105
1 <= requests.length <= 105
requests[i].length == 2
0 <= starti <= endi < n | [Python3] mark & sweep | 39 | maximum-sum-obtained-of-any-permutation | 0.37 | ye15 | Medium | 23,377 | 1,589 |
make sum divisible by p | class Solution:
def minSubarray(self, nums: List[int], p: int) -> int:
dp = defaultdict(int)
dp[0] = -1
target = sum(nums) % p
curSum = 0
result = len(nums)
if sum(nums) % p == 0: return 0
for i in range(len(nums)):
curSum += nums[i]
curMod = curSum % p
temp = (curSum - target) % p
if temp in dp:
if i - dp[temp] < result:
result = i - dp[temp]
dp[curMod] = i
return result if result < len(nums) else -1 | https://leetcode.com/problems/make-sum-divisible-by-p/discuss/1760163/WEEB-DOES-PYTHONC%2B%2B | 2 | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a contiguous block of elements in the array.
Example 1:
Input: nums = [3,1,4,2], p = 6
Output: 1
Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
Example 2:
Input: nums = [6,3,5,2], p = 9
Output: 2
Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
Example 3:
Input: nums = [1,2,3], p = 3
Output: 0
Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= p <= 109 | WEEB DOES PYTHON/C++ | 153 | make-sum-divisible-by-p | 0.28 | Skywalker5423 | Medium | 23,378 | 1,590 |
strange printer ii | class Solution:
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
visited = [0] * 61
graph = collections.defaultdict(set)
m, n = len(targetGrid), len(targetGrid[0])
for c in range(1, 61):
l,r,t,b = n,-1,m,-1
#to specify the covered range of color c
for i in range(m):
for j in range(n):
if targetGrid[i][j] == c:
l = min(l, j)
r = max(r, j)
t = min(t, i)
b = max(b, i)
#to find the contained colors
for i in range(t, b + 1):
for j in range(l, r + 1):
if targetGrid[i][j] != c:
graph[targetGrid[i][j]].add(c)
# to find if there is a cycle
def dfs(graph,i):
if visited[i] == -1:
return False
if visited[i] == 1:
return True
visited[i] = -1
for j in graph[i]:
if not dfs(graph,j):
return False
visited[i] = 1
return True
for c in range(61):
if not dfs(graph,c):
return False
return True | https://leetcode.com/problems/strange-printer-ii/discuss/911370/Same-as-CourseSchedule-Topological-sort. | 17 | There is a strange printer with the following two special requirements:
On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
Once the printer has used a color for the above operation, the same color cannot be used again.
You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.
Return true if it is possible to print the matrix targetGrid, otherwise, return false.
Example 1:
Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
Output: true
Example 2:
Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
Output: true
Example 3:
Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
Output: false
Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.
Constraints:
m == targetGrid.length
n == targetGrid[i].length
1 <= m, n <= 60
1 <= targetGrid[row][col] <= 60 | Same as CourseSchedule, Topological sort. | 810 | strange-printer-ii | 0.584 | Sakata_Gintoki | Hard | 23,382 | 1,591 |
rearrange spaces between words | class Solution(object):
def reorderSpaces(self, text):
word_list = text.split()
words, spaces = len(word_list), text.count(" ")
if words > 1:
q, r = spaces//(words-1), spaces%(words-1)
return (" " * q).join(word_list) + " " * r
else:
return "".join(word_list) + " " * spaces | https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant | 3 | You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.
Return the string after rearranging the spaces.
Example 1:
Input: text = " this is a sentence "
Output: "this is a sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
Example 2:
Input: text = " practice makes perfect"
Output: "practice makes perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
Constraints:
1 <= text.length <= 100
text consists of lowercase English letters and ' '.
text contains at least one word. | Python - simple and elegant | 176 | rearrange-spaces-between-words | 0.437 | domthedeveloper | Easy | 23,384 | 1,592 |
split a string into the max number of unique substrings | class Solution:
def maxUniqueSplit(self, s: str) -> int:
ans, n = 0, len(s)
def dfs(i, cnt, visited):
nonlocal ans, n
if i == n: ans = max(ans, cnt); return # stop condition
for j in range(i+1, n+1):
if s[i:j] in visited: continue # avoid re-visit/duplicates
visited.add(s[i:j]) # update visited set
dfs(j, cnt+1, visited) # backtracking
visited.remove(s[i:j]) # recover visited set for next possibility
dfs(0, 0, set()) # function call
return ans | https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855405/Python-3-or-Backtracking-DFS-clean-or-Explanations | 5 | Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters. | Python 3 | Backtracking, DFS, clean | Explanations | 849 | split-a-string-into-the-max-number-of-unique-substrings | 0.55 | idontknoooo | Medium | 23,407 | 1,593 |
maximum non negative product in a matrix | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def fn(i, j):
"""Return maximum & minimum products ending at (i, j)."""
if i == 0 and j == 0: return grid[0][0], grid[0][0]
if i < 0 or j < 0: return -inf, inf
if grid[i][j] == 0: return 0, 0
mx1, mn1 = fn(i-1, j) # from top
mx2, mn2 = fn(i, j-1) # from left
mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]
return (mx, mn) if grid[i][j] > 0 else (mn, mx)
mx, _ = fn(m-1, n-1)
return -1 if mx < 0 else mx % 1_000_000_007 | https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855131/Python3-top-down-dp | 36 | You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.
Notice that the modulo is performed after getting the maximum product.
Example 1:
Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: -1
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2:
Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).
Example 3:
Input: grid = [[1,3],[0,-4]]
Output: 0
Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
-4 <= grid[i][j] <= 4 | [Python3] top-down dp | 1,800 | maximum-non-negative-product-in-a-matrix | 0.33 | ye15 | Medium | 23,418 | 1,594 |
minimum cost to connect two groups of points | class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
m, n = len(cost), len(cost[0])
mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group
@lru_cache(None)
def fn(i, mask):
"""Return min cost of connecting group1[i:] and group2 represented as mask."""
if i == m: return sum(mn[j] for j in range(n) if not (mask & (1<<j)))
return min(cost[i][j] + fn(i+1, mask | 1<<j) for j in range(n))
return fn(0, 0) | https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/858187/Python3-top-down-dp | 1 | You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.
The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return the minimum cost it takes to connect the two groups.
Example 1:
Input: cost = [[15, 96], [36, 2]]
Output: 17
Explanation: The optimal way of connecting the groups is:
1--A
2--B
This results in a total cost of 17.
Example 2:
Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]
Output: 4
Explanation: The optimal way of connecting the groups is:
1--A
2--B
2--C
3--A
This results in a total cost of 4.
Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
Example 3:
Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]
Output: 10
Constraints:
size1 == cost.length
size2 == cost[i].length
1 <= size1, size2 <= 12
size1 >= size2
0 <= cost[i][j] <= 100 | [Python3] top-down dp | 169 | minimum-cost-to-connect-two-groups-of-points | 0.463 | ye15 | Hard | 23,429 | 1,595 |
crawler log folder | class Solution:
def minOperations(self, logs: List[str]) -> int:
ans = 0
for log in logs:
if log == "./": continue
elif log == "../": ans = max(0, ans-1) # parent directory
else: ans += 1 # child directory
return ans | https://leetcode.com/problems/crawler-log-folder/discuss/866343/Python3-straightforward | 11 | The Leetcode file system keeps a log each time some user performs a change folder operation.
The operations are described below:
"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
"./" : Remain in the same folder.
"x/" : Move to the child folder named x (This folder is guaranteed to always exist).
You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.
The file system starts in the main folder, then the operations in logs are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
Example 1:
Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.
Example 2:
Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3
Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0
Constraints:
1 <= logs.length <= 103
2 <= logs[i].length <= 10
logs[i] contains lowercase English letters, digits, '.', and '/'.
logs[i] follows the format described in the statement.
Folder names consist of lowercase English letters and digits. | [Python3] straightforward | 627 | crawler-log-folder | 0.644 | ye15 | Easy | 23,431 | 1,598 |
maximum profit of operating a centennial wheel | class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
ans = -1
most = pnl = waiting = 0
for i, x in enumerate(customers):
waiting += x # more people waiting in line
waiting -= (chg := min(4, waiting)) # boarding
pnl += chg * boardingCost - runningCost
if most < pnl: ans, most = i+1, pnl
q, r = divmod(waiting, 4)
if 4*boardingCost > runningCost: ans += q
if r*boardingCost > runningCost: ans += 1
return ans | https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866356/Python3-simulation | 5 | You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.
You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.
You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.
Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.
Example 1:
Input: customers = [8,3], boardingCost = 5, runningCost = 6
Output: 3
Explanation: The numbers written on the gondolas are the number of people currently there.
1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.
2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.
3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.
The highest profit was $37 after rotating the wheel 3 times.
Example 2:
Input: customers = [10,9,6], boardingCost = 6, runningCost = 4
Output: 7
Explanation:
1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.
2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.
3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.
4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.
5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.
6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.
7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.
The highest profit was $122 after rotating the wheel 7 times.
Example 3:
Input: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92
Output: -1
Explanation:
1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.
2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.
3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.
4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.
5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.
The profit was never positive, so return -1.
Constraints:
n == customers.length
1 <= n <= 105
0 <= customers[i] <= 50
1 <= boardingCost, runningCost <= 100 | [Python3] simulation | 381 | maximum-profit-of-operating-a-centennial-wheel | 0.436 | ye15 | Medium | 23,460 | 1,599 |
maximum number of achievable transfer requests | class Solution:
def maximumRequests(self, n: int, req: List[List[int]]) -> int:
tot = len(req)
for i in range(tot, 0, -1):
comb = list(itertools.combinations([j for j in range(tot)], i))
for c in comb:
net = [0 for j in range(n)]
for idx in c:
net[req[idx][0]] -= 1
net[req[idx][1]] += 1
if net == [0 for j in range(n)]:
return i
return 0 | https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866369/Python3-10-Lines-Bitmasking-or-Combinations-or-Easy-Explanation | 17 | We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.
All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.
Return the maximum number of achievable requests.
Example 1:
Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
Output: 5
Explantion: Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
Example 2:
Input: n = 3, requests = [[0,0],[1,2],[2,1]]
Output: 3
Explantion: Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
Example 3:
Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
Output: 4
Constraints:
1 <= n <= 20
1 <= requests.length <= 16
requests[i].length == 2
0 <= fromi, toi < n | [Python3] 10 Lines Bitmasking | Combinations | Easy Explanation | 1,000 | maximum-number-of-achievable-transfer-requests | 0.513 | uds5501 | Hard | 23,463 | 1,601 |
alert using same key card three or more times in a one hour period | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
key_time = {}
for index, name in enumerate(keyName):
key_time[name] = key_time.get(name, [])
key_time[name].append(int(keyTime[index].replace(":", "")))
ans = []
for name, time_list in key_time.items():
time_list.sort()
n = len(time_list)
for i in range(n-2):
if time_list[i+2] - time_list[i] <= 100:
ans.append(name)
break
return sorted(ans) | https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1284866/Python3-or-Dict-%2B-Sort | 3 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.
Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49".
Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.
Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period.
Example 1:
Input: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
Output: ["daniel"]
Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").
Example 2:
Input: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]
Output: ["bob"]
Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30").
Constraints:
1 <= keyName.length, keyTime.length <= 105
keyName.length == keyTime.length
keyTime[i] is in the format "HH:MM".
[keyName[i], keyTime[i]] is unique.
1 <= keyName[i].length <= 10
keyName[i] contains only lowercase English letters. | Python3 | Dict + Sort | 314 | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | 0.473 | Sanjaychandak95 | Medium | 23,465 | 1,604 |
find valid matrix given row and column sums | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
def backtrack(y, x):
choice = min(rowSum[y], colSum[x])
result[y][x] = choice
rowSum[y] -= choice
colSum[x] -= choice
if y == 0 and x == 0:
return
elif not rowSum[y]:
backtrack(y - 1, x)
elif not colSum[x]:
backtrack(y, x - 1)
Y, X = len(rowSum), len(colSum)
result = [[0 for _ in range(X)] for _ in range(Y)]
backtrack(Y-1, X-1)
return result | https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1734833/Python-or-Backtracking | 1 | You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
Example 1:
Input: rowSum = [3,8], colSum = [4,7]
Output: [[3,0],
[1,7]]
Explanation:
0th row: 3 + 0 = 3 == rowSum[0]
1st row: 1 + 7 = 8 == rowSum[1]
0th column: 3 + 1 = 4 == colSum[0]
1st column: 0 + 7 = 7 == colSum[1]
The row and column sums match, and all matrix elements are non-negative.
Another possible matrix is: [[1,2],
[3,5]]
Example 2:
Input: rowSum = [5,7,10], colSum = [8,6,8]
Output: [[0,5,0],
[6,1,0],
[2,0,8]]
Constraints:
1 <= rowSum.length, colSum.length <= 500
0 <= rowSum[i], colSum[i] <= 108
sum(rowSum) == sum(colSum) | Python | Backtracking | 102 | find-valid-matrix-given-row-and-column-sums | 0.78 | holdenkold | Medium | 23,473 | 1,605 |
find servers that handled most number of requests | class Solution:
def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
busy = [] # min-heap
free = list(range(k)) # min-heap
freq = [0]*k
for i, (ta, tl) in enumerate(zip(arrival, load)):
while busy and busy[0][0] <= ta:
_, ii = heappop(busy)
heappush(free, i + (ii - i) % k) # circularly relocate it
if free:
ii = heappop(free) % k
freq[ii] += 1
heappush(busy, (ta+tl, ii))
mx = max(freq)
return [i for i, x in enumerate(freq) if x == mx] | https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/1089184/Python3-summarizing-3-approaches | 13 | You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:
The ith (0-indexed) request arrives.
If all servers are busy, the request is dropped (not handled at all).
If the (i % k)th server is available, assign the request to that server.
Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.
You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.
Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.
Example 1:
Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]
Output: [1]
Explanation:
All of the servers start out available.
The first 3 requests are handled by the first 3 servers in order.
Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.
Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.
Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.
Example 2:
Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
Output: [0]
Explanation:
The first 3 requests are handled by first 3 servers.
Request 3 comes in. It is handled by server 0 since the server is available.
Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.
Example 3:
Input: k = 3, arrival = [1,2,3], load = [10,12,11]
Output: [0,1,2]
Explanation: Each server handles a single request, so they are all considered the busiest.
Constraints:
1 <= k <= 105
1 <= arrival.length, load.length <= 105
arrival.length == load.length
1 <= arrival[i], load[i] <= 109
arrival is strictly increasing. | [Python3] summarizing 3 approaches | 641 | find-servers-that-handled-most-number-of-requests | 0.429 | ye15 | Hard | 23,483 | 1,606 |
special array with x elements greater than or equal x | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if n<=nums[0]:
return n
for i in range(1,n):
count = n-i #counts number of elements in nums greater than equal i
if nums[i]>=(count) and (count)>nums[i-1]:
return count
return -1 | https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1527669/Python-or-Faster-than-94-or-2-methods-or-O(nlogn) | 5 | You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Notice that x does not have to be an element in nums.
Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.
Example 1:
Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
Example 2:
Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.
Example 3:
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000 | Python | Faster than 94% | 2 methods | O(nlogn) | 531 | special-array-with-x-elements-greater-than-or-equal-x | 0.601 | ana_2kacer | Easy | 23,484 | 1,608 |
even odd tree | class Solution:
def isEvenOddTree(self, root: TreeNode) -> bool:
even = 1 # even level
queue = deque([root])
while queue:
newq = []
prev = -inf if even else inf
for _ in range(len(queue)):
node = queue.popleft()
if even and (node.val&1 == 0 or prev >= node.val) or not even and (node.val&1 or prev <= node.val): return False
prev = node.val
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
even ^= 1
return True | https://leetcode.com/problems/even-odd-tree/discuss/877858/Python3-bfs-by-level | 1 | A binary tree is named Even-Odd if it meets the following conditions:
The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
Example 1:
Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
Explanation: The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
Example 2:
Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
Example 3:
Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 106 | [Python3] bfs by level | 103 | even-odd-tree | 0.538 | ye15 | Medium | 23,519 | 1,609 |
maximum number of visible points | class Solution:
def visiblePoints(self, points: List[List[int]], angle: int, l: List[int]) -> int:
array = []
nloc = 0
for p in points:
if p == l:
nloc += 1
else:
array.append(math.degrees(atan2(p[1]-l[1], p[0]-l[0])))
array.sort()
angles = array + [a+360 for a in array]
left, maxm = 0, 0
for right, a in enumerate(angles):
if a-angles[left] > angle:
left += 1
maxm = max(right-left+1, maxm)
return maxm + nloc | https://leetcode.com/problems/maximum-number-of-visible-points/discuss/1502236/Python-Clean-Sliding-Window | 1 | You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].
Your browser does not support the video tag or this video format.
You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.
There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
Return the maximum number of points you can see.
Example 1:
Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]
Output: 3
Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.
Example 2:
Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]
Output: 4
Explanation: All points can be made visible in your field of view, including the one at your location.
Example 3:
Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]
Output: 1
Explanation: You can only see one of the two points, as shown above.
Constraints:
1 <= points.length <= 105
points[i].length == 2
location.length == 2
0 <= angle < 360
0 <= posx, posy, xi, yi <= 100 | [Python] Clean Sliding Window | 669 | maximum-number-of-visible-points | 0.374 | soma28 | Hard | 23,527 | 1,610 |
minimum one bit operations to make integers zero | class Solution:
def minimumOneBitOperations(self, n: int) -> int:
"""
to flip the bits to turn the number to zero
Interpretation of Rules:
- recursive:
to turn a leading one of i bits to zero, the only way is to turn the i-1 bits to a leading one pattern
and to turn the i-1 bits leading zero to zero, the only way is to turn the i-2 bits to a leading one pattern
and so on, which is a recursive process
(10000.. -> 11000.. -> 01000..), (01000.. -> 01100.. -> 00100), ..., (..010 -> ..011 -> ..001 -> ..000)
- reversable:
Let's make some observations to check if there's any pattern:
- 2: 10 -> 11 -> 01 -> 00
- 4: 100 -> 101 -> 111 -> 110 -> 010 -> 011 -> 001 -> 000
- 8: 1000 -> 1001 -> 1011 -> 1010 -> 1110 -> 1111 -> 1101 -> 1100 -> 0100 -> (reversing 100 to 000) -> 0000
...
based on the observation, turning every i bits leading one to zero, is turning the i-1 bits from 00.. to 10..
and then back to 00.., which is a reverable process, and with the recursive process we can conclude that
turning any length of 00..M-> 10.. is a reversable process
- all unique states:
since it is recursive and reversable, and we are flipping every bit between 1 and 0 programtically 10.. <-> 00..
we can conclude that every intermediate state in a process is unique (2**i unique states, so we need 2**i - 1 steps)
for i bits 10.. <-> 00.. - numer of operations f(i) = 2**i - 1
this also aligns with the observation above that f(i) = 2*f(i-1) - 1 (-1 for no operation needed to achieve the initial 000)
Process:
to turn any binary to 0, we can turning the 1s to 0s one by one from lower bit to higher bit
and because turning a higher bit 1 to 0, would passing the unique state including the lower bit 1s
we can reverse those operations needed for the higher bit 100.. to the unique state including the lower bit 1s
e.g. turning 1010100 to 0
- 1010(100) -> 1010(000), we will need 2**3 - 1 operations
- 10(10000) -> 10(00000), we will need (2**5 - 1) - (2**3 - 1) operations
we will be passing the state 10(10100), which is ready available from the last state
so we can save/reverse/deduct the operations needed for 1010(000) <-> 1010(100)
- ...
so for any binary, f(binary) would tell us how many operations we need for binary <-> 000..
and for any more 1s, 100{binary} we can regard it as a process of 100.. <-> 100{binary} <-> 000{000..}
which is 100.. <-> 000.. (2**i - 1) saving the operations 100{000..} <-> 100{binary} (f(binary))
= (2**i - 1) - f(last_binary)
"""
binary = format(n, "b")
N, res = len(binary), 0
for i in range(1, N+1):
if binary[-i] == "1": res = 2**i-1 - res
return res | https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/2273798/Easy-to-understand-6-line-solution-with-explanation-or-O(N)-time-O(1)-space | 2 | Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 2:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109 | Easy to understand 6-line solution with explanation | O(N) time O(1) space | 370 | minimum-one-bit-operations-to-make-integers-zero | 0.634 | zhenyulin | Hard | 23,528 | 1,611 |
maximum nesting depth of the parentheses | class Solution:
def maxDepth(self, s: str) -> int:
depths = [0]
count = 0
for i in s:
if(i == '('):
count += 1
elif(i == ')'):
count -= 1
depths.append(count)
return max(depths) | https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1171599/Python3-Simple-And-Readable-Solution | 7 | Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation:
Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Explanation:
Digit 3 is inside of 3 nested parentheses in the string.
Example 3:
Input: s = "()(())((()()))"
Output: 3
Constraints:
1 <= s.length <= 100
s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
It is guaranteed that parentheses expression s is a VPS. | [Python3] Simple And Readable Solution | 258 | maximum-nesting-depth-of-the-parentheses | 0.827 | VoidCupboard | Easy | 23,531 | 1,614 |
maximal network rank | class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
graph = {}
for u, v in roads:
graph.setdefault(u, set()).add(v)
graph.setdefault(v, set()).add(u)
ans = 0
for i in range(n):
for j in range(i+1, n):
val = len(graph.get(i, set())) + len(graph.get(j, set())) - (j in graph.get(i, set()))
ans = max(ans, val)
return ans | https://leetcode.com/problems/maximal-network-rank/discuss/888965/Python3-graph-as-adjacency-list | 8 | There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
Example 1:
Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
Output: 4
Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
Example 2:
Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
Output: 5
Explanation: There are 5 roads that are connected to cities 1 or 2.
Example 3:
Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
Output: 5
Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
Constraints:
2 <= n <= 100
0 <= roads.length <= n * (n - 1) / 2
roads[i].length == 2
0 <= ai, bi <= n-1
ai != bi
Each pair of cities has at most one road connecting them. | [Python3] graph as adjacency list | 1,100 | maximal-network-rank | 0.581 | ye15 | Medium | 23,568 | 1,615 |
split two strings to make palindrome | class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
fn = lambda x: x == x[::-1] # check for palindrome
i = 0
while i < len(a) and a[i] == b[~i]: i += 1
if fn(a[:i] + b[i:]) or fn(a[:-i] + b[-i:]): return True
i = 0
while i < len(a) and a[~i] == b[i]: i += 1
if fn(b[:i] + a[i:]) or fn(b[:-i] + a[-i:]): return True
return False | https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/888981/Python3-greedy | 6 | You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
Return true if it is possible to form a palindrome string, otherwise return false.
Notice that x + y denotes the concatenation of strings x and y.
Example 1:
Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
Example 2:
Input: a = "xbdef", b = "xecab"
Output: false
Example 3:
Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
Constraints:
1 <= a.length, b.length <= 105
a.length == b.length
a and b consist of lowercase English letters | [Python3] greedy | 299 | split-two-strings-to-make-palindrome | 0.314 | ye15 | Medium | 23,577 | 1,616 |
count subtrees with max distance between cities | class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
# Create Tree as adjacency list
neigh: List[List[int]] = [[] for _ in range(n)]
for u, v in edges:
neigh[u - 1].append(v - 1)
neigh[v - 1].append(u - 1)
distance_array: List[int] = [0] * n
def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int:
"""Given a tree, return a central vertex (minimum radius vertex) with BFS"""
num_neighbors: List[int] = list(map(len, adj_list))
leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1))
while len(leaf_nodes) > 1:
leaf = leaf_nodes.popleft()
for neighbor in adj_list[leaf]:
num_neighbors[neighbor] -= 1
if num_neighbors[neighbor] == 1:
leaf_nodes.append(neighbor)
return leaf_nodes[0]
def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int],
child_subtrees: Dict[Tuple[int, int], int]) -> None:
""" Helper function to merge two disjoint rooted trees T_parent and T_child rooted at 'parent' and 'child',
into one tree rooted at 'parent', by adding an edge from 'parent' to 'child'.
Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees
of T_parent that contain 'parent', have diameter i, and height j.
Worst case complexity: O(n^4) per call
"""
for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()):
for (diam_for_child, height_for_child), count_from_child in child_subtrees.items():
new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1)
new_height = max(height_for_parent, height_for_child + 1)
parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent
return None
def compute_subtree_counts(current_vertex: int,
last_vertex: int = -1) -> Dict[Tuple[int, int], int]:
"""Recursively counts subtrees rooted at current_vertex using DFS,
with edge from current_vertex to 'last_vertex' (parent node) cut off"""
subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1}
for child_vertex in neigh[current_vertex]:
if child_vertex == last_vertex:
continue
merge_into_parent(parent_subtrees=subtree_counts,
child_subtrees=compute_subtree_counts(current_vertex=child_vertex,
last_vertex=current_vertex))
for (diameter, height), subtree_count in subtree_counts.items():
distance_array[diameter] += subtree_count
return subtree_counts
# Optimization: Use a max-degree vertex as our root to minimize recursion depth
max_degree_vertex: int = find_tree_center(vertices=list(range(n)),
adj_list=neigh)
compute_subtree_counts(current_vertex=max_degree_vertex)
return distance_array[1:] | https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/1068298/Python-Top-Down-DP-O(n5).-35-ms-and-faster-than-100-explained | 2 | There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.
For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.
Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.
Notice that the distance between the two cities is the number of edges in the path between them.
Example 1:
Input: n = 4, edges = [[1,2],[2,3],[2,4]]
Output: [3,4,0]
Explanation:
The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.
No subtree has two nodes where the max distance between them is 3.
Example 2:
Input: n = 2, edges = [[1,2]]
Output: [1]
Example 3:
Input: n = 3, edges = [[1,2],[2,3]]
Output: [2,1]
Constraints:
2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
All pairs (ui, vi) are distinct. | [Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained | 137 | count-subtrees-with-max-distance-between-cities | 0.657 | kcsquared | Hard | 23,584 | 1,617 |
mean of array after removing some elements | class Solution:
def trimMean(self, arr: List[int]) -> float:
arr.sort()
return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)]) | https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1193688/2-easy-Python-Solutions | 6 | Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
Answers within 10-5 of the actual answer will be considered accepted.
Example 1:
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
Example 2:
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
Output: 4.00000
Example 3:
Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
Output: 4.77778
Constraints:
20 <= arr.length <= 1000
arr.length is a multiple of 20.
0 <= arr[i] <= 105 | 2 easy Python Solutions | 617 | mean-of-array-after-removing-some-elements | 0.647 | ayushi7rawat | Easy | 23,587 | 1,619 |
coordinate with maximum network quality | class Solution:
def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:
mx = -inf
for x in range(51):
for y in range(51):
val = 0
for xi, yi, qi in towers:
d = sqrt((x-xi)**2 + (y-yi)**2)
if d <= radius: val += int(qi/(1 + d))
if val > mx:
ans = [x, y]
mx = val
return ans | https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/1103762/Python3-enumerate-all-candidates | 2 | You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.
You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.
The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula βqi / (1 + d)β, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.
Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.
Note:
A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:
x1 < x2, or
x1 == x2 and y1 < y2.
βvalβ is the greatest integer less than or equal to val (the floor function).
Example 1:
Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2
Output: [2,1]
Explanation: At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in β7 / (1 + sqrt(0)β = β7β = 7
- Quality of 5 from (1, 2) results in β5 / (1 + sqrt(2)β = β2.07β = 2
- Quality of 9 from (3, 1) results in β9 / (1 + sqrt(1)β = β4.5β = 4
No other coordinate has a higher network quality.
Example 2:
Input: towers = [[23,11,21]], radius = 9
Output: [23,11]
Explanation: Since there is only one tower, the network quality is highest right at the tower's location.
Example 3:
Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2
Output: [1,2]
Explanation: Coordinate (1, 2) has the highest network quality.
Constraints:
1 <= towers.length <= 50
towers[i].length == 3
0 <= xi, yi, qi <= 50
1 <= radius <= 50 | [Python3] enumerate all candidates | 143 | coordinate-with-maximum-network-quality | 0.376 | ye15 | Medium | 23,615 | 1,620 |
number of sets of k non overlapping line segments | class Solution:
def numberOfSets(self, n: int, k: int) -> int:
@cache
def fn(n, k):
"""Return number of sets."""
if n <= k: return 0
if k == 0: return 1
return 2*fn(n-1, k) + fn(n-1, k-1) - fn(n-2, k)
return fn(n, k) % 1_000_000_007 | https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/discuss/1103787/Python3-top-down-dp | 1 | Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.
Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.
Example 1:
Input: n = 4, k = 2
Output: 5
Explanation: The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
Example 2:
Input: n = 3, k = 1
Output: 3
Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
Example 3:
Input: n = 30, k = 7
Output: 796297179
Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
Constraints:
2 <= n <= 1000
1 <= k <= n-1 | [Python3] top-down dp | 141 | number-of-sets-of-k-non-overlapping-line-segments | 0.422 | ye15 | Medium | 23,617 | 1,621 |
largest substring between two equal characters | class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
ans = -1
seen = {}
for i, c in enumerate(s):
if c in seen: ans = max(ans, i - seen[c] - 1)
seen.setdefault(c, i)
return ans | https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/899540/Python3-via-dictionary | 13 | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.
Example 2:
Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".
Example 3:
Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.
Constraints:
1 <= s.length <= 300
s contains only lowercase English letters. | [Python3] via dictionary | 710 | largest-substring-between-two-equal-characters | 0.591 | ye15 | Easy | 23,618 | 1,624 |
lexicographically smallest string after applying operations | class Solution:
def findLexSmallestString(self, s: str, a: int, b: int) -> str:
op1 = lambda s: "".join(str((int(c)+a)%10) if i&1 else c for i, c in enumerate(s))
op2 = lambda s: s[-b:] + s[:-b]
seen = set()
stack = [s]
while stack:
s = stack.pop()
seen.add(s)
if (ss := op1(s)) not in seen: stack.append(ss)
if (ss := op2(s)) not in seen: stack.append(ss)
return min(seen) | https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899547/Python3-dfs | 7 | You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.
You can apply either of the following two operations any number of times and in any order on s:
Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951".
Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345".
Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'.
Example 1:
Input: s = "5525", a = 9, b = 2
Output: "2050"
Explanation: We can apply the following operations:
Start: "5525"
Rotate: "2555"
Add: "2454"
Add: "2353"
Rotate: "5323"
Add: "5222"
Add: "5121"
Rotate: "2151"
Add: "2050"
There is no way to obtain a string that is lexicographically smaller than "2050".
Example 2:
Input: s = "74", a = 5, b = 1
Output: "24"
Explanation: We can apply the following operations:
Start: "74"
Rotate: "47"
Add: "42"
Rotate: "24"
There is no way to obtain a string that is lexicographically smaller than "24".
Example 3:
Input: s = "0011", a = 4, b = 2
Output: "0011"
Explanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011".
Constraints:
2 <= s.length <= 100
s.length is even.
s consists of digits from 0 to 9 only.
1 <= a <= 9
1 <= b <= s.length - 1 | [Python3] dfs | 384 | lexicographically-smallest-string-after-applying-operations | 0.66 | ye15 | Medium | 23,634 | 1,625 |
best team with no conflicts | class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
'''
Using example scores = [1,2,3,5] and ages = [8,9,10,1]
data is [(1, 5), (8, 1), (9, 2), (10, 3)]
and dp is [5, 1, 2, 3]
when curr player is (1, 5)
there are no prev players -> so leave dp of curr as-is
when curr player is (8, 1)
prev player's score is not less than curr player score
nor is previous player's age same as curr player age -> so leave dp of curr as-is
when curr player is (9, 2)
prev player (1, 5) has score NOT less than, and age NOT equal to ... skipping
prev player (8, 1) has score YES less than ... so we do something!
since the accumulated dp of prev player + curr's score is GREATER than curr's accumulated dp value:
we update curr's accumulated dp value to be instead sum of prev player's dp value and curr's score
when curr player is (10, 3)
prev player (1, 5) has score NOT less, and age NTO equal to ... skipping
prev player (8, 1) has score YES less, so update curr's dp value from 3 -> 3+1 = 4
prev player (9, 2) has score YES less, so update curr's dp value from 4 -> 4+2 = 6
finally we return the max of all dp values for the dream team.
'''
# Sort by age and score ASC
data = sorted(zip(ages, scores), key=lambda x:(x[0], x[1]))
# Initialize dp with scores for each player
dp = [score for age, score in data]
N = len(data)
# For every current player
for curr in range(N):
# Compare every previous player
for prev in range(0, curr):
# And if previous player score is less OR previous player is same age
if (data[prev][1] <= data[curr][1] or data[curr][0] == data[prev][0]):
# Then update dp value for current player to be the max of either
# -> the current score as it is OR
# -> the current score PLUS the dp value of previous player
dp[curr] = max(dp[curr], data[curr][1] + dp[prev])
return max(dp) | https://leetcode.com/problems/best-team-with-no-conflicts/discuss/2848106/Python-Heavily-commented-to-self-understand-first-of-all-DP-2-Loops | 0 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.
Example 1:
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
Output: 34
Explanation: You can choose all the players.
Example 2:
Input: scores = [4,5,6,5], ages = [2,1,2,1]
Output: 16
Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
Example 3:
Input: scores = [1,2,3,5], ages = [8,9,10,1]
Output: 6
Explanation: It is best to choose the first 3 players.
Constraints:
1 <= scores.length, ages.length <= 1000
scores.length == ages.length
1 <= scores[i] <= 106
1 <= ages[i] <= 1000 | [Python] Heavily commented to self understand first of all - DP 2 Loops | 1 | best-team-with-no-conflicts | 0.412 | graceiscoding | Medium | 23,638 | 1,626 |
slowest key | class Solution:
def slowestKey(self, r: List[int], k: str) -> str:
times = {r[0]: [k[0]]}
for i in range(1 , len(r)):
t = r[i] - r[i - 1]
if(t in times):
times[t].append(k[i])
else:
times[t] = [k[i]]
keys = times[max(times.keys())]
return max(keys) | https://leetcode.com/problems/slowest-key/discuss/1172372/Python3-Simple-And-Readable-Solution | 7 | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.
The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.
Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.
Example 1:
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
Example 2:
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
Constraints:
releaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
1 <= releaseTimes[i] <= 109
releaseTimes[i] < releaseTimes[i+1]
keysPressed contains only lowercase English letters. | [Python3] Simple And Readable Solution | 337 | slowest-key | 0.593 | VoidCupboard | Easy | 23,642 | 1,629 |