problem_title
stringlengths 3
77
| python_solutions
stringlengths 81
8.45k
| post_href
stringlengths 64
213
| upvotes
int64 0
1.2k
| question
stringlengths 0
3.6k
| post_title
stringlengths 2
100
| views
int64 1
60.9k
| slug
stringlengths 3
77
| acceptance
float64 0.14
0.91
| user
stringlengths 3
26
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
| number
int64 1
2.48k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum cost to move chips to the same position | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
dic = Counter([n%2 for n in position])
return min(dic[0],dic[1]) | https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1510460/Greedy-Approach-oror-Well-Explained-oror-Easy-to-understand | 5 | We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.
Example 2:
Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.
Example 3:
Input: position = [1,1000000000]
Output: 1
Constraints:
1 <= position.length <= 100
1 <= position[i] <= 10^9 | ๐๐ Greedy Approach || Well-Explained || Easy-to-understand ๐ | 165 | minimum-cost-to-move-chips-to-the-same-position | 0.722 | abhi9Rai | Easy | 18,317 | 1,217 |
longest arithmetic subsequence of given difference | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
"""
dp is a hashtable, dp[x] is the longest subsequence ending with number x
"""
dp = {}
for x in arr:
if x - difference in dp:
dp[x] = dp[x-difference] + 1
else:
dp[x] = 1
return max(dp.values()) | https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1605339/Python3-dp-and-hash-table-easy-to-understand | 18 | Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
1 <= arr.length <= 105
-104 <= arr[i], difference <= 104 | [Python3] dp and hash table, easy to understand | 761 | longest-arithmetic-subsequence-of-given-difference | 0.518 | nick19981122 | Medium | 18,346 | 1,218 |
path with maximum gold | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
def solve(i,j,grid,vis,val):
# print(i,j,grid,vis,val)
if(i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0 or vis[i][j]):
# print(i,m,j,n)
return val
vis[i][j] = True
a = solve(i,j-1,grid,vis,val+grid[i][j])
b = solve(i,j+1,grid,vis,val+grid[i][j])
c = solve(i+1,j,grid,vis,val+grid[i][j])
d = solve(i-1,j,grid,vis,val+grid[i][j])
vis[i][j] = False
return max(a,b,c,d)
ma = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if(grid[i][j] != 0):
vis = [[False for i in range(len(grid[0]))] for j in range(len(grid))]
ma = max(ma,solve(i,j,grid,vis,0))
return ma | https://leetcode.com/problems/path-with-maximum-gold/discuss/1742414/very-easy-to-understand-using-backtracking-python3 | 1 | In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect all the gold in that cell.
From your position, you can walk one step to the left, right, up, or down.
You can't visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
There are at most 25 cells containing gold. | very easy to understand using backtracking, python3 | 99 | path-with-maximum-gold | 0.64 | jagdishpawar8105 | Medium | 18,363 | 1,219 |
count vowels permutation | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp_array = [[0] * 5 for _ in range(n + 1)]
dp_array[1] = [1, 1, 1, 1, 1]
for i in range(2, n + 1):
# a is allowed to follow e, i, or u.
dp_array[i][0] = dp_array[i - 1][1] + dp_array[i - 1][2] + dp_array[i - 1][4]
# e is allowed to follow a or i.
dp_array[i][1] = dp_array[i - 1][0] + dp_array[i - 1][2]
# i is allowed to follow e or o.
dp_array[i][2] = dp_array[i - 1][1] + dp_array[i - 1][3]
# o is allowed to follow i
dp_array[i][3] = dp_array[i - 1][2]
# u is allowed to follow i or o.
dp_array[i][4] = dp_array[i - 1][2] + dp_array[i - 1][3]
return sum(dp_array[n]) % ((10 ** 9) + 7) | https://leetcode.com/problems/count-vowels-permutation/discuss/398231/Dynamic-programming-in-Python-with-in-depth-explanation-and-diagrams | 36 | Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
Each vowel 'a' may only be followed by an 'e'.
Each vowel 'e' may only be followed by an 'a' or an 'i'.
Each vowel 'i' may not be followed by another 'i'.
Each vowel 'o' may only be followed by an 'i' or a 'u'.
Each vowel 'u' may only be followed by an 'a'.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
Example 2:
Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
Example 3:
Input: n = 5
Output: 68
Constraints:
1 <= n <= 2 * 10^4 | Dynamic programming in Python with in-depth explanation and diagrams | 1,600 | count-vowels-permutation | 0.605 | Hai_dee | Hard | 18,380 | 1,220 |
split a string in balanced strings | class Solution:
def balancedStringSplit(self, S: str) -> int:
m = c = 0
for s in S:
if s == 'L': c += 1
if s == 'R': c -= 1
if c == 0: m += 1
return m | https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403688/Python-3-(three-lines)-(beats-100.00-) | 30 | Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.
Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
2 <= s.length <= 1000
s[i] is either 'L' or 'R'.
s is a balanced string. | Python 3 (three lines) (beats 100.00 %) | 2,700 | split-a-string-in-balanced-strings | 0.848 | junaidmansuri | Easy | 18,424 | 1,221 |
queens that can attack the king | class Solution:
# Time: O(1)
# Space: O(1)
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
queen_set = {(i, j) for i, j in queens}
res = []
for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]]:
x, y = king[0], king[1]
while 0 <= x < 8 and 0 <= y < 8:
x += dx
y += dy
if (x, y) in queen_set:
res.append([x, y])
break
return res | https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/790679/Simple-Python-Solution | 5 | On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king.
You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king.
Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
Example 1:
Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
Output: [[0,1],[1,0],[3,3]]
Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Example 2:
Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
Output: [[2,2],[3,4],[4,4]]
Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Constraints:
1 <= queens.length < 64
queens[i].length == king.length == 2
0 <= xQueeni, yQueeni, xKing, yKing < 8
All the given positions are unique. | Simple Python Solution | 397 | queens-that-can-attack-the-king | 0.718 | whissely | Medium | 18,462 | 1,222 |
dice roll simulation | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
MOD = 10 ** 9 + 7
@lru_cache(None)
def func(idx, prevNum, prevNumFreq):
if idx == n:
return 1
ans = 0
for i in range(1, 7):
if i == prevNum:
if prevNumFreq < rollMax[i - 1]:
ans += func(idx + 1, i, prevNumFreq + 1)
else:
ans += func(idx + 1, i, 1)
return ans % MOD
return func(0, 0, 0) | https://leetcode.com/problems/dice-roll-simulation/discuss/1505338/Python-or-Intuitive-or-Recursion-%2B-Memo-or-Explanation | 2 | A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.
Two sequences are considered different if at least one element differs from each other.
Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30
Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181
Constraints:
1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15 | Python | Intuitive | Recursion + Memo | Explanation | 267 | dice-roll-simulation | 0.484 | detective_dp | Hard | 18,478 | 1,223 |
maximum equal frequency | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
cnt, freq, maxfreq, ans = collections.defaultdict(int), collections.defaultdict(int), 0, 0
for i, num in enumerate(nums):
cnt[num] = cnt.get(num, 0) + 1
freq[cnt[num]] += 1
freq[cnt[num]-1] -= 1
maxfreq = max(maxfreq, cnt[num])
if maxfreq == 1:
ans = i+1
elif maxfreq*freq[maxfreq] == i:
ans = i+1
elif (maxfreq-1)*(freq[maxfreq-1]+1) == i:
ans = i+1
return ans | https://leetcode.com/problems/maximum-equal-frequency/discuss/2448664/Python-easy-to-read-and-understand-or-hash-table | 1 | Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
Example 1:
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 105 | Python easy to read and understand | hash table | 73 | maximum-equal-frequency | 0.371 | sanial2001 | Hard | 18,484 | 1,224 |
airplane seat assignment probability | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 if n == 1 else 0.5 | https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/530102/Python3-symmetry | 1 | n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
Take their own seat if it is still available, and
Pick other seats randomly when they find their seat occupied
Return the probability that the nth person gets his own seat.
Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
Constraints:
1 <= n <= 105 | [Python3] symmetry | 139 | airplane-seat-assignment-probability | 0.649 | ye15 | Medium | 18,490 | 1,227 |
check if it is a straight line | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for x, y in coordinates[2:]:
if (y2 - y1) * (x - x1) != (x2 - x1) * (y - y1):
return False
return True | https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1247752/Python3-simple-solution | 6 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point. | Python3 simple solution | 176 | check-if-it-is-a-straight-line | 0.41 | EklavyaJoshi | Easy | 18,493 | 1,232 |
remove sub folders from the filesystem | class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
ans = []
for i, path in enumerate(sorted(folder)):
if i == 0 or not path.startswith(ans[-1] + "/"):
ans.append(path)
return ans | https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1196525/Python3-simple-solution-using-%22startswith%22-method | 3 | Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.
For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not.
Example 1:
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
Example 2:
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".
Example 3:
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Constraints:
1 <= folder.length <= 4 * 104
2 <= folder[i].length <= 100
folder[i] contains only lowercase letters and '/'.
folder[i] always starts with the character '/'.
Each folder name is unique. | Python3 simple solution using "startswith" method | 130 | remove-sub-folders-from-the-filesystem | 0.654 | EklavyaJoshi | Medium | 18,523 | 1,233 |
replace the substring for balanced string | class Solution:
def balancedString(self, s: str) -> int:
counter = collections.Counter(s)
n = len(s) // 4
extras = {}
for key in counter:
if counter[key] > n:
extras[key] = counter[key] - n
if not extras: return 0
i = 0
res = len(s)
for j in range(len(s)):
if s[j] in extras:
extras[s[j]] -= 1
while max(extras.values()) <= 0:
res = min(res, j-i+1)
if s[i] in extras:
extras[s[i]] += 1
i += 1
return res | https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/884039/Python3-sliding-window-with-explanation | 10 | You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.
A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Constraints:
n == s.length
4 <= n <= 105
n is a multiple of 4.
s contains only 'Q', 'W', 'E', and 'R'. | [Python3] sliding window with explanation | 888 | replace-the-substring-for-balanced-string | 0.369 | hwsbjts | Medium | 18,536 | 1,234 |
maximum profit in job scheduling | class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
jobs = sorted([(startTime[i],endTime[i],profit[i]) for i in range(len(startTime))])
heap=[]
cp,mp = 0,0 # cp->current profit, mp-> max-profit
for s,e,p in jobs:
while heap and heap[0][0]<=s:
et,tmp = heapq.heappop(heap)
cp = max(cp,tmp)
heapq.heappush(heap,(e,cp+p))
mp = max(mp,cp+p)
return mp | https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1431246/Easiest-oror-Heap-oror-98-faster-oror-Clean-and-Concise | 17 | We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 104
1 <= startTime[i] < endTime[i] <= 109
1 <= profit[i] <= 104 | ๐ Easiest || Heap || 98% faster || Clean & Concise ๐ | 1,100 | maximum-profit-in-job-scheduling | 0.512 | abhi9Rai | Hard | 18,542 | 1,235 |
find positive integer solution for a given equation | def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
x, y = 1, z
pairs = []
while x<=z and y>0:
cf = customfunction.f(x,y)
if cf==z:
pairs.append([x,y])
x, y = x+1, y-1
elif cf > z:
y -= 1
else:
x += 1
return pairs | https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/933212/Python-3-greater-91.68-faster.-O(n)-time | 27 | Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.
The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.
The judge will call your findSolution and compare your results with the answer key.
If your results match the answer key, your solution will be Accepted.
Example 1:
Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]
Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
Example 2:
Input: function_id = 2, z = 5
Output: [[1,5],[5,1]]
Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 * 5 = 5.
x=5, y=1 -> f(5, 1) = 5 * 1 = 5.
Constraints:
1 <= function_id <= 9
1 <= z <= 100
It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.
It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000. | Python 3 -> 91.68% faster. O(n) time | 1,500 | find-positive-integer-solution-for-a-given-equation | 0.693 | mybuddy29 | Medium | 18,570 | 1,237 |
circular permutation in binary representation | class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
ans = []
for i in range(1<<n):
ans.append(start ^ i ^ i >> 1)
return ans | https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1092321/Python3-backtracking | 1 | Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :
p[0] = start
p[i] and p[i+1] differ by only one bit in their binary representation.
p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
Example 1:
Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]
Example 2:
Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n | [Python3] backtracking | 117 | circular-permutation-in-binary-representation | 0.689 | ye15 | Medium | 18,578 | 1,238 |
maximum length of a concatenated string with unique characters | class Solution:
def maxLength(self,arr):
unique = ['']
res = 0
for i in range(len(arr)):
for j in range(len(unique)):
local = arr[i]+unique[j]
if len(local)==len(set(local)):
unique.append(local)
res=max(res,len(local))
return res | https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1478666/Two-Approach-oror-Well-Explained-oror-97-faster | 22 | You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] contains only lowercase English letters. | ๐ Two-Approach || Well-Explained || 97% faster ๐ | 2,200 | maximum-length-of-a-concatenated-string-with-unique-characters | 0.522 | abhi9Rai | Medium | 18,586 | 1,239 |
tiling a rectangle with the fewest squares | class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
if n == m: return 1
depth = [0]*m
def fn(x):
"""Explore tiling rectangle area via backtracking."""
nonlocal ans
if x < ans:
if min(depth) == n: ans = x # all tiled
else:
i = min(depth)
j = jj = depth.index(i) # (i, j)
while jj < m and depth[jj] == depth[j]: jj += 1
k = min(n - i, jj - j)
for kk in reversed(range(1, k+1)):
for jj in range(j, j+kk): depth[jj] += kk
fn(x+1)
for jj in range(j, j+kk): depth[jj] -= kk
ans = max(n, m)
fn(0)
return ans | https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/1216988/Python3-backtracking | 1 | Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.
Example 1:
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:
Input: n = 5, m = 8
Output: 5
Example 3:
Input: n = 11, m = 13
Output: 6
Constraints:
1 <= n, m <= 13 | [Python3] backtracking | 334 | tiling-a-rectangle-with-the-fewest-squares | 0.539 | ye15 | Hard | 18,642 | 1,240 |
minimum swaps to make strings equal | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
if s1 == s2:
return 0
else:
count = 0
d = {('xx','yy'):1,('xy','yx'):2,('yy','xx'):1,('yx','xy'):2}
x = []
y = []
for i,j in zip(s1,s2):
if i != j:
x.append(i)
y.append(j)
x.sort()
y.sort(reverse=True)
i,j = 0,0
if len(x)%2 != 0 or len(y)%2 != 0:
return -1
while i < len(x) and j < len(y):
z = (''.join(x[i:i+2]),''.join(y[i:i+2]))
if z not in d:
return -1
else:
count += d[z]
i += 2
j += 2
return count | https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/1196255/Python3-solution-using-list-and-dictionary | 2 | You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Constraints:
1 <= s1.length, s2.length <= 1000
s1.length == s2.length
s1, s2 only contain 'x' or 'y'. | Python3 solution using list and dictionary | 117 | minimum-swaps-to-make-strings-equal | 0.638 | EklavyaJoshi | Medium | 18,644 | 1,247 |
count number of nice subarrays | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
right ,left = 0,0
ans = 0
odd_cnt = 0
ans = 0
cur_sub_cnt = 0
for right in range(len(nums)):
if nums[right]%2 == 1:
odd_cnt += 1
cur_sub_cnt = 0
while odd_cnt == k:
if nums[left]%2 == 1:
odd_cnt -= 1
cur_sub_cnt += 1
left += 1
ans += cur_sub_cnt
return ans | https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1265615/Python-Two-pointer | 28 | Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length | Python - Two pointer | 1,300 | count-number-of-nice-subarrays | 0.597 | harshhx | Medium | 18,648 | 1,248 |
minimum remove to make valid parentheses | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
open = 0
s = list(s)
for i, c in enumerate(s):
if c == '(': open += 1
elif c == ')':
if not open: s[i] = ""
else: open -= 1
for i in range(len(s)-1, -1, -1):
if not open: break
if s[i] == '(': s[i] = ""; open -= 1
return "".join(s) | https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/503754/Python-Memory-Usage-Less-Than-100-Faster-than-100 | 24 | Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Example 1:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Example 2:
Input: s = "a)b(c)d"
Output: "ab(c)d"
Example 3:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Constraints:
1 <= s.length <= 105
s[i] is either '(' , ')', or lowercase English letter. | Python - Memory Usage Less Than 100%, Faster than 100% | 2,900 | minimum-remove-to-make-valid-parentheses | 0.657 | mmbhatk | Medium | 18,663 | 1,249 |
check if it is a good array | class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
import math
n = len(nums)
if n ==1:
return nums[0] ==1
d = math.gcd(nums[0], nums[1])
for i in range(n):
d = math.gcd(nums[i], d)
return d ==1 | https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/1489417/This-problem-is-about-chinese-remainder-theorem. | 2 | Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
Return True if the array is good otherwise return False.
Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6]
Output: false
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9 | This problem is about chinese remainder theorem. | 244 | check-if-it-is-a-good-array | 0.589 | byuns9334 | Hard | 18,718 | 1,250 |
cells with odd values in a matrix | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
row_data = [0]*m
col_data = [0]*n
for tup in indices:
row_data[tup[0]] = row_data[tup[0]] + 1
col_data[tup[1]] = col_data[tup[1]] + 1
odd_count = 0
for rowp in range(m):
for colp in range(n):
val = row_data[rowp] + col_data[colp]
if val % 2 != 0:
odd_count+=1
return odd_count | https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1682009/Optimal-O(m%2Bn)-space-or-O(m*n)-time-complexity-solution | 2 | There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do both of the following:
Increment all the cells on row ri.
Increment all the cells on column ci.
Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.
Example 1:
Input: m = 2, n = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.
Example 2:
Input: m = 2, n = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.
Constraints:
1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= ci < n
Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space? | Optimal O(m+n) space | O(m*n) time complexity solution | 172 | cells-with-odd-values-in-a-matrix | 0.786 | snagsbybalin | Easy | 18,722 | 1,252 |
reconstruct a 2 row binary matrix | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
s, n = sum(colsum), len(colsum)
if upper + lower != s: return []
u, d = [0] * n, [0] * n
for i in range(n):
if colsum[i] == 2 and upper > 0 and lower > 0:
u[i] = d[i] = 1
upper, lower = upper-1, lower-1
elif colsum[i] == 1:
if upper > 0 and upper >= lower:
u[i], upper = 1, upper-1
elif lower > 0 and lower > upper:
d[i], lower = 1, lower-1
else: return []
elif not colsum[i]: continue
else: return []
return [u, d] | https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/845641/Python-3-or-Greedy-or-Explanations | 3 | Given the following details of a matrix with n columns and 2 rows :
The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
The sum of elements of the 0-th(upper) row is given as upper.
The sum of elements of the 1-st(lower) row is given as lower.
The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.
Your task is to reconstruct the matrix with upper, lower and colsum.
Return it as a 2-D integer array.
If there are more than one valid solution, any of them will be accepted.
If no valid solution exists, return an empty 2-D array.
Example 1:
Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
Example 2:
Input: upper = 2, lower = 3, colsum = [2,2,1,1]
Output: []
Example 3:
Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
Constraints:
1 <= colsum.length <= 10^5
0 <= upper, lower <= colsum.length
0 <= colsum[i] <= 2 | Python 3 | Greedy | Explanations | 399 | reconstruct-a-2-row-binary-matrix | 0.438 | idontknoooo | Medium | 18,736 | 1,253 |
number of closed islands | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(i,j):
if grid[i][j]==1:
return True
if i<=0 or i>=m-1 or j<=0 or j>=n-1:
return False
grid[i][j]=1
up=dfs(i-1,j)
down=dfs(i+1,j)
left=dfs(i,j-1)
right=dfs(i,j+1)
return left and right and up and down
m,n = len(grid),len(grid[0])
c=0
# iterate through the grid from 1 to length of grid for rows and columns.
# the iteration starts from 1 because if a 0 is present in the 0th column, it can't be a closed island.
for i in range(1,m-1):
for j in range(1,n-1):
# if the item in the grid is 0 and it is surrounded by
# up, down, left, right 1's then increment the count.
if grid[i][j]==0 and dfs(i,j):
c+=1
return c | https://leetcode.com/problems/number-of-closed-islands/discuss/1250335/DFS-oror-Well-explained-oror-93-faster-oror | 14 | Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
Example 1:
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).
Example 2:
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Example 3:
Input: grid = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,1,1,1,0,1],
[1,0,1,0,1,0,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
Output: 2
Constraints:
1 <= grid.length, grid[0].length <= 100
0 <= grid[i][j] <=1 | ๐ DFS || Well-explained || 93% faster || | 836 | number-of-closed-islands | 0.642 | abhi9Rai | Medium | 18,746 | 1,254 |
maximum score words formed by letters | class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
count , n , dp = [0]*26 , len(words) , {}
for c in letters: count[ord(c) - 97] += 1
def recursion(index,count):
if index == n: return 0
tpl = tuple(count)
if (index,tpl) in dp: return dp[(index,tpl)]
ans = recursion(index + 1, count)
flag , tmp , cpy , add = True , defaultdict(int) , count.copy() , 0
for c in words[index]: tmp[c] += 1
for key in tmp:
if tmp[key] <= cpy[ord(key) - 97]:
cpy[ord(key) - 97] -= tmp[key]
add += score[ord(key) - 97] * tmp[key]
else:
flag = False
break
if flag : ans = max(ans, recursion(index + 1, cpy) + add)
dp[(index,tpl)] = ans
return ans
return recursion(0 , count) | https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/2407807/PYTHON-SOL-or-RECURSION-%2B-MEMOIZATION-or-EXPLAINED-or-CLEAR-AND-CONSCISE-or | 0 | Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.
Example 1:
Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
Output: 23
Explanation:
Score a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
Words "dad" and "dog" only get a score of 21.
Example 2:
Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
Output: 27
Explanation:
Score a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
Word "xxxz" only get a score of 25.
Example 3:
Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
Output: 0
Explanation:
Letter "e" can only be used once.
Constraints:
1 <= words.length <= 14
1 <= words[i].length <= 15
1 <= letters.length <= 100
letters[i].length == 1
score.length == 26
0 <= score[i] <= 10
words[i], letters[i] contains only lower case English letters. | PYTHON SOL | RECURSION + MEMOIZATION | EXPLAINED | CLEAR AND CONSCISE | | 42 | maximum-score-words-formed-by-letters | 0.728 | reaper_27 | Hard | 18,775 | 1,255 |
shift 2d grid | class Solution:
def rotate(self, nums: List[int], k: int) -> None: # From Leetcode Problem 189. Rotate Array
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
arr = [i for sublist in grid for i in sublist] # Flatten out the array
self.rotate(arr,k) # Rotate the array
grid = [[arr[i*n+j] for j in range(n)] for i in range(m)] # Convert Flattened output to 2d Matrix
return grid # Return 2d Result | https://leetcode.com/problems/shift-2d-grid/discuss/1935910/Just-Flatten-and-Rotate-the-Array | 5 | Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100 | โญ Just Flatten and Rotate the Array | 330 | shift-2d-grid | 0.68 | anCoderr | Easy | 18,779 | 1,260 |
greatest sum divisible by three | class Solution:
def maxSumDivThree(self, N: List[int]) -> int:
A, B, S = heapq.nsmallest(2,[n for n in N if n % 3 == 1]), heapq.nsmallest(2,[n for n in N if n % 3 == 2]), sum(N)
if S % 3 == 0: return S
if S % 3 == 1: return S - min(A[0], sum(B) if len(B) > 1 else math.inf)
if S % 3 == 2: return S - min(B[0], sum(A) if len(A) > 1 else math.inf)
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/497058/Python-3-(four-lines)-(Math-Solution)-(no-DP)-(beats-~92) | 5 | Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.
Example 3:
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
Constraints:
1 <= nums.length <= 4 * 104
1 <= nums[i] <= 104 | Python 3 (four lines) (Math Solution) (no DP) (beats ~92%) | 731 | greatest-sum-divisible-by-three | 0.509 | junaidmansuri | Medium | 18,824 | 1,262 |
minimum moves to move a box to their target location | class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
neighbors = [(0, -1), (0, 1), (-1, 0), (1, 0)]
def player_bfs(st_row, st_col, tgt_row, tgt_col):
nonlocal rows, cols
if (st_row, st_col) == (tgt_row, tgt_col):
return True
q = deque([(st_row, st_col)])
seen = [[False] * cols for _ in range(rows)]
seen[st_row][st_col] = True
while q:
row, col = q.pop()
for r, c in neighbors:
if 0 <= row+r < rows and 0 <= col+c < cols and not seen[row+r][col+c] and grid[row+r][col+c] == '.':
if row+r == tgt_row and col+c == tgt_col:
return True
seen[row+r][col+c] = True
q.appendleft((row+r, col+c))
return False
def box_bfs(st_row, st_col):
nonlocal rows, cols, target
q = deque([(st_row, st_col, start[0], start[1], 0)])
seen = {st_row, st_col, start[0], start[1]}
while q:
row, col, prow, pcol, moves = q.pop()
grid[row][col] = 'B'
for r, c in neighbors:
box_can_move = 0 <= row+r < rows and 0 <= col+c < cols and (row+r, col+c, row-r, col-c) not in seen and grid[row+r][col+c] == '.'
if box_can_move and player_bfs(prow, pcol, row-r, col-c):
if (row+r, col+c) == target:
return moves + 1
seen.add((row+r, col+c, row-r, col-c))
q.appendleft((row+r, col+c, row-r, col-c, moves+1))
grid[row][col] = '.'
return -1
start = target = box = None
rows, cols = len(grid), len(grid[0])
for r, row in enumerate(grid):
for c, pos in enumerate(row):
if pos == 'S':
start = (r, c)
grid[r][c] = '.'
elif pos == 'T':
target = (r, c)
grid[r][c] = '.'
elif pos == 'B':
box = (r, c)
grid[r][c] = '.'
return box_bfs(*box) | https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/discuss/2643673/Python3-Double-BFS-or-O(m2-*-n2) | 0 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.
Your task is to move the box 'B' to the target position 'T' under the following rules:
The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).
The character '.' represents the floor which means a free cell to walk.
The character '#' represents the wall which means an obstacle (impossible to walk there).
There is only one box 'B' and one target cell 'T' in the grid.
The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.
The player cannot walk through the box.
Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.
Example 1:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#",".","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.
Example 2:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#","#","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: -1
Example 3:
Input: grid = [["#","#","#","#","#","#"],
["#","T",".",".","#","#"],
["#",".","#","B",".","#"],
["#",".",".",".",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 5
Explanation: push the box down, left, left, up and up.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid contains only characters '.', '#', 'S', 'T', or 'B'.
There is only one character 'S', 'B', and 'T' in the grid. | Python3 Double BFS | O(m^2 * n^2) | 24 | minimum-moves-to-move-a-box-to-their-target-location | 0.49 | ryangrayson | Hard | 18,828 | 1,263 |
minimum time visiting all points | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
timer = 0
for i in range(len(points)-1):
dx = abs(points[i+1][0] - points[i][0])
dy = abs(points[i+1][1] - points[i][1])
timer = timer + max(dx,dy)
return timer | https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1114113/Python3-solution-with-explaination | 4 | On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move horizontally by one unit, or
move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
You have to visit the points in the same order as they appear in the array.
You are allowed to pass through points that appear later in the order, but these do not count as visits.
Example 1:
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds
Example 2:
Input: points = [[3,2],[-2,2]]
Output: 5
Constraints:
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000 | Python3 solution with explaination | 285 | minimum-time-visiting-all-points | 0.791 | shreytheshreyas | Easy | 18,830 | 1,266 |
count servers that communicate | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m,n = len(grid),len(grid[0])
rows = [0]*m
cols = [0]*n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j]==1:
rows[i]+=1
cols[j]+=1
total+=1
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j]==1 and rows[i]==1 and cols[j]==1:
cnt+=1
return total-cnt | https://leetcode.com/problems/count-servers-that-communicate/discuss/1587912/93-faster-oror-Well-Explained-oror-Thought-Process-oror-Clean-and-Concise | 2 | You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any other server.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.
Example 2:
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.
Example 3:
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 250
1 <= n <= 250
grid[i][j] == 0 or 1 | ๐๐ 93% faster || Well-Explained || Thought Process || Clean and Concise ๐ | 147 | count-servers-that-communicate | 0.593 | abhi9Rai | Medium | 18,862 | 1,267 |
search suggestions system | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
list_ = []
products.sort()
for i, c in enumerate(searchWord):
products = [ p for p in products if len(p) > i and p[i] == c ]
list_.append(products[:3])
return list_ | https://leetcode.com/problems/search-suggestions-system/discuss/436564/Python-A-simple-approach-without-using-Trie | 39 | You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"].
After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 104
All the strings of products are unique.
products[i] consists of lowercase English letters.
1 <= searchWord.length <= 1000
searchWord consists of lowercase English letters. | [Python] A simple approach without using Trie | 3,500 | search-suggestions-system | 0.665 | crosserclaws | Medium | 18,873 | 1,268 |
number of ways to stay in the same place after some steps | class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
M = 10 ** 9 + 7
@lru_cache(None)
def dfs(pos, steps):
# if we walk outside the array or use all the steps
# then return 0
if pos < 0 or pos > steps or pos > arrLen - 1: return 0
# if we use all the steps, return 1 only if pos is 0
if steps == 0: return pos == 0
return (
# move to the left
dfs(pos - 1, steps - 1) +
# stay at current position
dfs(pos, steps - 1) +
# move to the right
dfs(pos + 1, steps - 1)
) % M
return dfs(0, steps) | https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/2488667/LeetCode-The-Hard-Way-DP-with-Explanation | 1 | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
Example 3:
Input: steps = 4, arrLen = 2
Output: 8
Constraints:
1 <= steps <= 500
1 <= arrLen <= 106 | [LeetCode The Hard Way] DP with Explanation | 94 | number-of-ways-to-stay-in-the-same-place-after-some-steps | 0.436 | wingkwong | Hard | 18,909 | 1,269 |
find winner on a tic tac toe game | class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
# keep track of the "net score" of each row/col/diagonal
# player A adds 1 to the "net score" of each row/col/diagonal they play in,
# player B subtracts 1
# scores[0], scores[1] and scores[2] are for rows 0, 1 and 2
# scores[3], scores[4] and scores[5] are for cols 0, 1 and 2
# scores[6] and scores[7] are for the forward and backward diagonal
scores = [0] * 8
for i, (row, col) in enumerate(moves):
if i % 2 == 0: # if player A is playing
x = 1
else: # if player B is playing
x = -1
scores[row] += x
scores[col + 3] += x
if row == col:
scores[6] += x
if 2 - row == col:
scores[7] += x
for score in scores:
if score == 3:
return 'A'
elif score == -3:
return 'B'
return 'Draw' if len(moves) == 9 else 'Pending' | https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1767406/Python-3-solution-with-comments | 15 | Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
Players take turns placing characters into empty squares ' '.
The first player A always places 'X' characters, while the second player B always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never on filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
Example 1:
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: A wins, they always play first.
Example 2:
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: B wins.
Example 3:
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
Constraints:
1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe. | Python 3 solution with comments | 871 | find-winner-on-a-tic-tac-toe-game | 0.543 | dereky4 | Easy | 18,913 | 1,275 |
number of burgers with no waste of ingredients | class Solution:
def numOfBurgers(self, tomatoSlices, cheeseSlices):
# on the basis of the matrix solution
ans = [0.5 * tomatoSlices - cheeseSlices, -0.5 * tomatoSlices + 2 * cheeseSlices]
# using the constraints to see if solution satisfies it
if 0 <= int(ans[0]) == ans[0] and 0 <= int(ans[1]) == ans[1]:
return [int(ans[0]), int(ans[1])]
else:
return [] | https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/551868/Math-%2B-Python-Using-2-variables-linear-algebra-to-solve-the-problem | 3 | Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
Jumbo Burger: 4 tomato slices and 1 cheese slice.
Small Burger: 2 Tomato slices and 1 cheese slice.
Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].
Example 1:
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
Example 2:
Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
Example 3:
Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
Constraints:
0 <= tomatoSlices, cheeseSlices <= 107 | [Math + Python] Using 2 variables linear algebra to solve the problem | 203 | number-of-burgers-with-no-waste-of-ingredients | 0.506 | Suraj1127 | Medium | 18,938 | 1,276 |
count square submatrices with all ones | class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
count=matrix.count(1)
count=0
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c]==1:
count+=1
if r==0 or c==0: continue
old_val=matrix[r][c]
matrix[r][c]=min(matrix[r-1][c-1], matrix[r][c-1],matrix[r-1][c]) + 1 if matrix[r][c]==1 else 0
count= count+ matrix[r][c]- old_val
return count | https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1736397/Python-Thought-process-for-the-DP-solution-with-very-simple-explanation-(with-images) | 4 | Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
Constraints:
1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1 | Python ๐ Thought process for the DP solution with very simple explanation (with images) | 354 | count-square-submatrices-with-all-ones | 0.744 | InjySarhan | Medium | 18,949 | 1,277 |
palindrome partitioning iii | class Solution:
def palindromePartition(self, s: str, k: int) -> int:
#This is the cost function
def Cost(s):
i,j,c=0,len(s)-1,0
while i<j:
if s[i]!=s[j]:c+=1
j-=1
i+=1
return c
dp={}
# Recursion
def A(s,k):
# Memoization
if (s,k) in dp:
return dp[(s,k)]
# if k==1 then we want the whole string there is no other way
if k==1:
return Cost(s)
#intial value to max
f=float('inf')
#start checking whole string
for x in range(1,len(s)+1):
#check wheather if both the strings exist.
if len(s[:x]) and len(s[x:]):
#if exist we find the cost recursively assign min value
f=min(f,Cost(s[:x])+A(s[x:],k-1))
#store the min value
dp[(s,k)]=f
return dp[(s,k)]
return A(s,k)
``` | https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2593400/Dynamic-Programming-oror-Recursion-oror-Memoization-oror-Easy-Intuition-oror-Python | 2 | You are given a string s containing lowercase letters and an integer k. You need to :
First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.
Return the minimal number of characters that you need to change to divide the string.
Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
Example 2:
Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Example 3:
Input: s = "leetcode", k = 8
Output: 0
Constraints:
1 <= k <= s.length <= 100.
s only contains lowercase English letters. | Dynamic Programming || Recursion || Memoization || Easy Intuition || Python | 70 | palindrome-partitioning-iii | 0.608 | srikarsai550 | Hard | 18,966 | 1,278 |
subtract the product and sum of digits of an integer | class Solution:
def subtractProductAndSum(self, n: int) -> int:
p,s=1,0
while n!=0:
p*=(n%10)
s+=(n%10)
n//=10
return p-s | https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1713663/Python-3-(20ms)-or-3-Solutions-or-Fastest-Iterative-and-One-Liners-or-Super-Easy | 12 | Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Constraints:
1 <= n <= 10^5 | Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy | 659 | subtract-the-product-and-sum-of-digits-of-an-integer | 0.867 | MrShobhit | Easy | 18,970 | 1,281 |
group the people given the group size they belong to | class Solution:
# Time: O(n)
# Space: O(n)
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
res, dic = [], {}
for idx, group in enumerate(groupSizes):
if group not in dic:
dic[group] = [idx]
else:
dic[group].append(idx)
if len(dic[group]) == group:
res.append(dic[group])
del dic[group]
return res | https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/discuss/712693/Python-O(n)-Easy-to-Understand | 5 | There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n | Python O(n) Easy to Understand | 214 | group-the-people-given-the-group-size-they-belong-to | 0.857 | whissely | Medium | 19,027 | 1,282 |
find the smallest divisor given a threshold | class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
left, right = 1, max(nums)
while left + 1 < right:
mid = (left + right) // 2
div_sum = self.get_sum(mid, nums)
if div_sum > threshold:
left = mid
else:
right = mid
div_sum = self.get_sum(left, nums)
if div_sum <= threshold:
return left
return right
def get_sum(self, divisor, nums):
res = 0
for n in nums:
tmp = n // divisor
if tmp * divisor < n:
tmp += 1
res += tmp
return res | https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/discuss/863333/Python3-Binary-search-with-explanation | 3 | Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
The test cases are generated so that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106 | Python3 Binary search with explanation | 313 | find-the-smallest-divisor-given-a-threshold | 0.554 | ethuoaiesec | Medium | 19,062 | 1,283 |
minimum number of flips to convert binary matrix to zero matrix | class Solution:
def minFlips(self, G: List[List[int]]) -> int:
M, N = len(G), len(G[0])
P = [(i,j) for i,j in itertools.product(range(M),range(N))]
for n in range(M*N+1):
for p in itertools.permutations(P,n):
H = list(map(list,G))
for (x,y) in p:
for (i,j) in (x,y-1),(x,y),(x,y+1),(x-1,y),(x+1,y):
if 0 <= i < M and 0 <= j < N: H[i][j] = 1 - H[i][j]
if max(max(H)) == 0: return n
return -1
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/discuss/446552/Python-3-(ten-lines)-(Check-All-Permutations) | 3 | Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
Example 1:
Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We do not need to change it.
Example 3:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix cannot be a zero matrix.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 3
mat[i][j] is either 0 or 1. | Python 3 (ten lines) (Check All Permutations) | 441 | minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix | 0.72 | junaidmansuri | Hard | 19,077 | 1,284 |
element appearing more than 25 percent in sorted array | class Solution:
def findSpecialInteger(self, A: List[int]) -> int:
return collections.Counter(A).most_common(1)[0][0]
from statistics import mode
class Solution:
def findSpecialInteger(self, A: List[int]) -> int:
return mode(A)
class Solution:
def findSpecialInteger(self, A: List[int]) -> int:
return max(set(A), key = A.count)
class Solution:
def findSpecialInteger(self, A: List[int]) -> int:
return (lambda C: max(C.keys(), key = lambda x: C[x]))(collections.Counter(A))
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/452166/Python-3-(four-different-one-line-solutions)-(beats-100) | 18 | Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:
Input: arr = [1,1]
Output: 1
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 105 | Python 3 (four different one-line solutions) (beats 100%) | 1,800 | element-appearing-more-than-25-in-sorted-array | 0.595 | junaidmansuri | Easy | 19,078 | 1,287 |
remove covered intervals | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
res, longest = len(intervals), 0
srtd = sorted(intervals, key = lambda i: (i[0], -i[1]))
for _, end in srtd:
if end <= longest:
res -= 1
else:
longest = end
return res | https://leetcode.com/problems/remove-covered-intervals/discuss/1784520/Python3-SORTING-Explained | 46 | Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
Return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= li < ri <= 105
All the given intervals are unique. | โ๏ธ [Python3] SORTING ๐, Explained | 1,600 | remove-covered-intervals | 0.572 | artod | Medium | 19,099 | 1,288 |
minimum falling path sum ii | class Solution:
def minFallingPathSum(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
min1 = min11 = float('inf') # min1 -> minimum , min11 -> second minimum in even indexed row
min2 = min22 = float('inf') # min2 -> minimum , min22 -> second minimum in odd indexed row
for i in range(rows):
for j in range(cols):
if i==0:
if grid[i][j]<=min1: # Logic to find minimum and second minimum
min11 = min1
min1 = grid[i][j]
elif grid[i][j]<min11:
min11 = grid[i][j]
else:
if i%2:
if grid[i-1][j]==min1: # If adjacent -> then add the second minimum value
grid[i][j] += min11
else: # Else -> add the minimum value
grid[i][j] += min1
if grid[i][j]<min2: # Logic to find minimum and second minimum
min22 = min2
min2 = grid[i][j]
elif grid[i][j]<min22:
min22 = grid[i][j]
else:
if grid[i-1][j]==min2:
grid[i][j] += min22
else:
grid[i][j] += min2
if grid[i][j]<min1: # Logic to find minimum and second minimum
min11 = min1
min1 = grid[i][j]
elif grid[i][j]<min11:
min11 = grid[i][j]
if i%2: # Reset the minimum and second minimum values accordingly
min1 = min11 = float('inf')
else:
min2 = min22 = float('inf')
return min(grid[-1]) # Return the minimum element in last row | https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/1998001/Python-DP-Solution-or-Min-and-Second-min-or-Faster-than-79.77 | 2 | Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.
Example 2:
Input: grid = [[7]]
Output: 7
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
-99 <= grid[i][j] <= 99 | Python DP Solution | Min and Second min | Faster than 79.77% | 148 | minimum-falling-path-sum-ii | 0.593 | lin_lance_07 | Hard | 19,124 | 1,289 |
convert binary number in a linked list to integer | class Solution:
def getDecimalValue(self, head: ListNode) -> int:
answer = 0
while head:
answer = 2*answer + head.val
head = head.next
return answer | https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/discuss/455239/Python-Simple.-20ms. | 200 | Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
The most significant bit is at the head of the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0]
Output: 0
Constraints:
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1. | [Python] Simple. 20ms. | 7,800 | convert-binary-number-in-a-linked-list-to-integer | 0.825 | rohin7 | Easy | 19,134 | 1,290 |
sequential digits | class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
l=len(str(low))
h=len(str(high))
ans=[]
a=[12,23,34,45,56,67,78,89]
t=0
while l<=h:
for i in a:
for j in range(0,l-2):
t=i%10
if i==9:
break
i=int(str(i)+str(t+1))
if i%10==0:
break
if i>=low and i<=high:
ans.append(i)
l+=1
return ans | https://leetcode.com/problems/sequential-digits/discuss/1713379/Python-3-(20ms)-or-Faster-than-95-or-Generating-All-Sequential-Digits-within-Range | 3 | An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
Constraints:
10 <= low <= high <= 10^9 | Python 3 (20ms) | Faster than 95% | Generating All Sequential Digits within Range | 64 | sequential-digits | 0.613 | MrShobhit | Medium | 19,163 | 1,291 |
maximum side length of a square with sum less than or equal to threshold | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
ans = 0
m = len(mat)
n = len(mat[0])
presum = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
presum[i][j] = mat[i-1][j-1] + presum[i][j-1] + presum[i-1][j] - presum[i-1][j-1]
lo, hi = 1, min(i, j) + 1
while lo < hi:
mid = (lo + hi)//2
cursum = presum[i][j] - presum[i-mid][j] - presum[i][j-mid] + presum[i-mid][j-mid]
if cursum > threshold:
hi = mid
else:
lo = mid + 1
ans = max(ans, lo-1)
return ans | https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/691648/Python3-binary-search-like-bisect_right-Maximum-Side-Length-of-a-Square-with-Sum-less-Threshold | 1 | Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 300
0 <= mat[i][j] <= 104
0 <= threshold <= 105 | Python3 binary search like bisect_right - Maximum Side Length of a Square with Sum <= Threshold | 165 | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0.532 | r0bertz | Medium | 19,198 | 1,292 |
shortest path in a grid with obstacles elimination | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# x, y, obstacles, steps
q = deque([(0,0,k,0)])
seen = set()
while q:
x, y, left, steps = q.popleft()
if (x,y,left) in seen or left<0:
continue
if (x, y) == (m-1, n-1):
return steps
seen.add((x,y,left))
if grid[x][y] == 1:
left-=1
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
new_x, new_y = x+dx, y+dy
if 0<=new_x<m and 0<=new_y<n:
q.append((new_x, new_y, left, steps+1))
return -1 | https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758292/Python-Simple-and-Easy-Way-to-Solve-or-95-Faster | 14 | You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.
Example 1:
Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
Example 2:
Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: We need to eliminate at least two obstacles to find such a walk.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 40
1 <= k <= m * n
grid[i][j] is either 0 or 1.
grid[0][0] == grid[m - 1][n - 1] == 0 | โ๏ธ Python Simple and Easy Way to Solve | 95% Faster ๐ฅ | 995 | shortest-path-in-a-grid-with-obstacles-elimination | 0.456 | pniraj657 | Hard | 19,204 | 1,293 |
find numbers with even number of digits | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x)) % 2 == 0]) | https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/468107/Python-3-lightning-fast-one-line-solution | 31 | Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 105 | Python 3 lightning fast one line solution | 7,300 | find-numbers-with-even-number-of-digits | 0.77 | denisrasulev | Easy | 19,237 | 1,295 |
divide array in sets of k consecutive numbers | class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
hand = nums
W = k
if not hand and W > 0:
return False
if W > len(hand):
return False
if W == 0 or W == 1:
return True
expectation_map = {}
# self.count keep track of the numbers of cards that have been successfully counted as a straight,
# when self.count == len(hand) => All cards are part of a valid straight
self.count = 0
handLength = len(hand)
#Sort the hand.
sortedHand = sorted(hand)
"""
This method updates the expectation map in the following way:
a) If the len(l) == W
=> We've completed a straight of length W, add it towards the final count
b) if the next expected number (num+1) is already in the map
=> add the list to a queue of hands waiting to make a straight
c) if expected number (num+1) not in the map
=> Add a new expectation key with value as a new queue with this list
"""
def update_expectation_with_list(expectation_map, num, l, W):
# If we have W consecutive numbers, we're done with this set, count towards final count
if len(l) == W:
self.count += W
# we need more numbers to make this straight, add back with next expected num
else:
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append(l)
# New expected number, create new key and set [l] as value
else:
expectation_map[exp] = [l]
"""
Very similar to update_expectation_with_list. The difference here is we have the first card of the straight and thus we need to handle it correctly (set the value as a list of lists)
"""
def update_expectation_with_integer(expectation_map, num):
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append([num])
# New expected number, create new key and set [num] as value
else:
expectation_map[exp] = [[num]]
for idx,num in enumerate(sortedHand):
# A possible straight can be formed with this number
if num in expectation_map:
# there are multiple hands waiting for this number
if len(expectation_map[num]) > 1:
# pop the first hand
l = expectation_map[num].pop(0)
# add num to this hand
l.append(num)
# Update the expectation map
update_expectation_with_list(expectation_map, num, l, W)
# there's only one hand expecting this number
else:
# pop the first hand
l = expectation_map[num].pop(0)
l.append(num)
# Important : del the key! There's no other hand expecting this number
expectation_map.pop(num)
update_expectation_with_list(expectation_map, num, l, W)
# Nothing is expecting this number, add new expectation to the map
else:
update_expectation_with_integer(expectation_map, num)
return self.count == handLength | https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/785364/O(N-log(N))-time-and-O(N)-space-Python3-using-Hashmap-and-lists | 1 | Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.
Return true if it is possible. Otherwise, return false.
Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/ | O(N log(N)) time and O(N) space- Python3 using Hashmap and lists | 169 | divide-array-in-sets-of-k-consecutive-numbers | 0.566 | prajwalpv | Medium | 19,294 | 1,296 |
maximum number of occurrences of a substring | class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
s1 = []
count ={}
while minSize <= maxSize:
for i in range(0,len(s)):
if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters:
s1.append(s[i: i+ minSize])
minSize += 1
for i in s1:
count[i] = count[i] + 1 if i in count else 1
return max(count.values()) if count else 0 | https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/1905801/python-easy-approach | 4 | Given a string s, return the maximum number of occurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 occurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Constraints:
1 <= s.length <= 105
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s consists of only lowercase English letters. | python easy approach | 286 | maximum-number-of-occurrences-of-a-substring | 0.52 | hari07 | Medium | 19,299 | 1,297 |
maximum candies you can get from boxes | class Solution:
def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
myKeys = set()
canVisit = set(initialBoxes)
q = initialBoxes[:]
# Check [all keys we can get] and [all boxes we can visit]
while q:
box = q.pop(0)
myKeys.update(set((keys[box]))) # Add the keys in box into "myKeys"
canVisit.add(box) # Add current box into "canVisit"
newBoxes = containedBoxes[box] # Add next boxes to the queue
for nb in newBoxes:
q.append(nb)
ans = 0
# Visit all boxes we can visit
for i in canVisit:
# We can open the box only if we have the key or box's status is open(1)
if i in myKeys or status[i] == 1:
ans += candies[i]
return ans | https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/discuss/2841531/Easy-to-understand-BFS-Solution-(with-explanation) | 0 | You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:
status[i] is 1 if the ith box is open and 0 if the ith box is closed,
candies[i] is the number of candies in the ith box,
keys[i] is a list of the labels of the boxes you can open after opening the ith box.
containedBoxes[i] is a list of the boxes you found inside the ith box.
You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
Example 1:
Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.
Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:
Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.
The total number of candies will be 6.
Constraints:
n == status.length == candies.length == keys.length == containedBoxes.length
1 <= n <= 1000
status[i] is either 0 or 1.
1 <= candies[i] <= 1000
0 <= keys[i].length <= n
0 <= keys[i][j] < n
All values of keys[i] are unique.
0 <= containedBoxes[i].length <= n
0 <= containedBoxes[i][j] < n
All values of containedBoxes[i] are unique.
Each box is contained in one box at most.
0 <= initialBoxes.length <= n
0 <= initialBoxes[i] < n | Easy to understand BFS Solution (with explanation) | 1 | maximum-candies-you-can-get-from-boxes | 0.609 | child70370636 | Hard | 19,304 | 1,298 |
replace elements with greatest element on right side | class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
mx = arr[-1]
arr[-1] = -1
for i in range(len(arr) - 2, -1, -1):
temp = arr[i]
arr[i] = mx
if mx < temp: mx = temp
return arr | https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1058153/Easy-and-simple-python-solution-or-O(n) | 5 | Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation:
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
Example 2:
Input: arr = [400]
Output: [-1]
Explanation: There are no elements to the right of index 0.
Constraints:
1 <= arr.length <= 104
1 <= arr[i] <= 105 | Easy and simple python solution | O(n) | 510 | replace-elements-with-greatest-element-on-right-side | 0.747 | vanigupta20024 | Easy | 19,306 | 1,299 |
sum of mutated array closest to target | class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
arr.sort()
s, n = 0, len(arr)
for i in range(n):
ans = round((target - s)/n)
if ans <= arr[i]: return ans
s += arr[i]
n -= 1
return arr[-1] | https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/463586/Python3-Sort-and-scan | 20 | Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.
In case of a tie, return the minimum such integer.
Notice that the answer is not neccesarilly a number from arr.
Example 1:
Input: arr = [4,9,3], target = 10
Output: 3
Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.
Example 2:
Input: arr = [2,3,5], target = 10
Output: 5
Example 3:
Input: arr = [60864,25176,27249,21296,20204], target = 56803
Output: 11361
Constraints:
1 <= arr.length <= 104
1 <= arr[i], target <= 105 | [Python3] Sort & scan | 1,700 | sum-of-mutated-array-closest-to-target | 0.431 | ye15 | Medium | 19,347 | 1,300 |
number of paths with max score | class Solution:
def pathsWithMaxScore(self, board: List[str]) -> List[int]:
"""bottom-up dp"""
n = len(board) #dimension
#count > 0 also indicates state is reachable
dp = [[0, 0] for _ in range(n+1)] #score-count (augment by 1 for convenience)
for i in reversed(range(n)):
#not assuming reachability while updating state
copy = [[0, 0] for _ in range(n+1)] #to be updated to new dp
for j in reversed(range(n)):
if board[i][j] == "X": continue #skip obstacle
if board[i][j] == "S": #initialize "S"
copy[j] = [0, 1]
continue
#find max score from neighbors
for candidate in (copy[j+1], dp[j], dp[j+1]): #right/below/right-below
if not candidate[1]: continue #not reachable
if copy[j][0] < candidate[0]: copy[j] = candidate[:]
elif copy[j][0] == candidate[0]: copy[j][1] = (copy[j][1] + candidate[1])%(10**9+7)
#update with board number
if board[i][j] != "E": copy[j][0] += int(board[i][j])
dp = copy
return dp[0] | https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463581/Python3-Bottom-up-DP | 1 | You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.
You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.
In case there is no path, return [0, 0].
Example 1:
Input: board = ["E23","2X2","12S"]
Output: [7,1]
Example 2:
Input: board = ["E12","1X1","21S"]
Output: [4,2]
Example 3:
Input: board = ["E11","XXX","11S"]
Output: [0,0]
Constraints:
2 <= board.length == board[i].length <= 100 | [Python3] Bottom-up DP | 65 | number-of-paths-with-max-score | 0.387 | ye15 | Hard | 19,355 | 1,301 |
deepest leaves sum | class Solution:
def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
q = [(root, 0)]
ans = 0
curr_level = 0 # Maintains the current level we are at
while len(q) != 0: # Do a simple Level Order Traversal
current, max_level = q.pop(0)
if max_level > curr_level: # Update the ans as curr_level gets outdated
curr_level = max_level # Update curr_level
ans = 0 # Ans needs to be constructed for the new level i.e. max_level
ans += current.val
if current.left is not None:
q.append((current.left, max_level + 1))
if current.right is not None:
q.append((current.right, max_level + 1))
return ans | https://leetcode.com/problems/deepest-leaves-sum/discuss/1763924/Python-Simple-Level-Order-Traversal | 3 | Given the root of a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
Constraints:
The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100 | Python Simple Level Order Traversal | 139 | deepest-leaves-sum | 0.868 | anCoderr | Medium | 19,360 | 1,302 |
find n unique integers sum up to zero | class Solution:
def sumZero(self, n: int) -> List[int]:
return list(range(1,n))+[-n*(n-1)//2] | https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/463818/Two-Solutions-in-Python-3-(one-line)-(beats-100)-(24-ms) | 12 | Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
Constraints:
1 <= n <= 1000 | Two Solutions in Python 3 (one line) (beats 100%) (24 ms) | 1,300 | find-n-unique-integers-sum-up-to-zero | 0.771 | junaidmansuri | Easy | 19,393 | 1,304 |
all elements in two binary search trees | class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
h = lambda r: h(r.left) + [r.val] + h(r.right) if r else []
return sorted( h(root1) + h(root2) ) | https://leetcode.com/problems/all-elements-in-two-binary-search-trees/discuss/523589/python-only-2-lines-easy-to-read-with-explanation.-Can-it-be-any-shorter | 2 | Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]
Constraints:
The number of nodes in each tree is in the range [0, 5000].
-105 <= Node.val <= 105 | python, only 2 lines, easy to read, with explanation. Can it be any shorter? | 155 | all-elements-in-two-binary-search-trees | 0.798 | rmoskalenko | Medium | 19,438 | 1,305 |
jump game iii | class Solution:
def canReach(self, arr: List[int], i: int) -> bool:
if i < 0 or i >= len(arr) or arr[i] < 0: return False
arr[i] *= -1 # Mark visited
return arr[i] == 0 or self.canReach(arr, i - arr[i]) or self.canReach(arr, i + arr[i]) | https://leetcode.com/problems/jump-game-iii/discuss/571683/Python3-3-Lines-DFS.-O(N)-time-and-space.-Recursion | 5 | Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 104
0 <= arr[i] < arr.length
0 <= start < arr.length | [Python3] 3 Lines DFS. O(N) time and space. Recursion | 245 | jump-game-iii | 0.631 | jimmyyentran | Medium | 19,463 | 1,306 |
verbal arithmetic puzzle | class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
if max(map(len, words)) > len(result): return False # edge case
words.append(result)
digits = [0]*10
mp = {} # mapping from letter to digit
def fn(i, j, val):
"""Find proper mapping for words[i][~j] and result[~j] via backtracking."""
if j == len(result): return val == 0 # base condition
if i == len(words): return val % 10 == 0 and fn(0, j+1, val//10)
if j >= len(words[i]): return fn(i+1, j, val)
if words[i][~j] in mp:
if j and j+1 == len(words[i]) and mp[words[i][~j]] == 0: return # backtrack (no leading 0)
if i+1 == len(words): return fn(i+1, j, val - mp[words[i][~j]])
else: return fn(i+1, j, val + mp[words[i][~j]])
else:
for k, x in enumerate(digits):
if not x and (k or j == 0 or j+1 < len(words[i])):
mp[words[i][~j]] = k
digits[k] = 1
if i+1 == len(words) and fn(i+1, j, val-k): return True
if i+1 < len(words) and fn(i+1, j, val+k): return True
digits[k] = 0
mp.pop(words[i][~j])
return fn(0, 0, 0) | https://leetcode.com/problems/verbal-arithmetic-puzzle/discuss/1216642/Python3-backtracking | 4 | Given an equation, represented by words on the left side and the result on the right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
No two characters can map to the same digit.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on the left side (words) will equal to the number on the right side (result).
Return true if the equation is solvable, otherwise return false.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Explanation: There is no possible mapping to satisfy the equation, so we return false.
Note that two different characters cannot map to the same digit.
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contain only uppercase English letters.
The number of different characters used in the expression is at most 10. | [Python3] backtracking | 398 | verbal-arithmetic-puzzle | 0.348 | ye15 | Hard | 19,508 | 1,307 |
decrypt string from alphabet to integer mapping | class Solution:
def freqAlphabets(self, s: str) -> str:
for i in range(26,0,-1): s = s.replace(str(i)+'#'*(i>9),chr(96+i))
return s
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/discuss/470770/Python-3-(two-lines)-(beats-100)-(16-ms)-(With-Explanation) | 107 | You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.
The test cases are generated so that a unique mapping will always exist.
Example 1:
Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
Example 2:
Input: s = "1326#"
Output: "acz"
Constraints:
1 <= s.length <= 1000
s consists of digits and the '#' letter.
s will be a valid string such that mapping is always possible. | Python 3 (two lines) (beats 100%) (16 ms) (With Explanation) | 6,100 | decrypt-string-from-alphabet-to-integer-mapping | 0.795 | junaidmansuri | Easy | 19,511 | 1,309 |
xor queries of a subarray | class Solution:
def xorQueries(self, A: List[int], Q: List[List[int]]) -> List[int]:
B = [A[0]]
for a in A[1:]: B.append(B[-1]^a)
B.append(0)
return [B[L-1]^B[R] for L,R in Q] | https://leetcode.com/problems/xor-queries-of-a-subarray/discuss/470834/Python-3-(two-lines)-(beats-100)-(412-ms) | 5 | You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).
Return an array answer where answer[i] is the answer to the ith query.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
Example 2:
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]
Constraints:
1 <= arr.length, queries.length <= 3 * 104
1 <= arr[i] <= 109
queries[i].length == 2
0 <= lefti <= righti < arr.length | Python 3 (two lines) (beats 100%) (412 ms) | 639 | xor-queries-of-a-subarray | 0.722 | junaidmansuri | Medium | 19,550 | 1,310 |
get watched videos by your friends | class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
queue = [id]
count = 0
seen = set(queue)
while queue and count < level: #bfs
count += 1
temp = set()
for i in queue:
for j in friends[i]:
if j not in seen:
temp.add(j)
seen.add(j)
queue = temp
movies = dict()
for i in queue:
for m in watchedVideos[i]:
movies[m] = movies.get(m, 0) + 1
return [k for _, k in sorted((v, k) for k, v in movies.items())] | https://leetcode.com/problems/get-watched-videos-by-your-friends/discuss/491936/Python3-Breadth-first-search | 2 | There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.
Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.
Example 1:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
Explanation:
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = ["C"]
Person with id = 2 -> watchedVideos = ["B","C"]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2
Example 2:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation:
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
Constraints:
n == watchedVideos.length == friends.length
2 <= n <= 100
1 <= watchedVideos[i].length <= 100
1 <= watchedVideos[i][j].length <= 8
0 <= friends[i].length < n
0 <= friends[i][j] < n
0 <= id < n
1 <= level < n
if friends[i] contains j, then friends[j] contains i | [Python3] Breadth-first search | 322 | get-watched-videos-by-your-friends | 0.459 | ye15 | Medium | 19,563 | 1,311 |
minimum insertion steps to make a string palindrome | class Solution:
def minInsertions(self, S: str) -> int:
L = len(S)
DP = [[0 for _ in range(L+1)] for _ in range(L+1)]
for i,j in itertools.product(range(L),range(L)): DP[i+1][j+1] = DP[i][j] + 1 if S[i] == S[L-1-j] else max(DP[i][j+1],DP[i+1][j])
return L - DP[-1][-1]
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/470856/Python-3-(four-lines)-(DP)-(LCS) | 2 | Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters. | Python 3 (four lines) (DP) (LCS) | 537 | minimum-insertion-steps-to-make-a-string-palindrome | 0.657 | junaidmansuri | Hard | 19,570 | 1,312 |
decompress run length encoded list | class Solution:
def decompressRLElist(self, N: List[int]) -> List[int]:
L, A = len(N), []
for i in range(0,L,2):
A.extend(N[i]*[N[i+1]])
return A | https://leetcode.com/problems/decompress-run-length-encoded-list/discuss/478426/Python-3-(one-line)-(beats-100) | 23 | We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
Example 1:
Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
Example 2:
Input: nums = [1,1,2,3]
Output: [1,3,3]
Constraints:
2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100 | Python 3 (one line) (beats 100%) | 3,400 | decompress-run-length-encoded-list | 0.859 | junaidmansuri | Easy | 19,585 | 1,313 |
matrix block sum | class Solution:
def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
mat[:] = [[0] * (n + 1)] + [[0] + row for row in mat]
res = [[0] * n for i in range(m)]
for i in range(1, m + 1):
for j in range(1, n + 1):
mat[i][j] += mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1]
for i in range(m):
for j in range(n):
r1, r2 = max(i - K, 0), min(i + K + 1, m)
c1, c2 = max(j - K, 0), min(j + K + 1, n)
res[i][j] = mat[r2][c2] - mat[r2][c1] - mat[r1][c2] + mat[r1][c1]
return res | https://leetcode.com/problems/matrix-block-sum/discuss/711729/Python-DP-O(m*n) | 8 | Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100 | Python DP O(m*n) | 1,100 | matrix-block-sum | 0.754 | SWeszler | Medium | 19,632 | 1,314 |
sum of nodes with even valued grandparent | class Solution:
def __init__(self):
self.summary = 0
def sumEvenGrandparent(self, root: TreeNode) -> int:
self.walk(root, False, False)
return self.summary
def walk(self, node: TreeNode, parent_even: bool, grand_parent_even: bool):
if node is None:
return
if grand_parent_even:
self.summary += node.val
next_parent_even = True if node.val % 2 == 0 else False
self.walk(node.left, next_parent_even, parent_even)
self.walk(node.right, next_parent_even, parent_even)
return | https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/514777/Python3-96ms-solution | 7 | Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists.
Example 1:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
Example 2:
Input: root = [1]
Output: 0
Constraints:
The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100 | Python3 96ms solution | 740 | sum-of-nodes-with-even-valued-grandparent | 0.856 | tjucoder | Medium | 19,650 | 1,315 |
distinct echo substrings | class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
n = len(text)
def helper(size):
base = 1 << 5
M = 10 ** 9 + 7
a = pow(base, size, M)
t = 0
vis = defaultdict(set)
vis_pattern = set()
ans = 0
for i in range(n):
t = (base * t + ord(text[i]) - ord('a')) % M
if i >= size:
t -= a * (ord(text[i - size]) - ord('a'))
t %= M
if t not in vis_pattern and (i - size * 2 + 1) in vis[t]:
ans += 1
vis_pattern.add(t)
if i >= size - 1:
vis[t].add(i - size + 1)
return ans
return sum(helper(size) for size in range(1, n//2+1)) | https://leetcode.com/problems/distinct-echo-substrings/discuss/1341886/Python-3-Rolling-hash-(5780ms) | 2 | Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000
text has only lowercase English letters. | [Python 3] Rolling hash (5780ms) | 203 | distinct-echo-substrings | 0.497 | chestnut890123 | Hard | 19,672 | 1,316 |
convert integer to the sum of two no zero integers | class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
left = 0
right = n
ans = []
while True:
if str(left).count("0")==0 and str(right).count("0")==0:
ans.append(left)
ans.append(right)
break
left+=1
right-=1
return ans | https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/discuss/1219360/Python-Fast-and-Easy-Soln | 2 | No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.
Given an integer n, return a list of two integers [a, b] where:
a and b are No-Zero integers.
a + b = n
The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.
Example 1:
Input: n = 2
Output: [1,1]
Explanation: Let a = 1 and b = 1.
Both a and b are no-zero integers, and a + b = 2 = n.
Example 2:
Input: n = 11
Output: [2,9]
Explanation: Let a = 2 and b = 9.
Both a and b are no-zero integers, and a + b = 9 = n.
Note that there are other valid answers as [8, 3] that can be accepted.
Constraints:
2 <= n <= 104 | Python Fast & Easy Soln | 212 | convert-integer-to-the-sum-of-two-no-zero-integers | 0.56 | iamkshitij77 | Easy | 19,676 | 1,317 |
minimum flips to make a or b equal to c | class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
count = 0
while a or b or c:
if (a & 1) | (b & 1) != (c & 1):
if (c & 1): count += 1
else: count += (a & 1) + (b & 1)
a, b, c = a >> 1, b >> 1, c >> 1
return count | https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/489623/Python-Simple-Solution-Python-Memory-usage-less-than-100 | 5 | Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Example 1:
Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Example 2:
Input: a = 4, b = 2, c = 7
Output: 1
Example 3:
Input: a = 1, b = 2, c = 3
Output: 0
Constraints:
1 <= a <= 10^9
1 <= b <= 10^9
1 <= c <= 10^9 | Python - Simple Solution - Python - Memory usage less than 100% | 339 | minimum-flips-to-make-a-or-b-equal-to-c | 0.66 | mmbhatk | Medium | 19,692 | 1,318 |
number of operations to make network connected | class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
self.components = n
# We need atleast n-1 connections to connect n networks
if(len(connections) < n-1):
return -1
# If we have n-1 connections, we only need to count to number of components
# Union-Find
parent = [i for i in range(0, n)]
rank = [0] * n
for x, y in connections:
self.union(x, y, parent, rank)
# we require no. of components - 1 edge to connect n components
return self.components - 1
def find(self, x, parent):
if(parent[x] != x):
parent[x] = self.find(parent[x], parent)
return parent[x]
def union(self, x, y, parent, rank):
parent_x = self.find(x, parent)
parent_y = self.find(y, parent)
if(parent_x == parent_y):
return
rank_x = rank[parent_x]
rank_y = rank[parent_y]
if(rank_x > rank_y):
parent[parent_y] = parent_x
elif(rank_x < rank_y):
parent[parent_x] = parent_y
else:
parent[parent_y] = parent_x
rank[parent_x] += 1
self.components -= 1 | https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2420269/Operations-to-make-network-connected-oror-Python3-oror-Union-Find | 1 | There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.
Example 1:
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
Example 2:
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Example 3:
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.
Constraints:
1 <= n <= 105
1 <= connections.length <= min(n * (n - 1) / 2, 105)
connections[i].length == 2
0 <= ai, bi < n
ai != bi
There are no repeated connections.
No two computers are connected by more than one cable. | Operations to make network connected || Python3 || Union-Find | 30 | number-of-operations-to-make-network-connected | 0.585 | vanshika_2507 | Medium | 19,707 | 1,319 |
minimum distance to type a word using two fingers | class Solution:
def minimumDistance(self, word: str) -> int:
def dist(pre,cur):
if pre==None:
return 0
x1,y1 = divmod(ord(pre)-ord('A'),6)
x2,y2 = divmod(ord(cur)-ord('A'),6)
return abs(x1-x2) + abs(y1-y2)
@lru_cache(None)
def fingers(i,l,r):
if i == len(word):
return 0
n1 = dist(l,word[i]) + fingers(i+1,word[i],r)
n2 = dist(r,word[i]) + fingers(i+1,l,word[i])
return min(n1,n2)
return fingers(0,None,None) | https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/1509241/Well-Coded-oror-Clean-and-Concise-oror-93-faster | 2 | You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).
Given the string word, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Example 1:
Input: word = "CAKE"
Output: 3
Explanation: Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3
Example 2:
Input: word = "HAPPY"
Output: 6
Explanation: Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6
Constraints:
2 <= word.length <= 300
word consists of uppercase English letters. | ๐๐ Well-Coded || Clean & Concise || 93% faster ๐ | 228 | minimum-distance-to-type-a-word-using-two-fingers | 0.597 | abhi9Rai | Hard | 19,720 | 1,320 |
maximum 69 number | class Solution:
def maximum69Number (self, nums: int) -> int:
nums = str(nums) #changing integer to string
j = 1 #maximum number you can change atmost
for i in range(len(nums)):
if nums[i] == "6" and (j == 1): #checking if the element is "6" and we are change only once
bef = nums[:i] #stored element before the element 6 using slicing
aft = nums[i+1:] #stored element after the element 6 using slicing
nums = bef + "9"+aft #adding element in place of 6
j-=1 # we will reduct 1. so that above condition cant satisfy again.
nums = int(nums)
return nums | https://leetcode.com/problems/maximum-69-number/discuss/2787125/PYTHON-oror-EASY-TO-UNDERSTAND-oror-WELL-EXPLAINED | 5 | You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Constraints:
1 <= num <= 104
num consists of only 6 and 9 digits. | PYTHON || EASY TO UNDERSTAND || WELL EXPLAINED | 372 | maximum-69-number | 0.821 | thesunnysinha | Easy | 19,724 | 1,323 |
print words vertically | class Solution:
def printVertically(self, s: str) -> List[str]:
st=0 # track of index to take element from each word
s=s.split()
ans=[]
y=0
for i in s:
y=max(y,len(i))
while st<y:
u=[]
for i in s:
if st<len(i):
u.append(i[st])
else:
u.append(' ')# adding spaces if word length is less
while u[-1]==' ': # using stack operation to remove trailing spaces
u.pop()
ans.append(''.join(u))
st+=1# increasing index at each iteration
return ans | https://leetcode.com/problems/print-words-vertically/discuss/1277233/python-94.44-or-easy-or-with-comments | 2 | Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
Example 1:
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
"HAY"
"ORO"
"WEU"
Example 2:
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE"," T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
" T"
Example 3:
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]
Constraints:
1 <= s.length <= 200
s contains only upper case English letters.
It's guaranteed that there is only one space between 2 words. | python 94.44% | easy | with comments | 140 | print-words-vertically | 0.604 | chikushen99 | Medium | 19,781 | 1,324 |
delete leaves with a given value | class Solution:
def removeLeafNodes(self, R: TreeNode, t: int) -> TreeNode:
def RLN(R):
if R == None: return None
R.left, R.right = RLN(R.left), RLN(R.right)
return None if R.val == t and R.left == R.right else R
return RLN(R)
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/484504/Python-3-(beats-100)-(five-lines)-(recursive) | 2 | Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
Example 1:
Input: root = [1,2,3,2,null,2,4], target = 2
Output: [1,null,3,null,4]
Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left).
After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
Example 2:
Input: root = [1,3,3,3,2], target = 3
Output: [1,3,null,null,2]
Example 3:
Input: root = [1,2,null,2,null,2], target = 2
Output: [1]
Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
Constraints:
The number of nodes in the tree is in the range [1, 3000].
1 <= Node.val, target <= 1000 | Python 3 (beats 100%) (five lines) (recursive) | 302 | delete-leaves-with-a-given-value | 0.747 | junaidmansuri | Medium | 19,806 | 1,325 |
minimum number of taps to open to water a garden | class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
jumps = [0]*(n+1)
for i in range(n+1):
l, r = max(0,i-ranges[i]), min(n,i+ranges[i])
jumps[l] = max(jumps[l],r-l)
step = start = end = 0
while end < n:
start, end = end+1, max(i+jumps[i] for i in range(start, end+1))
if start > end:
return -1
step += 1
return step | https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/484299/Python-%3A-O(N) | 22 | There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e., the length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
Example 1:
Input: n = 5, ranges = [3,4,1,1,0,0]
Output: 1
Explanation: The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]
Example 2:
Input: n = 3, ranges = [0,0,0,0]
Output: -1
Explanation: Even if you activate all the four taps you cannot water the whole garden.
Constraints:
1 <= n <= 104
ranges.length == n + 1
0 <= ranges[i] <= 100 | Python : O(N) | 2,500 | minimum-number-of-taps-to-open-to-water-a-garden | 0.477 | fallenranger | Hard | 19,825 | 1,326 |
break a palindrome | class Solution:
def breakPalindrome(self, palindrome: str) -> str:
n = len(palindrome)
if n == 1: return ''
for i, c in enumerate(palindrome):
if c != 'a' and ((i != n // 2 and n % 2) or not n % 2): return palindrome[:i] + 'a' + palindrome[i+1:]
else: return palindrome[:-1] + 'b' | https://leetcode.com/problems/break-a-palindrome/discuss/846873/Python-3-or-Greedy-one-pass-or-Explanations | 7 | Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.
Example 1:
Input: palindrome = "abccba"
Output: "aaccba"
Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".
Of all the ways, "aaccba" is the lexicographically smallest.
Example 2:
Input: palindrome = "a"
Output: ""
Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
Constraints:
1 <= palindrome.length <= 1000
palindrome consists of only lowercase English letters. | Python 3 | Greedy one pass | Explanations | 1,300 | break-a-palindrome | 0.531 | idontknoooo | Medium | 19,838 | 1,328 |
sort the matrix diagonally | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
d = defaultdict(list)
for i in range(len(mat)):
for j in range(len(mat[0])):
d[i-j].append(mat[i][j])
for k in d.keys():
d[k].sort()
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j] = d[i-j].pop(0)
return mat | https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/920657/Python3-simple-solution | 8 | A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].
Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Example 2:
Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100 | Python3 simple solution | 463 | sort-the-matrix-diagonally | 0.836 | ermolushka2 | Medium | 19,889 | 1,329 |
reverse subarray to maximize array value | class Solution:
def maxValueAfterReverse(self, nums: List[int]) -> int:
maxi, mini = -math.inf, math.inf
for a, b in zip(nums, nums[1:]):
maxi = max(min(a, b), maxi)
mini = min(max(a, b), mini)
change = max(0, (maxi - mini) * 2)
# solving the boundary situation
for a, b in zip(nums, nums[1:]):
tmp1 = - abs(a - b) + abs(nums[0] - b)
tmp2 = - abs(a - b) + abs(nums[-1] - a)
change = max([tmp1, tmp2, change])
original_value = sum(abs(a - b) for a, b in zip(nums, nums[1:]))
return original_value + change | https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489882/O(n)-Solution-with-explanation | 325 | You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.
You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.
Find maximum possible value of the final array.
Example 1:
Input: nums = [2,3,1,5,4]
Output: 10
Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.
Example 2:
Input: nums = [2,4,9,24,2,1,10]
Output: 68
Constraints:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105 | O(n) Solution with explanation | 7,300 | reverse-subarray-to-maximize-array-value | 0.401 | neal99 | Hard | 19,929 | 1,330 |
rank transform of an array | class Solution:
"""
Time: O(n*log(n))
Memory: O(n)
"""
def arrayRankTransform(self, arr: List[int]) -> List[int]:
ranks = {num: r for r, num in enumerate(sorted(set(arr)), start=1)}
return [ranks[num] for num in arr] | https://leetcode.com/problems/rank-transform-of-an-array/discuss/2421511/Python-Elegant-and-Short-or-Two-lines-or-HashMap-%2B-Sorting | 2 | Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.
Example 1:
Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:
Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.
Example 3:
Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]
Constraints:
0 <= arr.length <= 105
-109 <= arr[i] <= 109 | Python Elegant & Short | Two lines | HashMap + Sorting | 220 | rank-transform-of-an-array | 0.591 | Kyrylo-Ktl | Easy | 19,930 | 1,331 |
remove palindromic subsequences | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s == s[::-1] else 2 | https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner | 45 | You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: s is already a palindrome, so its entirety can be removed in a single step.
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Constraints:
1 <= s.length <= 1000
s[i] is either 'a' or 'b'. | โ
Python || 2 Easy || One liner | 3,500 | remove-palindromic-subsequences | 0.761 | constantine786 | Easy | 19,954 | 1,332 |
filter restaurants by vegan friendly, price and distance | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
def f(x):
if (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance):
return True
else:
return False
y = list(filter(f,restaurants))
y.sort(key=lambda a:a[0],reverse=True)
y.sort(key=lambda a:a[1],reverse=True)
return [i[0] for i in y] | https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/1464395/Python3-solution | 3 | Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.
The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.
Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.
Example 1:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
Output: [3,1,5]
Explanation:
The restaurants are:
Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1]
After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).
Example 2:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
Output: [4,3,2,1,5]
Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.
Example 3:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
Output: [4,5]
Constraints:
1 <= restaurants.length <= 10^4
restaurants[i].length == 5
1 <= idi, ratingi, pricei, distancei <= 10^5
1 <= maxPrice, maxDistance <= 10^5
veganFriendlyi and veganFriendly are 0 or 1.
All idi are distinct. | Python3 solution | 242 | filter-restaurants-by-vegan-friendly-price-and-distance | 0.596 | EklavyaJoshi | Medium | 19,992 | 1,333 |
find the city with the smallest number of neighbors at a threshold distance | class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
"""Floyd-Warshall algorithm"""
dist = [[float("inf")]*n for _ in range(n)]
for i in range(n): dist[i][i] = 0
for i, j, w in edges: dist[i][j] = dist[j][i] = w
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
ans = {sum(d <= distanceThreshold for d in dist[i]): i for i in range(n)}
return ans[min(ans)] | https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/491784/Python3-Floyd-Warshall-algo | 2 | There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
Example 1:
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
Example 2:
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.
Constraints:
2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
All pairs (fromi, toi) are distinct. | [Python3] Floyd-Warshall algo | 98 | find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance | 0.533 | ye15 | Medium | 20,000 | 1,334 |
minimum difficulty of a job schedule | class Solution:
def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
jobCount = len(jobDifficulty)
if jobCount < d:
return -1
@lru_cache(None)
def topDown(jobIndex: int, remainDayCount: int) -> int:
remainJobCount = jobCount - jobIndex
if remainDayCount == 1:
return max(jobDifficulty[jobIndex:])
if remainJobCount == remainDayCount:
return sum(jobDifficulty[jobIndex:])
minDiff = float('inf')
maxToday = 0
for i in range(jobIndex, jobCount - remainDayCount + 1):
maxToday = max(maxToday, jobDifficulty[i])
minDiff = min(minDiff, maxToday + topDown(i+1, remainDayCount-1))
return minDiff
return topDown(0, d) | https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709132/91-Faster-Solution | 4 | You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.
Example 1:
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
Example 2:
Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
Example 3:
Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.
Constraints:
1 <= jobDifficulty.length <= 300
0 <= jobDifficulty[i] <= 1000
1 <= d <= 10 | 91% Faster Solution | 485 | minimum-difficulty-of-a-job-schedule | 0.587 | namanxk | Hard | 20,011 | 1,335 |
the k weakest rows in a matrix | class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
m = len(mat)
rows = sorted(range(m), key=lambda i: (mat[i], i))
del rows[k:]
return rows | https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1201679/C%2B%2B-Python3-No-Heap-No-BS-Simple-Sort-99.20 | 163 | You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.
A row i is weaker than a row j if one of the following is true:
The number of soldiers in row i is less than the number of soldiers in row j.
Both rows have the same number of soldiers and i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
Example 1:
Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
Example 2:
Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are [0,2,3,1].
Constraints:
m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j] is either 0 or 1. | [C++, Python3] No Heap, No BS, Simple Sort 99.20% | 6,300 | the-k-weakest-rows-in-a-matrix | 0.728 | mycoding1729 | Easy | 20,040 | 1,337 |
reduce array size to the half | class Solution:
def minSetSize(self, arr: List[int]) -> int:
freq = Counter(arr);
f = [];
for val in freq.values():
f.append(val);
f.sort(reverse=True)
ans = 0;
n = 0;
while(len(arr)//2>n):
n += f[ans];
ans += 1;
return ans; | https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2443490/Easy-to-understand-or-C%2B%2B-or-PYTHON-or | 3 | You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
Example 2:
Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.
Constraints:
2 <= arr.length <= 105
arr.length is even.
1 <= arr[i] <= 105 | Easy to understand | C++ | PYTHON | | 43 | reduce-array-size-to-the-half | 0.697 | dharmeshkporiya | Medium | 20,090 | 1,338 |
maximum product of splitted binary tree | class Solution:
def maxProduct(self, root: Optional[TreeNode]) -> int:
vals = []
def fn(node):
"""Return sum of sub-tree."""
if not node: return 0
ans = node.val + fn(node.left) + fn(node.right)
vals.append(ans)
return ans
total = fn(root)
return max((total-x)*x for x in vals) % 1_000_000_007 | https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/discuss/496700/Python3-post-order-dfs | 39 | Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.
Note that you need to maximize the answer before taking the mod and not after taking it.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
Example 2:
Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
Constraints:
The number of nodes in the tree is in the range [2, 5 * 104].
1 <= Node.val <= 104 | [Python3] post-order dfs | 1,500 | maximum-product-of-splitted-binary-tree | 0.434 | ye15 | Medium | 20,130 | 1,339 |
jump game v | class Solution:
def maxJumps(self, arr: List[int], d: int) -> int:
dp = defaultdict(int)
def dfs(i):
if i in dp: return dp[i]
m_path = 0
for j in range(i+1,i+d+1):
if j>=len(arr) or arr[j]>=arr[i]: break
m_path = max(m_path,dfs(j))
for j in range(i-1,i-d-1,-1):
if j<0 or arr[j]>=arr[i]: break
m_path = max(m_path,dfs(j))
dp[i] = m_path+1
return m_path+1
res = 0
for i in range(len(arr)):
res = max(res,dfs(i))
return res | https://leetcode.com/problems/jump-game-v/discuss/1670065/Well-Coded-and-Easy-Explanation-oror-Use-of-Memoization | 5 | Given an array of integers arr and an integer d. In one step you can jump from index i to index:
i + x where: i + x < arr.length and 0 < x <= d.
i - x where: i - x >= 0 and 0 < x <= d.
In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).
You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
Output: 4
Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
Example 2:
Input: arr = [3,3,3,3,3], d = 3
Output: 1
Explanation: You can start at any index. You always cannot jump to any index.
Example 3:
Input: arr = [7,6,5,4,3,2,1], d = 1
Output: 7
Explanation: Start at index 0. You can visit all the indicies.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 105
1 <= d <= arr.length | ๐๐ Well-Coded and Easy Explanation || Use of Memoization ๐ | 173 | jump-game-v | 0.625 | abhi9Rai | Hard | 20,147 | 1,340 |
number of steps to reduce a number to zero | class Solution:
"""
Time: O(log(n))
Memory: O(log(n))
"""
def numberOfSteps(self, num: int) -> int:
if num == 0:
return 0
return 1 + self.numberOfSteps(num - 1 if num & 1 else num >> 1) | https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/discuss/2738381/Python-Elegant-and-Short-or-O(1)-or-Recursive-Iterative-Bit-Manipulation | 28 | Given an integer num, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 106 | Python Elegant & Short | O(1) | Recursive / Iterative / Bit Manipulation | 1,300 | number-of-steps-to-reduce-a-number-to-zero | 0.854 | Kyrylo-Ktl | Easy | 20,151 | 1,342 |
number of sub arrays of size k and average greater than or equal to threshold | class Solution:
def numOfSubarrays(self, arr, k, threshold):
windowStart = 0
max_avg = 0
avg = 0
c=0
result = []
windowSum = 0
for windowEnd in range(len(arr)):
windowSum += arr[windowEnd]
if((windowEnd)>=k-1):
avg = windowSum//k
result.append(avg)
windowSum -= arr[windowStart]
windowStart += 1
for i in range(len(result)):
if(result[i]>=threshold):
c=c+1
return c | https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/discuss/1816745/Python-Solution-oror-Sliding-Window | 3 | Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
Example 2:
Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 104
1 <= k <= arr.length
0 <= threshold <= 104 | Python Solution || Sliding Window | 281 | number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold | 0.676 | aashutoshjha21022002 | Medium | 20,207 | 1,343 |
angle between hands of a clock | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
return min(abs(30*hour-5.5*minutes),360-abs(30*hour-5.5*minutes)) | https://leetcode.com/problems/angle-between-hands-of-a-clock/discuss/1911342/Python-one-line-solution-based-on-aptitude-formula | 2 | Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.
Answers within 10-5 of the actual value will be accepted as correct.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:
Input: hour = 3, minutes = 15
Output: 7.5
Constraints:
1 <= hour <= 12
0 <= minutes <= 59 | Python one line solution based on aptitude formula | 49 | angle-between-hands-of-a-clock | 0.634 | amannarayansingh10 | Medium | 20,227 | 1,344 |
jump game iv | class Solution:
def minJumps(self, arr: List[int]) -> int:
N, groups = len(arr), defaultdict(list)
for i, el in enumerate(arr):
groups[el].append(i)
vis, vis_groups = set(), set()
def bfs(lvl, dist):
nextLvl = set()
for i in lvl:
if i in vis: continue
if i == N-1: return dist
vis.add(i)
if i: nextLvl.add(i-1)
if i+1 < N: nextLvl.add(i+1)
if not arr[i] in vis_groups:
vis_groups.add(arr[i])
nextLvl.update(groups[arr[i]])
return bfs(nextLvl, dist + 1)
return bfs(set([0]), 0) | https://leetcode.com/problems/jump-game-iv/discuss/1691093/Python3-RECURSIVE-BFS-(_)-Explained | 9 | Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != j.
Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
Example 2:
Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You do not need to jump.
Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
Constraints:
1 <= arr.length <= 5 * 104
-108 <= arr[i] <= 108 | โ๏ธ [Python3] RECURSIVE BFS (าโก_โก) แค, Explained ๐ฅ | 321 | jump-game-iv | 0.44 | artod | Hard | 20,245 | 1,345 |
check if n and its double exist | class Solution:
def checkIfExist(self, A: List[int]) -> bool:
if A.count(0) > 1: return True
S = set(A) - {0}
for a in A:
if 2*a in S: return True
return False
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/check-if-n-and-its-double-exist/discuss/503507/Python-3-(five-lines)-(beats-100) | 20 | Given an array arr of integers, check if there exist two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]
Example 2:
Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the conditions.
Constraints:
2 <= arr.length <= 500
-103 <= arr[i] <= 103 | Python 3 (five lines) (beats 100%) | 4,100 | check-if-n-and-its-double-exist | 0.362 | junaidmansuri | Easy | 20,255 | 1,346 |
minimum number of steps to make two strings anagram | class Solution:
def minSteps(self, S: str, T: str) -> int:
D = collections.Counter(S) - collections.Counter(T)
return sum(max(0, D[s]) for s in set(S))
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/discuss/503535/Python-3-(two-lines)-(beats-100) | 9 | You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Example 1:
Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
Example 2:
Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
Example 3:
Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams.
Constraints:
1 <= s.length <= 5 * 104
s.length == t.length
s and t consist of lowercase English letters only. | Python 3 (two lines) (beats 100%) | 2,100 | minimum-number-of-steps-to-make-two-strings-anagram | 0.774 | junaidmansuri | Medium | 20,304 | 1,347 |
maximum students taking exam | class Solution:
def maxStudents(self, seats: list[list[str]]) -> int:
def count_bits(num: int) -> int:
# Count how many bits having value 1 in num.
cnt = 0
while num:
cnt += 1
num &= num - 1
return cnt
R, C = len(seats), len(seats[0])
validSeats = []
# Calculate valid seats mask for each row.
for row in seats:
curr = 0
for seat in row:
curr = (curr << 1) + (seat == '.')
validSeats.append(curr)
# dp[i][mask] stands for the maximum students on ith row with students
# following the mask.
dp = [[-1] * (1 << C) for _ in range(R + 1)]
dp[0][0] = 0
for r in range(1, R + 1):
seatMask = validSeats[r - 1]
for studentMask in range(1 << C):
validBits = count_bits(studentMask)
# 1. Check if a student mask is a subset of seatMask so that
# the target student could sit on a seat.
# 2. The student should not sit next to each other.
if (
studentMask & seatMask == studentMask and
studentMask & (studentMask >> 1) == 0
):
# Then check the upper student mask and make sure that
# 1. no student is on the upper left.
# 2. no student is on the upper right.
# Then the upper mask is a valid candidate for the current
# student mask.
for upperStudentMask in range(1 << C):
if (
studentMask & (upperStudentMask >> 1) == 0 and
studentMask & (upperStudentMask << 1) == 0 and
dp[r - 1][upperStudentMask] != -1
):
dp[r][studentMask] = max(
dp[r][studentMask],
dp[r - 1][upperStudentMask] + validBits
)
return max(dp[-1]) | https://leetcode.com/problems/maximum-students-taking-exam/discuss/1899957/Python-Bitmasking-dp-solution-with-explanation | 0 | Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.
Students must be placed in seats in good condition.
Example 1:
Input: seats = [["#",".","#","#",".","#"],
[".","#","#","#","#","."],
["#",".","#","#",".","#"]]
Output: 4
Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam.
Example 2:
Input: seats = [[".","#"],
["#","#"],
["#","."],
["#","#"],
[".","#"]]
Output: 3
Explanation: Place all students in available seats.
Example 3:
Input: seats = [["#",".",".",".","#"],
[".","#",".","#","."],
[".",".","#",".","."],
[".","#",".","#","."],
["#",".",".",".","#"]]
Output: 10
Explanation: Place students in available seats in column 1, 3 and 5.
Constraints:
seats contains only characters '.' and'#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8 | [Python] Bitmasking dp solution with explanation | 56 | maximum-students-taking-exam | 0.483 | eroneko | Hard | 20,334 | 1,349 |
count negative numbers in a sorted matrix | class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
result = 0
rows = len(grid)
cols = len(grid[0])
i = 0
j = cols - 1
while i < rows and j>=0:
curr = grid[i][j]
if(curr < 0):
j-=1
else:
result+=((cols-1) - j) #capture the no.of negative number in this row and jump to next row
i+=1
#left out negative rows
while i < rows:
result+=cols
i+=1
return result | https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/discuss/2193369/Python3-slight-tweak-in-binary-search | 6 | Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.
Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.
Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
Follow up: Could you find an O(n + m) solution? | ๐ Python3 slight tweak in binary search | 73 | count-negative-numbers-in-a-sorted-matrix | 0.752 | Dark_wolf_jss | Easy | 20,336 | 1,351 |
maximum number of events that can be attended | # Solution 1
def maxEvents(self, events: List[List[int]]) -> int:
events = sorted(events, key=lambda x: x[1])
visited = set()
for s, e in events:
for t in range(s, e+1):
if t not in visited:
visited.add(t)
break
return len(visited) | https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/discuss/726456/Python3-solution-with-detailed-explanation | 12 | You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.
Return the maximum number of events you can attend.
Example 1:
Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
Example 2:
Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4
Constraints:
1 <= events.length <= 105
events[i].length == 2
1 <= startDayi <= endDayi <= 105 | Python3 solution with detailed explanation | 2,400 | maximum-number-of-events-that-can-be-attended | 0.329 | peyman_np | Medium | 20,386 | 1,353 |
construct target array with multiple sums | class Solution:
def isPossible(self, target: List[int]) -> bool:
heapq._heapify_max(target)
s = sum(target)
while target[0] != 1:
sub = s - target[0]
if sub == 0: return False
n = max((target[0] - 1) // sub, 1)
s -= n * sub
target0 = target[0] - n * sub
if target0 < 1: return False
heapq._heapreplace_max(target, target0)
return True
``` | https://leetcode.com/problems/construct-target-array-with-multiple-sums/discuss/2189540/Python-Easy-Solution-oror-Less-Line-Of-Code-oror-Heapify | 14 | You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :
let x be the sum of all elements currently in your array.
choose index i, such that 0 <= i < n and set the value of arr at index i to x.
You may repeat this procedure as many times as needed.
Return true if it is possible to construct the target array from arr, otherwise, return false.
Example 1:
Input: target = [9,3,5]
Output: true
Explanation: Start with arr = [1, 1, 1]
[1, 1, 1], sum = 3 choose index 1
[1, 3, 1], sum = 5 choose index 2
[1, 3, 5], sum = 9 choose index 0
[9, 3, 5] Done
Example 2:
Input: target = [1,1,1,2]
Output: false
Explanation: Impossible to create target array from [1,1,1,1].
Example 3:
Input: target = [8,5]
Output: true
Constraints:
n == target.length
1 <= n <= 5 * 104
1 <= target[i] <= 109 | Python Easy Solution || Less Line Of Code || Heapify | 1,400 | construct-target-array-with-multiple-sums | 0.363 | vaibhav0077 | Hard | 20,393 | 1,354 |
sort integers by the number of 1 bits | class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return sorted(arr, key = lambda item: (str(bin(item))[2:].count("1"), item)) | https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2697450/Python-or-1-liner-lambda-key | 4 | You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.
Example 1:
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]
Example 2:
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
Constraints:
1 <= arr.length <= 500
0 <= arr[i] <= 104 | Python | 1-liner lambda key | 791 | sort-integers-by-the-number-of-1-bits | 0.72 | LordVader1 | Easy | 20,399 | 1,356 |
number of substrings containing all three characters | class Solution:
def numberOfSubstrings(self, s: str) -> int:
a = b = c = 0 # counter for letter a/b/c
ans, i, n = 0, 0, len(s) # i: slow pointer
for j, letter in enumerate(s): # j: fast pointer
if letter == 'a': a += 1 # increment a/b/c accordingly
elif letter == 'b': b += 1
else: c += 1
while a > 0 and b > 0 and c > 0: # if all of a/b/c are contained, move slow pointer
ans += n-j # count possible substr, if a substr ends at j, then there are n-j substrs to the right that are containing all a/b/c
if s[i] == 'a': a -= 1 # decrement counter accordingly
elif s[i] == 'b': b -= 1
else: c -= 1
i += 1 # move slow pointer
return ans | https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/851021/Python-3-or-Two-Pointers-or-Explanation | 23 | Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb"
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc"
Output: 1
Constraints:
3 <= s.length <= 5 x 10^4
s only consists of a, b or c characters. | Python 3 | Two Pointers | Explanation | 1,200 | number-of-substrings-containing-all-three-characters | 0.631 | idontknoooo | Medium | 20,440 | 1,358 |
count all valid pickup and delivery options | class Solution:
def countOrders(self, n: int) -> int:
n=2*n
ans=1
while n>=2:
ans = ans *((n*(n-1))//2)
n-=2
ans=ans%1000000007
return ans | https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1825566/Python-oror-Easy-To-Understand-oror-98-Faster-oror-Maths | 3 | Given n orders, each order consists of a pickup and a delivery service.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
Example 2:
Input: n = 2
Output: 6
Explanation: All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
Example 3:
Input: n = 3
Output: 90
Constraints:
1 <= n <= 500 | โ
Python || Easy To Understand || 98% Faster || Maths | 53 | count-all-valid-pickup-and-delivery-options | 0.629 | rahulmittall | Hard | 20,453 | 1,359 |
Subsets and Splits