problem_title stringlengths 3 77 | python_solutions stringlengths 81 8.45k | post_href stringlengths 64 213 | upvotes int64 0 1.2k | question stringlengths 0 3.6k | post_title stringlengths 2 100 | views int64 1 60.9k | slug stringlengths 3 77 | acceptance float64 0.14 0.91 | user stringlengths 3 26 | difficulty stringclasses 3
values | __index_level_0__ int64 0 34k | number int64 1 2.48k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
average salary excluding the minimum and maximum salary | class Solution:
def average(self, salary: List[int]) -> float:
minimum = float("inf")
maximum = float("-inf")
i = 0
sums = 0
while i<len(salary):
minimum = min(minimum, salary[i])
maximum = max(maximum, salary[i])
sums+=salary[i]
... | https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2213970/Python3-one-pass-solution-beats-99.20-of-submissions | 6 | You are given an array of unique integers salary where salary[i] is the salary of the ith employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanatio... | 📌 Python3 one pass solution beats 99.20% of submissions | 207 | average-salary-excluding-the-minimum-and-maximum-salary | 0.627 | Dark_wolf_jss | Easy | 22,161 | 1,491 |
the kth factor of n | class Solution:
def kthFactor(self, n: int, k: int) -> int:
factors = []
for i in range(1,n+1):
if n % i == 0:
factors.append(i)
if k > len(factors):
return -1
else:
return factors[k-1] | https://leetcode.com/problems/the-kth-factor-of-n/discuss/1352274/Python3-simple-solution-using-list | 1 | You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors... | Python3 simple solution using list | 139 | the-kth-factor-of-n | 0.624 | EklavyaJoshi | Medium | 22,210 | 1,492 |
longest subarray of 1s after deleting one element | class Solution:
def longestSubarray(self, nums: List[int]) -> int:
m=0
l=len(nums)
one=True
for i in range(0,l):
if nums[i]==0:
one=False
left=i-1
right=i+1
ones=0
while left>=0:
... | https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708121/Easy-Solution-without-DP-Simple-Pictorial-Explanation-or-Python-Solution. | 12 | Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 n... | [Easy Solution without DP] Simple Pictorial Explanation | Python Solution. | 1,100 | longest-subarray-of-1s-after-deleting-one-element | 0.602 | lazerx | Medium | 22,239 | 1,493 |
parallel courses ii | class Solution:
def minNumberOfSemesters(self, n: int, dependencies: List[List[int]], k: int) -> int:
pre = [0]*n # prerequisites
for u, v in dependencies:
pre[v-1] |= 1 << (u-1)
@cache
def fn(mask):
"""Return min semesters to take remaining c... | https://leetcode.com/problems/parallel-courses-ii/discuss/1111255/Python3-dp | 2 | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course ne... | [Python3] dp | 171 | parallel-courses-ii | 0.311 | ye15 | Hard | 22,268 | 1,494 |
path crossing | class Solution:
def isPathCrossing(self, path: str) -> bool:
l = [(0,0)]
x,y = 0,0
for i in path:
if i == 'N':
y += 1
if i == 'S':
y -= 1
if i == 'E':
x += 1
if i == 'W':
x -= 1
... | https://leetcode.com/problems/path-crossing/discuss/1132447/Python3-simple-solution-faster-than-99-users | 4 | Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is, if at any time you are on a location ... | Python3 simple solution faster than 99% users | 252 | path-crossing | 0.558 | EklavyaJoshi | Easy | 22,272 | 1,496 |
check if array pairs are divisible by k | class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
freq = dict()
for x in arr: freq[x%k] = 1 + freq.get(x%k, 0)
return all(freq[x] == freq.get(xx:=(k-x)%k, 0) and (x != xx or freq[x]%2 == 0) for x in freq) | https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/709252/Python3-3-line-frequency-table | 3 | Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pair... | [Python3] 3-line frequency table | 255 | check-if-array-pairs-are-divisible-by-k | 0.396 | ye15 | Medium | 22,296 | 1,497 |
number of subsequences that satisfy the given sum condition | class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
n = len(nums)
nums.sort()
i, j = 0, n-1
res = 0
NUM = 10**9+7
while i <= j:
if nums[i] + nums[j] > target:
j -= 1
elif nums[i]... | https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/discuss/1703899/python-easy-two-pointers-%2B-sorting-solution | 3 | You are given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: ... | python easy two-pointers + sorting solution | 755 | number-of-subsequences-that-satisfy-the-given-sum-condition | 0.381 | byuns9334 | Medium | 22,302 | 1,498 |
max value of equation | class Solution:
def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:
ans = -inf
hp = []
for xj, yj in points:
while hp and xj - hp[0][1] > k: heappop(hp)
if hp:
ans = max(ans, xj + yj - hp[0][0])
heappush(hp, (xj-yj, ... | https://leetcode.com/problems/max-value-of-equation/discuss/709364/Python3-heap | 8 | You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.
Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <=... | [Python3] heap | 721 | max-value-of-equation | 0.464 | ye15 | Hard | 22,309 | 1,499 |
can make arithmetic progression from sequence | class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
return len(set(arr[i-1] - arr[i] for i in range(1, len(arr)))) == 1 | https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720103/Python3-2-line-(sorting) | 17 | A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: ... | [Python3] 2-line (sorting) | 1,100 | can-make-arithmetic-progression-from-sequence | 0.681 | ye15 | Easy | 22,311 | 1,502 |
last moment before all ants fall out of a plank | class Solution:
def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
if left and not right:
return max(left)
if not left and right:
return n - min(right)
if not left and not right:
return 0
if left and right:
retur... | https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/discuss/720202/PythonPython3-Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank | 1 | We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.
When two ants moving in two different directions meet at some point, they change their directions and continue moving again.... | [Python/Python3] Last Moment Before All Ants Fall Out of a Plank | 87 | last-moment-before-all-ants-fall-out-of-a-plank | 0.553 | newborncoder | Medium | 22,355 | 1,503 |
count submatrices with all ones | class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
#precipitate mat to histogram
for i in range(m):
for j in range(n):
if mat[i][j] and i > 0:
mat[i][j] += mat[i-1][j] #histogram
... | https://leetcode.com/problems/count-submatrices-with-all-ones/discuss/721999/Python3-O(MN)-histogram-model | 111 | Given an m x n binary matrix mat, return the number of submatrices that have all ones.
Example 1:
Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 re... | [Python3] O(MN) histogram model | 7,600 | count-submatrices-with-all-ones | 0.578 | ye15 | Medium | 22,360 | 1,504 |
minimum possible integer after at most k adjacent swaps on digits | class Solution:
def minInteger(self, num: str, k: int) -> str:
n = len(num)
if k >= n*(n-1)//2: return "".join(sorted(num)) #special case
#find smallest elements within k swaps
#and swap it to current position
num = list(num)
for i in range(n):
... | https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/discuss/720123/Python3-brute-force | 2 | You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain... | [Python3] brute force | 374 | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0.383 | ye15 | Hard | 22,364 | 1,505 |
reformat date | class Solution:
def reformatDate(self, date: str) -> str:
s = date.split() # Divides the elements into 3 individual parts
monthDict = {'Jan': '01', 'Feb': '02',
'Mar': '03', 'Apr': '04',
'May': '05', 'Jun': '06',
'Jul': '07',... | https://leetcode.com/problems/reformat-date/discuss/1861804/Python-3-Easy-Dict.-Solution-wout-imports-(98) | 12 | Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to the format YYYY-MM-DD, where... | Python 3 - Easy Dict. Solution w/out imports (98%) | 768 | reformat-date | 0.626 | IvanTsukei | Easy | 22,365 | 1,507 |
range sum of sorted subarray sums | class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
ans = []
for i in range(len(nums)):
prefix = 0
for ii in range(i, len(nums)):
prefix += nums[ii]
ans.append(prefix)
ans.sort()
return sum... | https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/730973/Python3-priority-queue | 46 | You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusiv... | [Python3] priority queue | 3,600 | range-sum-of-sorted-subarray-sums | 0.593 | ye15 | Medium | 22,398 | 1,508 |
minimum difference between largest and smallest value in three moves | class Solution:
def minDifference(self, nums: List[int]) -> int:
n = len(nums)
# If nums are less than 3 all can be replace,
# so min diff will be 0, which is default condition
if n > 3:
# Init min difference
min_diff = float("inf")
... | https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1433873/Python3Python-Easy-readable-solution-with-comments. | 10 | You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In ... | [Python3/Python] Easy readable solution with comments. | 1,000 | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0.546 | ssshukla26 | Medium | 22,403 | 1,509 |
stone game iv | class Solution:
def winnerSquareGame(self, n: int) -> bool:
dp = [False] * (n + 1)
squares = []
curSquare = 1
for i in range(1, n + 1):
if i == curSquare * curSquare:
squares.append(i)
curSquare += 1
dp[i] = True
... | https://leetcode.com/problems/stone-game-iv/discuss/1708107/Python3-DP | 8 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, r... | [Python3] DP | 397 | stone-game-iv | 0.605 | PatrickOweijane | Hard | 22,413 | 1,510 |
number of good pairs | class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
hashMap = {}
res = 0
for number in nums:
if number in hashMap:
res += hashMap[number]
hashMap[number] += 1
else:
hashMap[number] = 1
... | https://leetcode.com/problems/number-of-good-pairs/discuss/749025/Python-O(n)-simple-dictionary-solution | 88 | Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair... | Python O(n) simple dictionary solution | 6,200 | number-of-good-pairs | 0.882 | Arturo001 | Easy | 22,427 | 1,512 |
number of substrings with only 1s | class Solution:
def numSub(self, s: str) -> int:
res = 0
s = s.split("0")
for one in s:
if one == "":
continue
n = len(one)
temp = (n / 2)*(2*n + (n-1)*-1)
... | https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731754/Python-Sum-of-Arithmetic-Progression-with-explanation-**100.00-Faster** | 8 | Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
In... | [Python] Sum of Arithmetic Progression with explanation **100.00% Faster** | 506 | number-of-substrings-with-only-1s | 0.454 | Jasper-W | Medium | 22,479 | 1,513 |
path with maximum probability | class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
graph, prob = dict(), dict() #graph with prob
for i, (u, v) in enumerate(edges):
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)... | https://leetcode.com/problems/path-with-maximum-probability/discuss/731655/Python3-Dijkstra's-algo | 27 | You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of succes... | [Python3] Dijkstra's algo | 2,500 | path-with-maximum-probability | 0.484 | ye15 | Medium | 22,497 | 1,514 |
best position for a service centre | class Solution:
def getMinDistSum(self, positions: List[List[int]]) -> float:
#euclidean distance
fn = lambda x, y: sum(sqrt((x-xx)**2 + (y-yy)**2) for xx, yy in positions)
#centroid as starting point
x = sum(x for x, _ in positions)/len(positions)
y = sum(y for _, y in posi... | https://leetcode.com/problems/best-position-for-a-service-centre/discuss/731717/Python3-geometric-median | 62 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.
Given an array positions where positions[i] = [xi,... | [Python3] geometric median | 3,700 | best-position-for-a-service-centre | 0.377 | ye15 | Hard | 22,502 | 1,515 |
water bottles | class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = r = 0
while numBottles:
ans += numBottles
numBottles, r = divmod(numBottles + r, numExchange)
return ans | https://leetcode.com/problems/water-bottles/discuss/743152/Python3-5-line-iterative | 9 | There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles and numExchange, return the maximum number of w... | [Python3] 5-line iterative | 573 | water-bottles | 0.602 | ye15 | Easy | 22,503 | 1,518 |
number of nodes in the sub tree with the same label | class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
ans = [0] * n
tree = collections.defaultdict(list)
for a, b in edges: # build tree
tree[a].append(b)
tree[b].append(a)
def dfs(node):... | https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/discuss/1441578/Python-3-or-DFS-Graph-Counter-or-Explanation | 7 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has t... | Python 3 | DFS, Graph, Counter | Explanation | 366 | number-of-nodes-in-the-sub-tree-with-the-same-label | 0.41 | idontknoooo | Medium | 22,528 | 1,519 |
maximum number of non overlapping substrings | class Solution:
def maxNumOfSubstrings(self, s: str) -> List[str]:
locs = {}
for i, x in enumerate(s):
locs.setdefault(x, []).append(i)
def fn(lo, hi):
"""Return expanded range covering all chars in s[lo:hi+1]."""
for xx in locs:
... | https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/1208758/Python3-greedy | 1 | Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:
The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.
A substring that contains a certain character c must also contain ... | [Python3] greedy | 281 | maximum-number-of-non-overlapping-substrings | 0.381 | ye15 | Hard | 22,532 | 1,520 |
find a value of a mysterious function closest to target | class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
ans, seen = inf, set()
for x in arr:
seen = {ss & x for ss in seen} | {x}
ans = min(ans, min(abs(ss - target) for ss in seen))
return ans | https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target/discuss/746723/Python3-bitwise-and | 8 | Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the val... | [Python3] bitwise and | 306 | find-a-value-of-a-mysterious-function-closest-to-target | 0.436 | ye15 | Hard | 22,534 | 1,521 |
count odd numbers in an interval range | class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 0:
return (high-low+1)//2
return (high-low)//2 + 1 | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/discuss/1813332/Python-3-or-Math-or-Intuitive | 60 | Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
... | Python 3 | Math | Intuitive | 4,500 | count-odd-numbers-in-an-interval-range | 0.462 | ndus | Easy | 22,537 | 1,523 |
number of sub arrays with odd sum | class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
cumSum = odd = even = 0
for num in arr:
cumSum += num
if cumSum % 2:
odd += 1
else:
even += 1
return odd * (even + 1) % (pow(10, 9) + 7) | https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/discuss/2061760/Python-oror-8-line-math-using-Prefix-Sum | 1 | Given an array of integers arr, return the number of subarrays with an odd sum.
Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the a... | Python || 8-line math using Prefix Sum | 138 | number-of-sub-arrays-with-odd-sum | 0.436 | gulugulugulugulu | Medium | 22,594 | 1,524 |
number of good ways to split a string | class Solution:
def numSplits(self, s: str) -> int:
# this is not neccessary, but speeds things up
length = len(s)
if length == 1: # never splittable
return 0
elif length == 2: # always splittable
return 1
# we are recording the first and last occurence of ea... | https://leetcode.com/problems/number-of-good-ways-to-split-a-string/discuss/1520004/99.7-Python-3-solution-with-17-lines-no-search-explained | 70 | You are given a string s.
A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.
Return the number of good splits you can make in s.
Example 1:
Input: s... | 99.7% Python 3 solution with 17 lines, no search, explained | 2,200 | number-of-good-ways-to-split-a-string | 0.694 | epistoteles | Medium | 22,600 | 1,525 |
minimum number of increments on subarrays to form a target array | class Solution:
def minNumberOperations(self, target: List[int]) -> int:
res = target[0]
for i in range(1, len(target)):
if target[i] >= target[i - 1]:
res -= target[i - 1]
res += target[i]
return res | https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/discuss/1589995/Python3-O(n)-time-O(1)-space-solution | 1 | You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases ar... | [Python3] O(n) time, O(1) space solution | 87 | minimum-number-of-increments-on-subarrays-to-form-a-target-array | 0.686 | maosipov11 | Hard | 22,624 | 1,526 |
shuffle string | class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
res = [''] * len(s)
for i in range(len(s)):
res[indices[i]] = s[i]
return ''.join(i for i in res) | https://leetcode.com/problems/shuffle-string/discuss/768482/Simple-Python-Solution-Faster-than-99.56 | 25 | You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As s... | Simple Python Solution - Faster than 99.56% | 4,200 | shuffle-string | 0.857 | parkershamblin | Easy | 22,628 | 1,528 |
minimum suffix flips | class Solution:
def minFlips(self, target: str) -> int:
return len(list(groupby("0" + target)))-1 | https://leetcode.com/problems/minimum-suffix-flips/discuss/755814/Python3-1-line | 16 | You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.
In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' ... | [Python3] 1-line | 872 | minimum-suffix-flips | 0.724 | ye15 | Medium | 22,687 | 1,529 |
number of good leaf nodes pairs | class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
def dfs(node):
"""Return (a list of) distances to leaves of sub-tree rooted at node."""
nonlocal ans
if not node: return []
if node.left is node.right is None: return [0]
... | https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/discuss/755979/Python3-recursive-postorder-dfs | 3 | You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], dis... | [Python3] recursive postorder dfs | 264 | number-of-good-leaf-nodes-pairs | 0.607 | ye15 | Medium | 22,705 | 1,530 |
string compression ii | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
rle = lambda x: x if x <= 1 else int(log10(x)) + 2 # rle length of a char repeated x times
@cache
def fn(i, k, prev, cnt):
"""Return length of rle of s[i:] with k chars to be deleted."""
... | https://leetcode.com/problems/string-compression-ii/discuss/1203398/Python3-top-down-dp | 12 | Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and ... | [Python3] top-down dp | 1,300 | string-compression-ii | 0.499 | ye15 | Hard | 22,711 | 1,531 |
count good triplets | class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
return sum(abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c for i in range(len(arr)) for j in range(i+1, len(arr)) for k in range(j+1, len(arr))) | https://leetcode.com/problems/count-good-triplets/discuss/767942/Python3-1-line | 4 | Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute va... | [Python3] 1-line | 1,800 | count-good-triplets | 0.808 | ye15 | Easy | 22,716 | 1,534 |
find the winner of an array game | class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
win = cnt = 0 #winner & count
for i, x in enumerate(arr):
if win < x: win, cnt = x, 0 #new winner in town
if i: cnt += 1 #when initializing (i.e. i == 0) count is 0
if cnt == k: break #earl... | https://leetcode.com/problems/find-the-winner-of-an-array-game/discuss/767983/Python3-6-line-O(N) | 7 | Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array... | [Python3] 6-line O(N) | 267 | find-the-winner-of-an-array-game | 0.488 | ye15 | Medium | 22,741 | 1,535 |
minimum swaps to arrange a binary grid | class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
#summarizing row into number
row = [0]*m
for i in range(m):
row[i] = next((j for j in reversed(range(n)) if grid[i][j]), 0)
ans = 0
#sequentially lo... | https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768030/Python3-bubble-ish-sort | 13 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diago... | [Python3] bubble-ish sort | 750 | minimum-swaps-to-arrange-a-binary-grid | 0.465 | ye15 | Medium | 22,744 | 1,536 |
get the maximum score | class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
ans = i = ii = s = ss = 0
while i < len(nums1) and ii < len(nums2):
#update range sum & move pointer
if nums1[i] < nums2[ii]:
s += nums1[i]
i += 1
... | https://leetcode.com/problems/get-the-maximum-score/discuss/768050/Python3-range-sum-with-two-pointers-O(M%2BN) | 1 | You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:
Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the othe... | [Python3] range sum with two pointers O(M+N) | 73 | get-the-maximum-score | 0.393 | ye15 | Hard | 22,746 | 1,537 |
kth missing positive number | class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
ss, x = set(arr), 1
while True:
if x not in ss: k -= 1
if not k: return x
x += 1 | https://leetcode.com/problems/kth-missing-positive-number/discuss/784720/Python3-O(N)-and-O(logN)-solutions | 5 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Return the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive inte... | [Python3] O(N) and O(logN) solutions | 240 | kth-missing-positive-number | 0.56 | ye15 | Easy | 22,749 | 1,539 |
can convert string in k moves | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
cycles, extra = divmod(k, 26)
shifts = [cycles + (shift <= extra) for shift in range(26)]
for cs, ct in zip(s, t):
shift = (ord(ct) - ord(cs... | https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/2155709/python-3-or-simple-O(n)O(1)-solution | 0 | Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:
Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.
Shifting a character m... | python 3 | simple O(n)/O(1) solution | 67 | can-convert-string-in-k-moves | 0.332 | dereky4 | Medium | 22,800 | 1,540 |
minimum insertions to balance a parentheses string | class Solution:
def minInsertions(self, s: str) -> int:
"""
(
"""
res = need = 0
for i in range(len(s)):
if s[i] == '(':
need += 2
if need % 2 == 1:
res += 1
need -= 1
if s[i] == ... | https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2825876/Python | 0 | Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:
Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
In other words, we treat ... | Python | 2 | minimum-insertions-to-balance-a-parentheses-string | 0.499 | lillllllllly | Medium | 22,804 | 1,541 |
find longest awesome substring | class Solution:
def longestAwesome(self, s: str) -> int:
# li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
li = [2**i for i in range(10)]
# checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}
checker = set(li)
checker.add(0)
# di: k = prefix xor, v = the first idx I got... | https://leetcode.com/problems/find-longest-awesome-substring/discuss/2259262/Python3-or-Prefix-xor-or-O(n)-Solution | 1 | You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we c... | Python3 | Prefix xor | O(n) Solution | 75 | find-longest-awesome-substring | 0.414 | shugokra | Hard | 22,816 | 1,542 |
make the string great | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and abs(ord(stack[-1]) - ord(c)) == 32: stack.pop() #pop "bad"
else: stack.append(c) #push "good"
return "".join(stack) | https://leetcode.com/problems/make-the-string-great/discuss/781044/Python3-5-line-stack-O(N) | 34 | Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent... | [Python3] 5-line stack O(N) | 1,400 | make-the-string-great | 0.633 | ye15 | Easy | 22,818 | 1,544 |
find kth bit in nth binary string | class Solution:
def findKthBit(self, n: int, k: int) -> str:
if k == 1: return "0"
if k == 2**(n-1): return "1"
if k < 2**(n-1): return self.findKthBit(n-1, k)
return "0" if self.findKthBit(n-1, 2**n-k) == "1" else "1" | https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781062/Python3-4-line-recursive | 11 | Given two positive integers n and k, the binary string Sn is formed as follows:
S1 = "0"
Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
For example, ... | [Python3] 4-line recursive | 432 | find-kth-bit-in-nth-binary-string | 0.583 | ye15 | Medium | 22,872 | 1,545 |
maximum number of non overlapping subarrays with sum equals target | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
ans = prefix = 0
seen = set([0]) #prefix sum seen so far ()
for i, x in enumerate(nums):
prefix += x
if prefix - target in seen:
ans += 1
seen.clear() #r... | https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/781075/Python3-O(N)-prefix-sum | 2 | Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to targ... | [Python3] O(N) prefix sum | 54 | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | 0.472 | ye15 | Medium | 22,892 | 1,546 |
minimum cost to cut a stick | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
@lru_cache(None)
def fn(lo, hi):
"""Return cost of cutting [lo, hi]."""
cc = [c for c in cuts if lo < c < hi] #collect cuts within this region
if not cc: return 0
ans = inf
... | https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp | 6 | Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:
Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
The cost o... | [Python3] top-down & bottom-up dp | 488 | minimum-cost-to-cut-a-stick | 0.57 | ye15 | Hard | 22,897 | 1,547 |
three consecutive odds | class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
count = 0
for i in range(0, len(arr)):
if arr[i] %2 != 0:
count += 1
if count == 3:
return True
else:
count = 0
return ... | https://leetcode.com/problems/three-consecutive-odds/discuss/794097/Python3-straight-forward-solution | 20 | Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
Example 1:
Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consec... | Python3 straight forward solution | 1,600 | three-consecutive-odds | 0.636 | sjha2048 | Easy | 22,903 | 1,550 |
minimum operations to make array equal | class Solution:
def minOperations(self, n: int) -> int:
if(n%2!=0):
n=n//2
return n*(n+1)
else:
n=n//2
return n**2 | https://leetcode.com/problems/minimum-operations-to-make-array-equal/discuss/1704407/Understandable-code-for-beginners-like-me-in-python-!! | 2 | You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array... | Understandable code for beginners like me in python !! | 92 | minimum-operations-to-make-array-equal | 0.811 | kabiland | Medium | 22,937 | 1,551 |
magnetic force between two balls | class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
def fn(d):
"""Return True if d is a feasible distance."""
ans, prev = 0, -inf # where previous ball is put
for x in position:
if x - prev >= d:
... | https://leetcode.com/problems/magnetic-force-between-two-balls/discuss/794249/Python3-binary-search-distance-space | 4 | In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any tw... | [Python3] binary search distance space | 473 | magnetic-force-between-two-balls | 0.57 | ye15 | Medium | 22,962 | 1,552 |
minimum number of days to eat n oranges | class Solution:
def minDays(self, n: int) -> int:
ans = 0
queue = [n]
seen = set()
while queue: #bfs
newq = []
for x in queue:
if x == 0: return ans
seen.add(x)
if x-1 not in seen: newq.append(x-1)
... | https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/discuss/794275/Python3-bfs | 26 | There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose on... | [Python3] bfs | 1,500 | minimum-number-of-days-to-eat-n-oranges | 0.346 | ye15 | Hard | 22,969 | 1,553 |
thousand separator | class Solution:
def thousandSeparator(self, n: int) -> str:
return f"{n:,}".replace(",", ".") | https://leetcode.com/problems/thousand-separator/discuss/805712/Python3-1-line | 25 | Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Constraints:
0 <= n <= 231 - 1 | [Python3] 1-line | 980 | thousand-separator | 0.549 | ye15 | Easy | 22,975 | 1,556 |
minimum number of vertices to reach all nodes | class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
if not edges:
return []
incoming_degrees = {i: 0 for i in range(n)}
for x, y in edges:
incoming_degrees[y] += 1
result = [k for k, ... | https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1212672/Python-Easy-Solution-Count-of-Nodes-with-Zero-Incoming-Degree | 4 | Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that y... | Python Easy Solution - Count of Nodes with Zero Incoming-Degree | 195 | minimum-number-of-vertices-to-reach-all-nodes | 0.796 | ChidinmaKO | Medium | 23,002 | 1,557 |
minimum numbers of function calls to make target array | class Solution:
def minOperations(self, nums: List[int]) -> int:
return sum(bin(a).count('1') for a in nums) + len(bin(max(nums))) - 2 - 1 | https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/807358/Python-Bit-logic-Explained | 3 | You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:
You want to use the modify function to convert arr to nums using the minimum number of calls.
Return the minimum number of function calls to make nums fr... | Python Bit logic Explained | 125 | minimum-numbers-of-function-calls-to-make-target-array | 0.642 | akhil_ak | Medium | 23,031 | 1,558 |
detect cycles in 2d grid | class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def fn(i, j, d):
"""Traverse the grid to find cycle via backtracking."""
if grid[i][j] != "BLACK":
val = grid[i][j]
... | https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/806630/Python3-memoized-dfs-with-a-direction-parameter-(16-line) | 1 | Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions ... | [Python3] memoized dfs with a direction parameter (16-line) | 75 | detect-cycles-in-2d-grid | 0.48 | ye15 | Medium | 23,037 | 1,559 |
most visited sector in a circular track | class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
x, xx = rounds[0], rounds[-1]
return list(range(x, xx+1)) if x <= xx else list(range(1, xx+1)) + list(range(x, n+1)) | https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/806738/Python3-2-line | 10 | Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] a... | [Python3] 2-line | 1,200 | most-visited-sector-in-a-circular-track | 0.584 | ye15 | Easy | 23,046 | 1,560 |
maximum number of coins you can get | class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles.sort(reverse=True)
sum = 0
for i in range(1,len(piles)-int(len(piles)/3),2):
sum += piles[i]
print(sum)
return sum | https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1232262/Python-Simple-Solution | 2 | There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with the maximum number of coins... | Python Simple Solution | 146 | maximum-number-of-coins-you-can-get | 0.786 | yashwant_mahawar | Medium | 23,052 | 1,561 |
find latest group of size m | class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
span = [0]*(len(arr)+2)
freq = [0]*(len(arr)+1)
ans = -1
for i, x in enumerate(arr, 1):
freq[span[x-1]] -= 1
freq[span[x+1]] -= 1
span[x] = span[x-span[x-1]] = span[x+span[x+... | https://leetcode.com/problems/find-latest-group-of-size-m/discuss/809823/Python3-summarizing-two-approaches | 0 | Given an array arr that represents a permutation of numbers from 1 to n.
You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.
You are also given an integer m. Find the l... | [Python3] summarizing two approaches | 57 | find-latest-group-of-size-m | 0.425 | ye15 | Medium | 23,086 | 1,562 |
stone game v | class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
length = len(stoneValue)
if length == 1:
return 0
# Calculate sum
s = [0 for _ in range(length)]
s[0] = stoneValue[0]
for i in range(1, length):
s[i] = s[i-1] + stoneValue[i... | https://leetcode.com/problems/stone-game-v/discuss/1504994/Python-O(n2)-optimized-solution.-O(n3)-cannot-pass. | 4 | There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all th... | Python O(n^2) optimized solution. O(n^3) cannot pass. | 202 | stone-game-v | 0.406 | pureme | Hard | 23,087 | 1,563 |
detect pattern of length m repeated k or more times | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
for i in range(len(arr)-m+1):
count = 1
x = arr[i:i+m]
res = 1
for j in range(i+m,len(arr)-m+1,m):
if x == arr[j:j+m]:
count += 1
... | https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1254278/Python3-simple-solution | 2 | Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Retur... | Python3 simple solution | 124 | detect-pattern-of-length-m-repeated-k-or-more-times | 0.436 | EklavyaJoshi | Easy | 23,092 | 1,566 |
maximum length of subarray with positive product | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = pos = neg = 0
for x in nums:
if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0
elif x < 0: pos, neg = 1 + neg if neg else 0, 1 + pos
else: pos = neg = 0 # reset
ans = max(ans, pos)
... | https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819332/Python3-7-line-O(N)-time-and-O(1)-space | 59 | Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]... | [Python3] 7-line O(N) time & O(1) space | 2,700 | maximum-length-of-subarray-with-positive-product | 0.438 | ye15 | Medium | 23,107 | 1,567 |
minimum number of days to disconnect island | class Solution:
def minDays(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimension
grid = "".join("".join(map(str, x)) for x in grid)
@lru_cache(None)
def fn(s):
"""Return True if grid is disconnected."""
row, grid = [], []
... | https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/discuss/819360/Python3-bfs | 0 | You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.
The grid is said to be connected if we have exactly one island, otherwise is said disconnected.
In one day, we are allowed to change any single ... | [Python3] bfs | 66 | minimum-number-of-days-to-disconnect-island | 0.468 | ye15 | Hard | 23,132 | 1,568 |
number of ways to reorder array to get same bst | class Solution:
def numOfWays(self, nums: List[int]) -> int:
def fn(nums):
"""Post-order traversal."""
if len(nums) <= 1: return len(nums) # boundary condition
ll = [x for x in nums if x < nums[0]]
rr = [x for x in nums if x > nums[0]]
l... | https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819349/Python3-math-ish | 2 | Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the origi... | [Python3] math-ish | 337 | number-of-ways-to-reorder-array-to-get-same-bst | 0.481 | ye15 | Hard | 23,133 | 1,569 |
matrix diagonal sum | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
"""
The primary diagonal is formed by the elements A00, A11, A22, A33.
Condition for Primary Diagonal:
The row-column condition is row = column.
The secondary diagonal is formed by the elements A03, A12,... | https://leetcode.com/problems/matrix-diagonal-sum/discuss/1369404/PYTHON-Best-solution-with-explanation.-SC-%3A-O(1)-TC-%3A-O(n) | 5 | Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Expla... | [PYTHON] Best solution with explanation. SC : O(1) TC : O(n) | 233 | matrix-diagonal-sum | 0.798 | er1shivam | Easy | 23,135 | 1,572 |
number of ways to split a string | class Solution:
def numWays(self, s: str) -> int:
total = s.count('1')
if total % 3: return 0
n = len(s)
if not total: return (1+n-2) * (n-2) // 2 % 1000000007
avg, ans = total // 3, 0
cnt = first_part_right_zeros = last_part_left_zeros = 0
for i in range(n):
... | https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830700/Python-3-or-Math-(Pass)-Backtracking-(TLE)-or-Explanation | 2 | Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.
Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "10101"
Output: 4
Explanation... | Python 3 | Math (Pass), Backtracking (TLE) | Explanation | 215 | number-of-ways-to-split-a-string | 0.325 | idontknoooo | Medium | 23,188 | 1,573 |
shortest subarray to be removed to make array sorted | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
def lowerbound(left, right, target):
while left < right:
mid = left + (right - left) // 2
if arr[mid] == target:
right = mid
... | https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/835866/Python-Solution-Based-on-Binary-Search | 4 | Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest su... | Python Solution Based on Binary Search | 694 | shortest-subarray-to-be-removed-to-make-array-sorted | 0.366 | pochy | Medium | 23,195 | 1,574 |
count all possible routes | class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
@lru_cache(None)
def fn(n, x):
"""Return all possible routes from n to finish with x fuel."""
if x < 0: return 0 # not going anywhere without fuel
an... | https://leetcode.com/problems/count-all-possible-routes/discuss/831260/Python3-top-down-dp | 3 | You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any... | [Python3] top-down dp | 169 | count-all-possible-routes | 0.568 | ye15 | Hard | 23,203 | 1,575 |
replace all s to avoid consecutive repeating characters | class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for c in "abc":
if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c):
s[i] = c
break ... | https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/831516/Python3-one-of-three-letters | 66 | Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating cha... | [Python3] one of three letters | 3,100 | replace-all-s-to-avoid-consecutive-repeating-characters | 0.491 | ye15 | Easy | 23,205 | 1,576 |
number of ways where square of number is equal to product of two numbers | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
sqr1, sqr2 = defaultdict(int), defaultdict(int)
m, n = len(nums1), len(nums2)
for i in range(m):
sqr1[nums1[i]**2] += 1
for j in range(n):
sqr2[nums2[j]**2] += 1
... | https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1658113/Python-intuitive-hashmap-solution-O(n*m)-time | 2 | Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0... | Python intuitive hashmap solution, O(n*m) time | 114 | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | 0.4 | byuns9334 | Medium | 23,219 | 1,577 |
minimum time to make rope colorful | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
ans = prev = 0 # index of previously retained letter
for i in range(1, len(s)):
if s[prev] != s[i]: prev = i
else:
ans += min(cost[prev], cost[i])
if cost[prev] < cost[i]: pr... | https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/831500/Python3-greedy | 58 | Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it color... | [Python3] greedy | 3,800 | minimum-time-to-make-rope-colorful | 0.637 | ye15 | Medium | 23,224 | 1,578 |
special positions in a binary matrix | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
onesx = []
onesy = []
for ri, rv in enumerate(mat):
for ci, cv in enumerate(rv):
if cv == 1:
onesx.append(ri)
onesy.append(ci)
count = 0
... | https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1802763/Python-Memory-Efficient-Solution | 4 | Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
Example 1:
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
Explanation: (1, 2) is a special posit... | 📌 Python Memory-Efficient Solution | 129 | special-positions-in-a-binary-matrix | 0.654 | croatoan | Easy | 23,278 | 1,582 |
count unhappy friends | class Solution:
def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
def find_preferred_friends(x: int) -> List[int]:
"""
Returns friends of x that have a higher preference than partner.
"""
partner = partners[x] # Find the p... | https://leetcode.com/problems/count-unhappy-friends/discuss/1103620/Readable-python-solution | 3 | You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 t... | Readable python solution | 325 | count-unhappy-friends | 0.603 | alexanco | Medium | 23,299 | 1,583 |
min cost to connect all points | class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
manhattan = lambda p1, p2: abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
n, c = len(points), collections.defaultdict(list)
for i in range(n):
for j in range(i+1, n):
d = manhattan(points[i], poi... | https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/843995/Python-3-or-Min-Spanning-Tree-or-Prim's-Algorithm | 80 | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make a... | Python 3 | Min Spanning Tree | Prim's Algorithm | 13,100 | min-cost-to-connect-all-points | 0.641 | idontknoooo | Medium | 23,308 | 1,584 |
check if string is transformable with substring sort operations | class Solution:
def isTransformable(self, s: str, t: str) -> bool:
if sorted(s) != sorted(t): return False # edge case
pos = [deque() for _ in range(10)]
for i, ss in enumerate(s): pos[int(ss)].append(i)
for tt in t:
i = pos[int(tt)].popleft()
... | https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/844119/Python3-8-line-deque | 2 | Given two strings s and t, transform string s into string t using the following operation any number of times:
Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
For example, applying the operation on the underlined substring in "14234" results in "12344".
Return true if it... | [Python3] 8-line deque | 198 | check-if-string-is-transformable-with-substring-sort-operations | 0.484 | ye15 | Hard | 23,325 | 1,585 |
sum of all odd length subarrays | class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
s=0
for i in range(len(arr)):
for j in range(i,len(arr),2):
s+=sum(arr[i:j+1])
return s | https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/943380/Python-Simple-Solution | 53 | Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
... | Python Simple Solution | 4,100 | sum-of-all-odd-length-subarrays | 0.835 | lokeshsenthilkumar | Easy | 23,326 | 1,588 |
maximum sum obtained of any permutation | class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
chg = [0]*len(nums) # change
for i, j in requests:
chg[i] += 1
if j+1 < len(nums): chg[j+1] -= 1
for i in range(1, len(nums)): chg[i] += chg[i-1] # cumulated change
... | https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/discuss/858448/Python3-mark-and-sweep | 0 | We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums.
Since... | [Python3] mark & sweep | 39 | maximum-sum-obtained-of-any-permutation | 0.37 | ye15 | Medium | 23,377 | 1,589 |
make sum divisible by p | class Solution:
def minSubarray(self, nums: List[int], p: int) -> int:
dp = defaultdict(int)
dp[0] = -1
target = sum(nums) % p
curSum = 0
result = len(nums)
if sum(nums) % p == 0: return 0
for i in range(len(nums)):
curSum += nums[i]
curMod = curSum % p
... | https://leetcode.com/problems/make-sum-divisible-by-p/discuss/1760163/WEEB-DOES-PYTHONC%2B%2B | 2 | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a con... | WEEB DOES PYTHON/C++ | 153 | make-sum-divisible-by-p | 0.28 | Skywalker5423 | Medium | 23,378 | 1,590 |
strange printer ii | class Solution:
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
visited = [0] * 61
graph = collections.defaultdict(set)
m, n = len(targetGrid), len(targetGrid[0])
for c in range(1, 61):
l,r,t,b = n,-1,m,-1
#to specify the covered range of color c
... | https://leetcode.com/problems/strange-printer-ii/discuss/911370/Same-as-CourseSchedule-Topological-sort. | 17 | There is a strange printer with the following two special requirements:
On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
Once the printer has used a color for the above operation, the same color cannot be used again.... | Same as CourseSchedule, Topological sort. | 810 | strange-printer-ii | 0.584 | Sakata_Gintoki | Hard | 23,382 | 1,591 |
rearrange spaces between words | class Solution(object):
def reorderSpaces(self, text):
word_list = text.split()
words, spaces = len(word_list), text.count(" ")
if words > 1:
q, r = spaces//(words-1), spaces%(words-1)
return (" " * q).join(word_list) + " " * r
else:
retur... | https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant | 3 | You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair ... | Python - simple and elegant | 176 | rearrange-spaces-between-words | 0.437 | domthedeveloper | Easy | 23,384 | 1,592 |
split a string into the max number of unique substrings | class Solution:
def maxUniqueSplit(self, s: str) -> int:
ans, n = 0, len(s)
def dfs(i, cnt, visited):
nonlocal ans, n
if i == n: ans = max(ans, cnt); return # stop condition
for j in range(i+1, n+1):
if s[i:j] in visited: continue # avoid... | https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855405/Python-3-or-Backtracking-DFS-clean-or-Explanations | 5 | Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substrin... | Python 3 | Backtracking, DFS, clean | Explanations | 849 | split-a-string-into-the-max-number-of-unique-substrings | 0.55 | idontknoooo | Medium | 23,407 | 1,593 |
maximum non negative product in a matrix | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def fn(i, j):
"""Return maximum & minimum products ending at (i, j)."""
if i == 0 and j == 0: return grid[0][0], grid[0][0]
... | https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855131/Python3-top-down-dp | 36 | You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negativ... | [Python3] top-down dp | 1,800 | maximum-non-negative-product-in-a-matrix | 0.33 | ye15 | Medium | 23,418 | 1,594 |
minimum cost to connect two groups of points | class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
m, n = len(cost), len(cost[0])
mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group
@lru_cache(None)
def fn(i, mask):
"""Return min cost of connecting group1[i:] ... | https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/858187/Python3-top-down-dp | 1 | You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.
The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. ... | [Python3] top-down dp | 169 | minimum-cost-to-connect-two-groups-of-points | 0.463 | ye15 | Hard | 23,429 | 1,595 |
crawler log folder | class Solution:
def minOperations(self, logs: List[str]) -> int:
ans = 0
for log in logs:
if log == "./": continue
elif log == "../": ans = max(0, ans-1) # parent directory
else: ans += 1 # child directory
return ans | https://leetcode.com/problems/crawler-log-folder/discuss/866343/Python3-straightforward | 11 | The Leetcode file system keeps a log each time some user performs a change folder operation.
The operations are described below:
"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
"./" : Remain in the same folder.
"x/" : Move to the child folder ... | [Python3] straightforward | 627 | crawler-log-folder | 0.644 | ye15 | Easy | 23,431 | 1,598 |
maximum profit of operating a centennial wheel | class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
ans = -1
most = pnl = waiting = 0
for i, x in enumerate(customers):
waiting += x # more people waiting in line
waiting -= (chg := min(4, waiting)) # b... | https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866356/Python3-simulation | 5 | You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.
You are given an array customers of length n where customers[i] is the number of new customers arriving j... | [Python3] simulation | 381 | maximum-profit-of-operating-a-centennial-wheel | 0.436 | ye15 | Medium | 23,460 | 1,599 |
maximum number of achievable transfer requests | class Solution:
def maximumRequests(self, n: int, req: List[List[int]]) -> int:
tot = len(req)
for i in range(tot, 0, -1):
comb = list(itertools.combinations([j for j in range(tot)], i))
for c in comb:
net = [0 for j in range(n)]
for idx in c:
... | https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866369/Python3-10-Lines-Bitmasking-or-Combinations-or-Easy-Explanation | 17 | We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.
A... | [Python3] 10 Lines Bitmasking | Combinations | Easy Explanation | 1,000 | maximum-number-of-achievable-transfer-requests | 0.513 | uds5501 | Hard | 23,463 | 1,601 |
alert using same key card three or more times in a one hour period | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
key_time = {}
for index, name in enumerate(keyName):
key_time[name] = key_time.get(name, [])
key_time[name].append(int(keyTime[index].replace(":", "")))
ans = []
for nam... | https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1284866/Python3-or-Dict-%2B-Sort | 3 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName an... | Python3 | Dict + Sort | 314 | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | 0.473 | Sanjaychandak95 | Medium | 23,465 | 1,604 |
find valid matrix given row and column sums | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
def backtrack(y, x):
choice = min(rowSum[y], colSum[x])
result[y][x] = choice
rowSum[y] -= choice
colSum[x] -= choice
if y == 0 and x == 0:
... | https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1734833/Python-or-Backtracking | 1 | You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any m... | Python | Backtracking | 102 | find-valid-matrix-given-row-and-column-sums | 0.78 | holdenkold | Medium | 23,473 | 1,605 |
find servers that handled most number of requests | class Solution:
def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
busy = [] # min-heap
free = list(range(k)) # min-heap
freq = [0]*k
for i, (ta, tl) in enumerate(zip(arrival, load)):
while busy and busy[0][0] <= ta:
... | https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/1089184/Python3-summarizing-3-approaches | 13 | You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:
The ith (0-indexed) request arrives.
If all... | [Python3] summarizing 3 approaches | 641 | find-servers-that-handled-most-number-of-requests | 0.429 | ye15 | Hard | 23,483 | 1,606 |
special array with x elements greater than or equal x | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if n<=nums[0]:
return n
for i in range(1,n):
count = n-i #counts number of elements in nums greater than equal i
if nums[i]>=(count) and (coun... | https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1527669/Python-or-Faster-than-94-or-2-methods-or-O(nlogn) | 5 | You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Notice that x does not have to be an element in nums.
Return x if the array is special, otherwise, return -1. It can be proven th... | Python | Faster than 94% | 2 methods | O(nlogn) | 531 | special-array-with-x-elements-greater-than-or-equal-x | 0.601 | ana_2kacer | Easy | 23,484 | 1,608 |
even odd tree | class Solution:
def isEvenOddTree(self, root: TreeNode) -> bool:
even = 1 # even level
queue = deque([root])
while queue:
newq = []
prev = -inf if even else inf
for _ in range(len(queue)):
node = queue.popleft()
if even a... | https://leetcode.com/problems/even-odd-tree/discuss/877858/Python3-bfs-by-level | 1 | A binary tree is named Even-Odd if it meets the following conditions:
The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to righ... | [Python3] bfs by level | 103 | even-odd-tree | 0.538 | ye15 | Medium | 23,519 | 1,609 |
maximum number of visible points | class Solution:
def visiblePoints(self, points: List[List[int]], angle: int, l: List[int]) -> int:
array = []
nloc = 0
for p in points:
if p == l:
nloc += 1
else:
array.append(math.degrees(atan2(p[1]-l[1], p[0]-l[0])))
... | https://leetcode.com/problems/maximum-number-of-visible-points/discuss/1502236/Python-Clean-Sliding-Window | 1 | You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy ... | [Python] Clean Sliding Window | 669 | maximum-number-of-visible-points | 0.374 | soma28 | Hard | 23,527 | 1,610 |
minimum one bit operations to make integers zero | class Solution:
def minimumOneBitOperations(self, n: int) -> int:
"""
to flip the bits to turn the number to zero
Interpretation of Rules:
- recursive:
to turn a leading one of i bits to zero, the only way is to turn the i-1 bits to a leading one pattern
... | https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/2273798/Easy-to-understand-6-line-solution-with-explanation-or-O(N)-time-O(1)-space | 2 | Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum num... | Easy to understand 6-line solution with explanation | O(N) time O(1) space | 370 | minimum-one-bit-operations-to-make-integers-zero | 0.634 | zhenyulin | Hard | 23,528 | 1,611 |
maximum nesting depth of the parentheses | class Solution:
def maxDepth(self, s: str) -> int:
depths = [0]
count = 0
for i in s:
if(i == '('):
count += 1
elif(i == ')'):
count -= 1
depths.append(count)
return max(depths) | https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1171599/Python3-Simple-And-Readable-Solution | 7 | Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation:
Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Explanation:... | [Python3] Simple And Readable Solution | 258 | maximum-nesting-depth-of-the-parentheses | 0.827 | VoidCupboard | Easy | 23,531 | 1,614 |
maximal network rank | class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
graph = {}
for u, v in roads:
graph.setdefault(u, set()).add(v)
graph.setdefault(v, set()).add(u)
ans = 0
for i in range(n):
for j in range(i+1, n):
... | https://leetcode.com/problems/maximal-network-rank/discuss/888965/Python3-graph-as-adjacency-list | 8 | There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is direc... | [Python3] graph as adjacency list | 1,100 | maximal-network-rank | 0.581 | ye15 | Medium | 23,568 | 1,615 |
split two strings to make palindrome | class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
fn = lambda x: x == x[::-1] # check for palindrome
i = 0
while i < len(a) and a[i] == b[~i]: i += 1
if fn(a[:i] + b[i:]) or fn(a[:-i] + b[-i:]): return True
i = 0
... | https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/888981/Python3-greedy | 6 | You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffi... | [Python3] greedy | 299 | split-two-strings-to-make-palindrome | 0.314 | ye15 | Medium | 23,577 | 1,616 |
count subtrees with max distance between cities | class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
# Create Tree as adjacency list
neigh: List[List[int]] = [[] for _ in range(n)]
for u, v in edges:
neigh[u - 1].append(v - 1)
neigh[v - 1].append(u - 1)
dist... | https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/1068298/Python-Top-Down-DP-O(n5).-35-ms-and-faster-than-100-explained | 2 | There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is reach... | [Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained | 137 | count-subtrees-with-max-distance-between-cities | 0.657 | kcsquared | Hard | 23,584 | 1,617 |
mean of array after removing some elements | class Solution:
def trimMean(self, arr: List[int]) -> float:
arr.sort()
return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)]) | https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1193688/2-easy-Python-Solutions | 6 | Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
Answers within 10-5 of the actual answer will be considered accepted.
Example 1:
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing th... | 2 easy Python Solutions | 617 | mean-of-array-after-removing-some-elements | 0.647 | ayushi7rawat | Easy | 23,587 | 1,619 |
coordinate with maximum network quality | class Solution:
def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:
mx = -inf
for x in range(51):
for y in range(51):
val = 0
for xi, yi, qi in towers:
d = sqrt((x-xi)**2 + (y-yi)**2)
if d ... | https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/1103762/Python3-enumerate-all-candidates | 2 | You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.
You are also given an integer... | [Python3] enumerate all candidates | 143 | coordinate-with-maximum-network-quality | 0.376 | ye15 | Medium | 23,615 | 1,620 |
number of sets of k non overlapping line segments | class Solution:
def numberOfSets(self, n: int, k: int) -> int:
@cache
def fn(n, k):
"""Return number of sets."""
if n <= k: return 0
if k == 0: return 1
return 2*fn(n-1, k) + fn(n-1, k-1) - fn(n-2, k)
return fn(n, k) % 1_000_... | https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/discuss/1103787/Python3-top-down-dp | 1 | Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n point... | [Python3] top-down dp | 141 | number-of-sets-of-k-non-overlapping-line-segments | 0.422 | ye15 | Medium | 23,617 | 1,621 |
largest substring between two equal characters | class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
ans = -1
seen = {}
for i, c in enumerate(s):
if c in seen: ans = max(ans, i - seen[c] - 1)
seen.setdefault(c, i)
return ans | https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/899540/Python3-via-dictionary | 13 | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty... | [Python3] via dictionary | 710 | largest-substring-between-two-equal-characters | 0.591 | ye15 | Easy | 23,618 | 1,624 |
lexicographically smallest string after applying operations | class Solution:
def findLexSmallestString(self, s: str, a: int, b: int) -> str:
op1 = lambda s: "".join(str((int(c)+a)%10) if i&1 else c for i, c in enumerate(s))
op2 = lambda s: s[-b:] + s[:-b]
seen = set()
stack = [s]
while stack:
s = stack.pop()
... | https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899547/Python3-dfs | 7 | You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.
You can apply either of the following two operations any number of times and in any order on s:
Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becom... | [Python3] dfs | 384 | lexicographically-smallest-string-after-applying-operations | 0.66 | ye15 | Medium | 23,634 | 1,625 |
best team with no conflicts | class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
'''
Using example scores = [1,2,3,5] and ages = [8,9,10,1]
data is [(1, 5), (8, 1), (9, 2), (10, 3)]
and dp is [5, 1, 2, 3]
when curr player is (1, 5)
there are... | https://leetcode.com/problems/best-team-with-no-conflicts/discuss/2848106/Python-Heavily-commented-to-self-understand-first-of-all-DP-2-Loops | 0 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictl... | [Python] Heavily commented to self understand first of all - DP 2 Loops | 1 | best-team-with-no-conflicts | 0.412 | graceiscoding | Medium | 23,638 | 1,626 |
slowest key | class Solution:
def slowestKey(self, r: List[int], k: str) -> str:
times = {r[0]: [k[0]]}
for i in range(1 , len(r)):
t = r[i] - r[i - 1]
if(t in times):
times[t].append(k[i])
else:
times[t] = [k[i]]
keys =... | https://leetcode.com/problems/slowest-key/discuss/1172372/Python3-Simple-And-Readable-Solution | 7 | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays a... | [Python3] Simple And Readable Solution | 337 | slowest-key | 0.593 | VoidCupboard | Easy | 23,642 | 1,629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.