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... | ๐๐ 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
... | 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 with... | [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,gr... | 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 wa... | 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[... | 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 ano... | 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 s... | 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]]:
... | 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] represen... | 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 ... | 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 wi... | 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
... | 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 ele... | 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 pers... | [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... | 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 mo... | 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... | 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 leng... | [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:
... | 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... | ๐ 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... | 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... | [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 eleme... | ๐ 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 tile... | 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 =... | [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:
... | 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... | 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_... | 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 =... | 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... | 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, contain... | 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.
... | 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
... | 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 cell... | 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:
... | 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-in... | 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=df... | 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,... | ๐ 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
... | 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. ... | 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])
... | 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.
Ex... | โญ 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 =... | 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... | 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
... | 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 chara... | 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)
ret... | 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 sqr... | 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
... | 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 ser... | ๐๐ 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... | 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 thr... | [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
... | 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 poi... | [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... | 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, ... | 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]... | 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... | [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
... | 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... | 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
... | 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 div... | 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 digit... | 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(id... | 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.
Retur... | 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:
... | 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... | 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:
... | 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 can... | 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]... | 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:
... | 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 =... | โ๏ธ [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 -> mi... | 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]]
O... | 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... | [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
... | 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
Ou... | 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... | 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 sq... | 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 o... | 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 ... | โ๏ธ 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 (od... | 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.... | 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... | 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.appen... | 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... | 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 vis... | 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 ... | 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 in... | 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[... | 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... | [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(rang... | 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 m... | [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... | 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 <= ... | 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 <= ... | 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 ... | 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... | [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):
"""Fin... | 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 lead... | [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 gener... | 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 q... | 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... | 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 vi... | [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 ... | 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 d... | 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 rig... | 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):
... | 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]... | 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
... | 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
Explana... | 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
... | 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: t... | [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
... | 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 r... | 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... | 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:... | 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 compone... | 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 c... | 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 == ... | 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 coor... | ๐๐ 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): #ch... | 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.
Chang... | 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:
... | 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:
In... | 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 = ... | 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+... | 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... | 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: retu... | 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 ... | 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()
... | 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[... | 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... | 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:... | 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... | 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 cha... | โ
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] <= maxDis... | 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 ... | 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
fo... | 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 di... | [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
... | 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 maximu... | 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... | [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;
ret... | 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} wil... | 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
... | 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... | [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]: b... | 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... | ๐๐ 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 o... | 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 = win... | 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... | 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 ... | 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 i... | 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 th... | โ๏ธ [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: Th... | 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... | 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(s... | 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 s... | [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:
... | 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],... | ๐ 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 l... | 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: e... | 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._... | 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 ne... | 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,... | 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 ... | 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", "ab... | 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... | โ
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
No community queries yet
The top public SQL queries from the community will appear here once available.